codemirror-python.js 13 KB

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