python.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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.version && parseInt(parserConf.version, 10) === 3) {
  36. commonkeywords = commonkeywords.concat(py3.keywords);
  37. commonBuiltins = commonBuiltins.concat(py3.builtins);
  38. var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
  39. } else {
  40. commonkeywords = commonkeywords.concat(py2.keywords);
  41. commonBuiltins = commonBuiltins.concat(py2.builtins);
  42. var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
  43. }
  44. var keywords = wordRegexp(commonkeywords);
  45. var builtins = wordRegexp(commonBuiltins);
  46. var indentInfo = null;
  47. // tokenizers
  48. function tokenBase(stream, state) {
  49. // Handle scope changes
  50. if (stream.sol()) {
  51. var scopeOffset = state.scopes[0].offset;
  52. if (stream.eatSpace()) {
  53. var lineOffset = stream.indentation();
  54. if (lineOffset > scopeOffset) {
  55. indentInfo = 'indent';
  56. } else if (lineOffset < scopeOffset) {
  57. indentInfo = 'dedent';
  58. }
  59. return null;
  60. } else {
  61. if (scopeOffset > 0) {
  62. dedent(stream, state);
  63. }
  64. }
  65. }
  66. if (stream.eatSpace()) {
  67. return null;
  68. }
  69. var ch = stream.peek();
  70. // Handle Comments
  71. if (ch === '#') {
  72. stream.skipToEnd();
  73. return 'comment';
  74. }
  75. // Handle Number Literals
  76. if (stream.match(/^[0-9\.]/, false)) {
  77. var floatLiteral = false;
  78. // Floats
  79. if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
  80. if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
  81. if (stream.match(/^\.\d+/)) { floatLiteral = true; }
  82. if (floatLiteral) {
  83. // Float literals may be "imaginary"
  84. stream.eat(/J/i);
  85. return 'number';
  86. }
  87. // Integers
  88. var intLiteral = false;
  89. // Hex
  90. if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
  91. // Binary
  92. if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
  93. // Octal
  94. if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
  95. // Decimal
  96. if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
  97. // Decimal literals may be "imaginary"
  98. stream.eat(/J/i);
  99. // TODO - Can you have imaginary longs?
  100. intLiteral = true;
  101. }
  102. // Zero by itself with no other piece of number.
  103. if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
  104. if (intLiteral) {
  105. // Integer literals may be "long"
  106. stream.eat(/L/i);
  107. return 'number';
  108. }
  109. }
  110. // Handle Strings
  111. if (stream.match(stringPrefixes)) {
  112. state.tokenize = tokenStringFactory(stream.current());
  113. return state.tokenize(stream, state);
  114. }
  115. // Handle operators and Delimiters
  116. if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
  117. return null;
  118. }
  119. if (stream.match(doubleOperators)
  120. || stream.match(singleOperators)
  121. || stream.match(wordOperators)) {
  122. return 'operator';
  123. }
  124. if (stream.match(singleDelimiters)) {
  125. return null;
  126. }
  127. if (stream.match(keywords)) {
  128. return 'keyword';
  129. }
  130. if (stream.match(builtins)) {
  131. return 'builtin';
  132. }
  133. if (stream.match(identifiers)) {
  134. return 'variable';
  135. }
  136. // Handle non-detected items
  137. stream.next();
  138. return ERRORCLASS;
  139. }
  140. function tokenStringFactory(delimiter) {
  141. while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
  142. delimiter = delimiter.substr(1);
  143. }
  144. var singleline = delimiter.length == 1;
  145. var OUTCLASS = 'string';
  146. function tokenString(stream, state) {
  147. while (!stream.eol()) {
  148. stream.eatWhile(/[^'"\\]/);
  149. if (stream.eat('\\')) {
  150. stream.next();
  151. if (singleline && stream.eol()) {
  152. return OUTCLASS;
  153. }
  154. } else if (stream.match(delimiter)) {
  155. state.tokenize = tokenBase;
  156. return OUTCLASS;
  157. } else {
  158. stream.eat(/['"]/);
  159. }
  160. }
  161. if (singleline) {
  162. if (parserConf.singleLineStringErrors) {
  163. return ERRORCLASS;
  164. } else {
  165. state.tokenize = tokenBase;
  166. }
  167. }
  168. return OUTCLASS;
  169. }
  170. tokenString.isString = true;
  171. return tokenString;
  172. }
  173. function indent(stream, state, type) {
  174. type = type || 'py';
  175. var indentUnit = 0;
  176. if (type === 'py') {
  177. if (state.scopes[0].type !== 'py') {
  178. state.scopes[0].offset = stream.indentation();
  179. return;
  180. }
  181. for (var i = 0; i < state.scopes.length; ++i) {
  182. if (state.scopes[i].type === 'py') {
  183. indentUnit = state.scopes[i].offset + conf.indentUnit;
  184. break;
  185. }
  186. }
  187. } else {
  188. indentUnit = stream.column() + stream.current().length;
  189. }
  190. state.scopes.unshift({
  191. offset: indentUnit,
  192. type: type
  193. });
  194. }
  195. function dedent(stream, state, type) {
  196. type = type || 'py';
  197. if (state.scopes.length == 1) return;
  198. if (state.scopes[0].type === 'py') {
  199. var _indent = stream.indentation();
  200. var _indent_index = -1;
  201. for (var i = 0; i < state.scopes.length; ++i) {
  202. if (_indent === state.scopes[i].offset) {
  203. _indent_index = i;
  204. break;
  205. }
  206. }
  207. if (_indent_index === -1) {
  208. return true;
  209. }
  210. while (state.scopes[0].offset !== _indent) {
  211. state.scopes.shift();
  212. }
  213. return false;
  214. } else {
  215. if (type === 'py') {
  216. state.scopes[0].offset = stream.indentation();
  217. return false;
  218. } else {
  219. if (state.scopes[0].type != type) {
  220. return true;
  221. }
  222. state.scopes.shift();
  223. return false;
  224. }
  225. }
  226. }
  227. function tokenLexer(stream, state) {
  228. indentInfo = null;
  229. var style = state.tokenize(stream, state);
  230. var current = stream.current();
  231. // Handle '.' connected identifiers
  232. if (current === '.') {
  233. style = stream.match(identifiers, false) ? null : ERRORCLASS;
  234. if (style === null && state.lastToken === 'meta') {
  235. // Apply 'meta' style to '.' connected identifiers when
  236. // appropriate.
  237. style = 'meta';
  238. }
  239. return style;
  240. }
  241. // Handle decorators
  242. if (current === '@') {
  243. return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;
  244. }
  245. if ((style === 'variable' || style === 'builtin')
  246. && state.lastToken === 'meta') {
  247. style = 'meta';
  248. }
  249. // Handle scope changes.
  250. if (current === 'pass' || current === 'return') {
  251. state.dedent += 1;
  252. }
  253. if (current === 'lambda') state.lambda = true;
  254. if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
  255. || indentInfo === 'indent') {
  256. indent(stream, state);
  257. }
  258. var delimiter_index = '[({'.indexOf(current);
  259. if (delimiter_index !== -1) {
  260. indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
  261. }
  262. if (indentInfo === 'dedent') {
  263. if (dedent(stream, state)) {
  264. return ERRORCLASS;
  265. }
  266. }
  267. delimiter_index = '])}'.indexOf(current);
  268. if (delimiter_index !== -1) {
  269. if (dedent(stream, state, current)) {
  270. return ERRORCLASS;
  271. }
  272. }
  273. if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
  274. if (state.scopes.length > 1) state.scopes.shift();
  275. state.dedent -= 1;
  276. }
  277. return style;
  278. }
  279. var external = {
  280. startState: function(basecolumn) {
  281. return {
  282. tokenize: tokenBase,
  283. scopes: [{offset:basecolumn || 0, type:'py'}],
  284. lastToken: null,
  285. lambda: false,
  286. dedent: 0
  287. };
  288. },
  289. token: function(stream, state) {
  290. var style = tokenLexer(stream, state);
  291. state.lastToken = style;
  292. if (stream.eol() && stream.lambda) {
  293. state.lambda = false;
  294. }
  295. return style;
  296. },
  297. indent: function(state) {
  298. if (state.tokenize != tokenBase) {
  299. return state.tokenize.isString ? CodeMirror.Pass : 0;
  300. }
  301. return state.scopes[0].offset;
  302. },
  303. lineComment: "#"
  304. };
  305. return external;
  306. });
  307. CodeMirror.defineMIME("text/x-python", "python");