python.js 13KB

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