python.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. (function(mod) {
  2. if (typeof exports == "object" && typeof module == "object") // CommonJS
  3. mod(require("../../lib/codemirror"));
  4. else if (typeof define == "function" && define.amd) // AMD
  5. define(["../../lib/codemirror"], mod);
  6. else // Plain browser env
  7. mod(CodeMirror);
  8. })(function(CodeMirror) {
  9. "use strict";
  10. CodeMirror.defineMode("python", function(conf, parserConf) {
  11. var ERRORCLASS = 'error';
  12. function wordRegexp(words) {
  13. return new RegExp("^((" + words.join(")|(") + "))\\b");
  14. }
  15. var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
  16. var singleDelimiters = parserConf.singleDelimiters || new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
  17. var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
  18. var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
  19. var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
  20. var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
  21. var hangingIndent = parserConf.hangingIndent || parserConf.indentUnit;
  22. var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
  23. var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
  24. 'def', 'del', 'elif', 'else', 'except', 'finally',
  25. 'for', 'from', 'global', 'if', 'import',
  26. 'lambda', 'pass', 'raise', 'return',
  27. 'try', 'while', 'with', 'yield'];
  28. var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr',
  29. 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
  30. 'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset',
  31. 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
  32. 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
  33. 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
  34. 'object', 'oct', 'open', 'ord', 'pow', 'property', 'range',
  35. 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
  36. 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
  37. 'type', 'vars', 'zip', '__import__', 'NotImplemented',
  38. 'Ellipsis', '__debug__'];
  39. var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile',
  40. 'file', 'intern', 'long', 'raw_input', 'reduce', 'reload',
  41. 'unichr', 'unicode', 'xrange', 'False', 'True', 'None'],
  42. 'keywords': ['exec', 'print']};
  43. var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'],
  44. 'keywords': ['nonlocal', 'False', 'True', 'None']};
  45. if(parserConf.extra_keywords != undefined){
  46. commonkeywords = commonkeywords.concat(parserConf.extra_keywords);
  47. }
  48. if(parserConf.extra_builtins != undefined){
  49. commonBuiltins = commonBuiltins.concat(parserConf.extra_builtins);
  50. }
  51. if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
  52. commonkeywords = commonkeywords.concat(py3.keywords);
  53. commonBuiltins = commonBuiltins.concat(py3.builtins);
  54. var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
  55. } else {
  56. commonkeywords = commonkeywords.concat(py2.keywords);
  57. commonBuiltins = commonBuiltins.concat(py2.builtins);
  58. var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
  59. }
  60. var keywords = wordRegexp(commonkeywords);
  61. var builtins = wordRegexp(commonBuiltins);
  62. var indentInfo = null;
  63. // tokenizers
  64. function tokenBase(stream, state) {
  65. // Handle scope changes
  66. if (stream.sol()) {
  67. var scopeOffset = state.scopes[0].offset;
  68. if (stream.eatSpace()) {
  69. var lineOffset = stream.indentation();
  70. if (lineOffset > scopeOffset) {
  71. indentInfo = 'indent';
  72. } else if (lineOffset < scopeOffset) {
  73. indentInfo = 'dedent';
  74. }
  75. return null;
  76. } else {
  77. if (scopeOffset > 0) {
  78. dedent(stream, state);
  79. }
  80. }
  81. }
  82. if (stream.eatSpace()) {
  83. return null;
  84. }
  85. var ch = stream.peek();
  86. // Handle Comments
  87. if (ch === '#') {
  88. stream.skipToEnd();
  89. return 'comment';
  90. }
  91. // Handle Number Literals
  92. if (stream.match(/^[0-9\.]/, false)) {
  93. var floatLiteral = false;
  94. // Floats
  95. if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
  96. if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
  97. if (stream.match(/^\.\d+/)) { floatLiteral = true; }
  98. if (floatLiteral) {
  99. // Float literals may be "imaginary"
  100. stream.eat(/J/i);
  101. return 'number';
  102. }
  103. // Integers
  104. var intLiteral = false;
  105. // Hex
  106. if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
  107. // Binary
  108. if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
  109. // Octal
  110. if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
  111. // Decimal
  112. if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
  113. // Decimal literals may be "imaginary"
  114. stream.eat(/J/i);
  115. // TODO - Can you have imaginary longs?
  116. intLiteral = true;
  117. }
  118. // Zero by itself with no other piece of number.
  119. if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
  120. if (intLiteral) {
  121. // Integer literals may be "long"
  122. stream.eat(/L/i);
  123. return 'number';
  124. }
  125. }
  126. // Handle Strings
  127. if (stream.match(stringPrefixes)) {
  128. state.tokenize = tokenStringFactory(stream.current());
  129. return state.tokenize(stream, state);
  130. }
  131. // Handle operators and Delimiters
  132. if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
  133. return null;
  134. }
  135. if (stream.match(doubleOperators)
  136. || stream.match(singleOperators)
  137. || stream.match(wordOperators)) {
  138. return 'operator';
  139. }
  140. if (stream.match(singleDelimiters)) {
  141. return null;
  142. }
  143. if (stream.match(keywords)) {
  144. return 'keyword';
  145. }
  146. if (stream.match(builtins)) {
  147. return 'builtin';
  148. }
  149. if (stream.match(/^(self|cls)\b/)) {
  150. return "variable-2";
  151. }
  152. if (stream.match(identifiers)) {
  153. if (state.lastToken == 'def' || state.lastToken == 'class') {
  154. return 'def';
  155. }
  156. return 'variable';
  157. }
  158. // Handle non-detected items
  159. stream.next();
  160. return ERRORCLASS;
  161. }
  162. function tokenStringFactory(delimiter) {
  163. while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
  164. delimiter = delimiter.substr(1);
  165. }
  166. var singleline = delimiter.length == 1;
  167. var OUTCLASS = 'string';
  168. function tokenString(stream, state) {
  169. while (!stream.eol()) {
  170. stream.eatWhile(/[^'"\\]/);
  171. if (stream.eat('\\')) {
  172. stream.next();
  173. if (singleline && stream.eol()) {
  174. return OUTCLASS;
  175. }
  176. } else if (stream.match(delimiter)) {
  177. state.tokenize = tokenBase;
  178. return OUTCLASS;
  179. } else {
  180. stream.eat(/['"]/);
  181. }
  182. }
  183. if (singleline) {
  184. if (parserConf.singleLineStringErrors) {
  185. return ERRORCLASS;
  186. } else {
  187. state.tokenize = tokenBase;
  188. }
  189. }
  190. return OUTCLASS;
  191. }
  192. tokenString.isString = true;
  193. return tokenString;
  194. }
  195. function indent(stream, state, type) {
  196. type = type || 'py';
  197. var indentUnit = 0;
  198. if (type === 'py') {
  199. if (state.scopes[0].type !== 'py') {
  200. state.scopes[0].offset = stream.indentation();
  201. return;
  202. }
  203. for (var i = 0; i < state.scopes.length; ++i) {
  204. if (state.scopes[i].type === 'py') {
  205. indentUnit = state.scopes[i].offset + conf.indentUnit;
  206. break;
  207. }
  208. }
  209. } else if (stream.match(/\s*($|#)/, false)) {
  210. // An open paren/bracket/brace with only space or comments after it
  211. // on the line will indent the next line a fixed amount, to make it
  212. // easier to put arguments, list items, etc. on their own lines.
  213. indentUnit = stream.indentation() + hangingIndent;
  214. } else {
  215. indentUnit = stream.column() + stream.current().length;
  216. }
  217. state.scopes.unshift({
  218. offset: indentUnit,
  219. type: type
  220. });
  221. }
  222. function dedent(stream, state, type) {
  223. type = type || 'py';
  224. if (state.scopes.length == 1) return;
  225. if (state.scopes[0].type === 'py') {
  226. var _indent = stream.indentation();
  227. var _indent_index = -1;
  228. for (var i = 0; i < state.scopes.length; ++i) {
  229. if (_indent === state.scopes[i].offset) {
  230. _indent_index = i;
  231. break;
  232. }
  233. }
  234. if (_indent_index === -1) {
  235. return true;
  236. }
  237. while (state.scopes[0].offset !== _indent) {
  238. state.scopes.shift();
  239. }
  240. return false;
  241. } else {
  242. if (type === 'py') {
  243. state.scopes[0].offset = stream.indentation();
  244. return false;
  245. } else {
  246. if (state.scopes[0].type != type) {
  247. return true;
  248. }
  249. state.scopes.shift();
  250. return false;
  251. }
  252. }
  253. }
  254. function tokenLexer(stream, state) {
  255. indentInfo = null;
  256. var style = state.tokenize(stream, state);
  257. var current = stream.current();
  258. // Handle '.' connected identifiers
  259. if (current === '.') {
  260. style = stream.match(identifiers, false) ? null : ERRORCLASS;
  261. if (style === null && state.lastStyle === 'meta') {
  262. // Apply 'meta' style to '.' connected identifiers when
  263. // appropriate.
  264. style = 'meta';
  265. }
  266. return style;
  267. }
  268. // Handle decorators
  269. if (current === '@') {
  270. return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;
  271. }
  272. if ((style === 'variable' || style === 'builtin')
  273. && state.lastStyle === 'meta') {
  274. style = 'meta';
  275. }
  276. // Handle scope changes.
  277. if (current === 'pass' || current === 'return') {
  278. state.dedent += 1;
  279. }
  280. if (current === 'lambda') state.lambda = true;
  281. if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
  282. || indentInfo === 'indent') {
  283. indent(stream, state);
  284. }
  285. var delimiter_index = '[({'.indexOf(current);
  286. if (delimiter_index !== -1) {
  287. indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
  288. }
  289. if (indentInfo === 'dedent') {
  290. if (dedent(stream, state)) {
  291. return ERRORCLASS;
  292. }
  293. }
  294. delimiter_index = '])}'.indexOf(current);
  295. if (delimiter_index !== -1) {
  296. if (dedent(stream, state, current)) {
  297. return ERRORCLASS;
  298. }
  299. }
  300. if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
  301. if (state.scopes.length > 1) state.scopes.shift();
  302. state.dedent -= 1;
  303. }
  304. return style;
  305. }
  306. var external = {
  307. startState: function(basecolumn) {
  308. return {
  309. tokenize: tokenBase,
  310. scopes: [{offset:basecolumn || 0, type:'py'}],
  311. lastStyle: null,
  312. lastToken: null,
  313. lambda: false,
  314. dedent: 0
  315. };
  316. },
  317. token: function(stream, state) {
  318. var style = tokenLexer(stream, state);
  319. state.lastStyle = style;
  320. var current = stream.current();
  321. if (current && style) {
  322. state.lastToken = current;
  323. }
  324. if (stream.eol() && state.lambda) {
  325. state.lambda = false;
  326. }
  327. return style;
  328. },
  329. indent: function(state) {
  330. if (state.tokenize != tokenBase) {
  331. return state.tokenize.isString ? CodeMirror.Pass : 0;
  332. }
  333. return state.scopes[0].offset;
  334. },
  335. lineComment: "#",
  336. fold: "indent"
  337. };
  338. return external;
  339. });
  340. CodeMirror.defineMIME("text/x-python", "python");
  341. var words = function(str){return str.split(' ');};
  342. CodeMirror.defineMIME("text/x-cython", {
  343. name: "python",
  344. extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
  345. "extern gil include nogil property public"+
  346. "readonly struct union DEF IF ELIF ELSE")
  347. });
  348. });