python.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. (function(mod) {
  4. if (typeof exports == "object" && typeof module == "object") // CommonJS
  5. mod(require("../../lib/codemirror"));
  6. else if (typeof define == "function" && define.amd) // AMD
  7. define(["../../lib/codemirror"], mod);
  8. else // Plain browser env
  9. mod(CodeMirror);
  10. })(function(CodeMirror) {
  11. "use strict";
  12. function wordRegexp(words) {
  13. return new RegExp("^((" + words.join(")|(") + "))\\b");
  14. }
  15. var wordOperators = wordRegexp(["and", "or", "not", "is"]);
  16. var commonKeywords = ["as", "assert", "break", "class", "continue",
  17. "def", "del", "elif", "else", "except", "finally",
  18. "for", "from", "global", "if", "import",
  19. "lambda", "pass", "raise", "return",
  20. "try", "while", "with", "yield", "in"];
  21. var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
  22. "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
  23. "enumerate", "eval", "filter", "float", "format", "frozenset",
  24. "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
  25. "input", "int", "isinstance", "issubclass", "iter", "len",
  26. "list", "locals", "map", "max", "memoryview", "min", "next",
  27. "object", "oct", "open", "ord", "pow", "property", "range",
  28. "repr", "reversed", "round", "set", "setattr", "slice",
  29. "sorted", "staticmethod", "str", "sum", "super", "tuple",
  30. "type", "vars", "zip", "__import__", "NotImplemented",
  31. "Ellipsis", "__debug__"];
  32. CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));
  33. function top(state) {
  34. return state.scopes[state.scopes.length - 1];
  35. }
  36. CodeMirror.defineMode("python", function(conf, parserConf) {
  37. var ERRORCLASS = "error";
  38. var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.]/;
  39. // (Backwards-compatiblity with old, cumbersome config system)
  40. var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,
  41. parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@])/]
  42. for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)
  43. var hangingIndent = parserConf.hangingIndent || conf.indentUnit;
  44. var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
  45. if (parserConf.extra_keywords != undefined)
  46. myKeywords = myKeywords.concat(parserConf.extra_keywords);
  47. if (parserConf.extra_builtins != undefined)
  48. myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
  49. var py3 = !(parserConf.version && Number(parserConf.version) < 3)
  50. if (py3) {
  51. // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
  52. var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
  53. myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);
  54. myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
  55. var stringPrefixes = new RegExp("^(([rbuf]|(br))?('{3}|\"{3}|['\"]))", "i");
  56. } else {
  57. var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;
  58. myKeywords = myKeywords.concat(["exec", "print"]);
  59. myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
  60. "file", "intern", "long", "raw_input", "reduce", "reload",
  61. "unichr", "unicode", "xrange", "False", "True", "None"]);
  62. var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
  63. }
  64. var keywords = wordRegexp(myKeywords);
  65. var builtins = wordRegexp(myBuiltins);
  66. // tokenizers
  67. function tokenBase(stream, state) {
  68. if (stream.sol()) state.indent = stream.indentation()
  69. // Handle scope changes
  70. if (stream.sol() && top(state).type == "py") {
  71. var scopeOffset = top(state).offset;
  72. if (stream.eatSpace()) {
  73. var lineOffset = stream.indentation();
  74. if (lineOffset > scopeOffset)
  75. pushPyScope(state);
  76. else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")
  77. state.errorToken = true;
  78. return null;
  79. } else {
  80. var style = tokenBaseInner(stream, state);
  81. if (scopeOffset > 0 && dedent(stream, state))
  82. style += " " + ERRORCLASS;
  83. return style;
  84. }
  85. }
  86. return tokenBaseInner(stream, state);
  87. }
  88. function tokenBaseInner(stream, state) {
  89. if (stream.eatSpace()) return null;
  90. var ch = stream.peek();
  91. // Handle Comments
  92. if (ch == "#") {
  93. stream.skipToEnd();
  94. return "comment";
  95. }
  96. // Handle Number Literals
  97. if (stream.match(/^[0-9\.]/, false)) {
  98. var floatLiteral = false;
  99. // Floats
  100. if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
  101. if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
  102. if (stream.match(/^\.\d+/)) { floatLiteral = true; }
  103. if (floatLiteral) {
  104. // Float literals may be "imaginary"
  105. stream.eat(/J/i);
  106. return "number";
  107. }
  108. // Integers
  109. var intLiteral = false;
  110. // Hex
  111. if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
  112. // Binary
  113. if (stream.match(/^0b[01_]+/i)) intLiteral = true;
  114. // Octal
  115. if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
  116. // Decimal
  117. if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
  118. // Decimal literals may be "imaginary"
  119. stream.eat(/J/i);
  120. // TODO - Can you have imaginary longs?
  121. intLiteral = true;
  122. }
  123. // Zero by itself with no other piece of number.
  124. if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
  125. if (intLiteral) {
  126. // Integer literals may be "long"
  127. stream.eat(/L/i);
  128. return "number";
  129. }
  130. }
  131. // Handle Strings
  132. if (stream.match(stringPrefixes)) {
  133. state.tokenize = tokenStringFactory(stream.current());
  134. return state.tokenize(stream, state);
  135. }
  136. for (var i = 0; i < operators.length; i++)
  137. if (stream.match(operators[i])) return "operator"
  138. if (stream.match(delimiters)) return "punctuation";
  139. if (state.lastToken == "." && stream.match(identifiers))
  140. return "property";
  141. if (stream.match(keywords) || stream.match(wordOperators))
  142. return "keyword";
  143. if (stream.match(builtins))
  144. return "builtin";
  145. if (stream.match(/^(self|cls)\b/))
  146. return "variable-2";
  147. if (stream.match(identifiers)) {
  148. if (state.lastToken == "def" || state.lastToken == "class")
  149. return "def";
  150. return "variable";
  151. }
  152. // Handle non-detected items
  153. stream.next();
  154. return ERRORCLASS;
  155. }
  156. function tokenStringFactory(delimiter) {
  157. while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
  158. delimiter = delimiter.substr(1);
  159. var singleline = delimiter.length == 1;
  160. var OUTCLASS = "string";
  161. function tokenString(stream, state) {
  162. while (!stream.eol()) {
  163. stream.eatWhile(/[^'"\\]/);
  164. if (stream.eat("\\")) {
  165. stream.next();
  166. if (singleline && stream.eol())
  167. return OUTCLASS;
  168. } else if (stream.match(delimiter)) {
  169. state.tokenize = tokenBase;
  170. return OUTCLASS;
  171. } else {
  172. stream.eat(/['"]/);
  173. }
  174. }
  175. if (singleline) {
  176. if (parserConf.singleLineStringErrors)
  177. return ERRORCLASS;
  178. else
  179. state.tokenize = tokenBase;
  180. }
  181. return OUTCLASS;
  182. }
  183. tokenString.isString = true;
  184. return tokenString;
  185. }
  186. function pushPyScope(state) {
  187. while (top(state).type != "py") state.scopes.pop()
  188. state.scopes.push({offset: top(state).offset + conf.indentUnit,
  189. type: "py",
  190. align: null})
  191. }
  192. function pushBracketScope(stream, state, type) {
  193. var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1
  194. state.scopes.push({offset: state.indent + hangingIndent,
  195. type: type,
  196. align: align})
  197. }
  198. function dedent(stream, state) {
  199. var indented = stream.indentation();
  200. while (state.scopes.length > 1 && top(state).offset > indented) {
  201. if (top(state).type != "py") return true;
  202. state.scopes.pop();
  203. }
  204. return top(state).offset != indented;
  205. }
  206. function tokenLexer(stream, state) {
  207. if (stream.sol()) state.beginningOfLine = true;
  208. var style = state.tokenize(stream, state);
  209. var current = stream.current();
  210. // Handle decorators
  211. if (state.beginningOfLine && current == "@")
  212. return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;
  213. if (/\S/.test(current)) state.beginningOfLine = false;
  214. if ((style == "variable" || style == "builtin")
  215. && state.lastToken == "meta")
  216. style = "meta";
  217. // Handle scope changes.
  218. if (current == "pass" || current == "return")
  219. state.dedent += 1;
  220. if (current == "lambda") state.lambda = true;
  221. if (current == ":" && !state.lambda && top(state).type == "py")
  222. pushPyScope(state);
  223. var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1;
  224. if (delimiter_index != -1)
  225. pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
  226. delimiter_index = "])}".indexOf(current);
  227. if (delimiter_index != -1) {
  228. if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent
  229. else return ERRORCLASS;
  230. }
  231. if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
  232. if (state.scopes.length > 1) state.scopes.pop();
  233. state.dedent -= 1;
  234. }
  235. return style;
  236. }
  237. var external = {
  238. startState: function(basecolumn) {
  239. return {
  240. tokenize: tokenBase,
  241. scopes: [{offset: basecolumn || 0, type: "py", align: null}],
  242. indent: basecolumn || 0,
  243. lastToken: null,
  244. lambda: false,
  245. dedent: 0
  246. };
  247. },
  248. token: function(stream, state) {
  249. var addErr = state.errorToken;
  250. if (addErr) state.errorToken = false;
  251. var style = tokenLexer(stream, state);
  252. if (style && style != "comment")
  253. state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;
  254. if (style == "punctuation") style = null;
  255. if (stream.eol() && state.lambda)
  256. state.lambda = false;
  257. return addErr ? style + " " + ERRORCLASS : style;
  258. },
  259. indent: function(state, textAfter) {
  260. if (state.tokenize != tokenBase)
  261. return state.tokenize.isString ? CodeMirror.Pass : 0;
  262. var scope = top(state), closing = scope.type == textAfter.charAt(0)
  263. if (scope.align != null)
  264. return scope.align - (closing ? 1 : 0)
  265. else
  266. return scope.offset - (closing ? hangingIndent : 0)
  267. },
  268. electricInput: /^\s*[\}\]\)]$/,
  269. closeBrackets: {triples: "'\""},
  270. lineComment: "#",
  271. fold: "indent"
  272. };
  273. return external;
  274. });
  275. CodeMirror.defineMIME("text/x-python", "python");
  276. var words = function(str) { return str.split(" "); };
  277. CodeMirror.defineMIME("text/x-cython", {
  278. name: "python",
  279. extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+
  280. "extern gil include nogil property public "+
  281. "readonly struct union DEF IF ELIF ELSE")
  282. });
  283. });