python.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. var py2 = {builtins: ["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
  33. "file", "intern", "long", "raw_input", "reduce", "reload",
  34. "unichr", "unicode", "xrange", "False", "True", "None"],
  35. keywords: ["exec", "print"]};
  36. var py3 = {builtins: ["ascii", "bytes", "exec", "print"],
  37. keywords: ["nonlocal", "False", "True", "None"]};
  38. CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));
  39. function top(state) {
  40. return state.scopes[state.scopes.length - 1];
  41. }
  42. CodeMirror.defineMode("python", function(conf, parserConf) {
  43. var ERRORCLASS = "error";
  44. var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
  45. var singleDelimiters = parserConf.singleDelimiters || new RegExp("^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]");
  46. var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
  47. var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
  48. var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
  49. var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
  50. var hangingIndent = parserConf.hangingIndent || conf.indentUnit;
  51. var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
  52. if(parserConf.extra_keywords != undefined){
  53. myKeywords = myKeywords.concat(parserConf.extra_keywords);
  54. }
  55. if(parserConf.extra_builtins != undefined){
  56. myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
  57. }
  58. if (parserConf.version && parseInt(parserConf.version, 10) == 3) {
  59. myKeywords = myKeywords.concat(py3.keywords);
  60. myBuiltins = myBuiltins.concat(py3.builtins);
  61. var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
  62. } else {
  63. myKeywords = myKeywords.concat(py2.keywords);
  64. myBuiltins = myBuiltins.concat(py2.builtins);
  65. var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
  66. }
  67. var keywords = wordRegexp(myKeywords);
  68. var builtins = wordRegexp(myBuiltins);
  69. // tokenizers
  70. function tokenBase(stream, state) {
  71. // Handle scope changes
  72. if (stream.sol() && top(state).type == "py") {
  73. var scopeOffset = top(state).offset;
  74. if (stream.eatSpace()) {
  75. var lineOffset = stream.indentation();
  76. if (lineOffset > scopeOffset)
  77. pushScope(stream, state, "py");
  78. else if (lineOffset < scopeOffset && dedent(stream, state))
  79. state.errorToken = true;
  80. return null;
  81. } else {
  82. var style = tokenBaseInner(stream, state);
  83. if (scopeOffset > 0 && dedent(stream, state))
  84. style += " " + ERRORCLASS;
  85. return style;
  86. }
  87. }
  88. return tokenBaseInner(stream, state);
  89. }
  90. function tokenBaseInner(stream, state) {
  91. if (stream.eatSpace()) return null;
  92. var ch = stream.peek();
  93. // Handle Comments
  94. if (ch == "#") {
  95. stream.skipToEnd();
  96. return "comment";
  97. }
  98. // Handle Number Literals
  99. if (stream.match(/^[0-9\.]/, false)) {
  100. var floatLiteral = false;
  101. // Floats
  102. if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
  103. if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
  104. if (stream.match(/^\.\d+/)) { floatLiteral = true; }
  105. if (floatLiteral) {
  106. // Float literals may be "imaginary"
  107. stream.eat(/J/i);
  108. return "number";
  109. }
  110. // Integers
  111. var intLiteral = false;
  112. // Hex
  113. if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true;
  114. // Binary
  115. if (stream.match(/^0b[01]+/i)) intLiteral = true;
  116. // Octal
  117. if (stream.match(/^0o[0-7]+/i)) intLiteral = true;
  118. // Decimal
  119. if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
  120. // Decimal literals may be "imaginary"
  121. stream.eat(/J/i);
  122. // TODO - Can you have imaginary longs?
  123. intLiteral = true;
  124. }
  125. // Zero by itself with no other piece of number.
  126. if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
  127. if (intLiteral) {
  128. // Integer literals may be "long"
  129. stream.eat(/L/i);
  130. return "number";
  131. }
  132. }
  133. // Handle Strings
  134. if (stream.match(stringPrefixes)) {
  135. state.tokenize = tokenStringFactory(stream.current());
  136. return state.tokenize(stream, state);
  137. }
  138. // Handle operators and Delimiters
  139. if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters))
  140. return null;
  141. if (stream.match(doubleOperators)
  142. || stream.match(singleOperators)
  143. || stream.match(wordOperators))
  144. return "operator";
  145. if (stream.match(singleDelimiters))
  146. return null;
  147. if (stream.match(keywords))
  148. return "keyword";
  149. if (stream.match(builtins))
  150. return "builtin";
  151. if (stream.match(/^(self|cls)\b/))
  152. return "variable-2";
  153. if (stream.match(identifiers)) {
  154. if (state.lastToken == "def" || state.lastToken == "class")
  155. return "def";
  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. var singleline = delimiter.length == 1;
  166. var OUTCLASS = "string";
  167. function tokenString(stream, state) {
  168. while (!stream.eol()) {
  169. stream.eatWhile(/[^'"\\]/);
  170. if (stream.eat("\\")) {
  171. stream.next();
  172. if (singleline && stream.eol())
  173. return OUTCLASS;
  174. } else if (stream.match(delimiter)) {
  175. state.tokenize = tokenBase;
  176. return OUTCLASS;
  177. } else {
  178. stream.eat(/['"]/);
  179. }
  180. }
  181. if (singleline) {
  182. if (parserConf.singleLineStringErrors)
  183. return ERRORCLASS;
  184. else
  185. state.tokenize = tokenBase;
  186. }
  187. return OUTCLASS;
  188. }
  189. tokenString.isString = true;
  190. return tokenString;
  191. }
  192. function pushScope(stream, state, type) {
  193. var offset = 0, align = null;
  194. if (type == "py") {
  195. while (top(state).type != "py")
  196. state.scopes.pop();
  197. }
  198. offset = top(state).offset + (type == "py" ? conf.indentUnit : hangingIndent);
  199. if (type != "py" && !stream.match(/^(\s|#.*)*$/, false))
  200. align = stream.column() + 1;
  201. state.scopes.push({offset: offset, type: type, align: align});
  202. }
  203. function dedent(stream, state) {
  204. var indented = stream.indentation();
  205. while (top(state).offset > indented) {
  206. if (top(state).type != "py") return true;
  207. state.scopes.pop();
  208. }
  209. return top(state).offset != indented;
  210. }
  211. function tokenLexer(stream, state) {
  212. var style = state.tokenize(stream, state);
  213. var current = stream.current();
  214. // Handle '.' connected identifiers
  215. if (current == ".") {
  216. style = stream.match(identifiers, false) ? null : ERRORCLASS;
  217. if (style == null && state.lastStyle == "meta") {
  218. // Apply 'meta' style to '.' connected identifiers when
  219. // appropriate.
  220. style = "meta";
  221. }
  222. return style;
  223. }
  224. // Handle decorators
  225. if (current == "@")
  226. return stream.match(identifiers, false) ? "meta" : ERRORCLASS;
  227. if ((style == "variable" || style == "builtin")
  228. && state.lastStyle == "meta")
  229. style = "meta";
  230. // Handle scope changes.
  231. if (current == "pass" || current == "return")
  232. state.dedent += 1;
  233. if (current == "lambda") state.lambda = true;
  234. if (current == ":" && !state.lambda && top(state).type == "py")
  235. pushScope(stream, state, "py");
  236. var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1;
  237. if (delimiter_index != -1)
  238. pushScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
  239. delimiter_index = "])}".indexOf(current);
  240. if (delimiter_index != -1) {
  241. if (top(state).type == current) state.scopes.pop();
  242. else return ERRORCLASS;
  243. }
  244. if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
  245. if (state.scopes.length > 1) state.scopes.pop();
  246. state.dedent -= 1;
  247. }
  248. return style;
  249. }
  250. var external = {
  251. startState: function(basecolumn) {
  252. return {
  253. tokenize: tokenBase,
  254. scopes: [{offset: basecolumn || 0, type: "py", align: null}],
  255. lastStyle: null,
  256. lastToken: null,
  257. lambda: false,
  258. dedent: 0
  259. };
  260. },
  261. token: function(stream, state) {
  262. var addErr = state.errorToken;
  263. if (addErr) state.errorToken = false;
  264. var style = tokenLexer(stream, state);
  265. state.lastStyle = style;
  266. var current = stream.current();
  267. if (current && style)
  268. state.lastToken = current;
  269. if (stream.eol() && state.lambda)
  270. state.lambda = false;
  271. return addErr ? style + " " + ERRORCLASS : style;
  272. },
  273. indent: function(state, textAfter) {
  274. if (state.tokenize != tokenBase)
  275. return state.tokenize.isString ? CodeMirror.Pass : 0;
  276. var scope = top(state);
  277. var closing = textAfter && textAfter.charAt(0) == scope.type;
  278. if (scope.align != null)
  279. return scope.align - (closing ? 1 : 0);
  280. else if (closing && state.scopes.length > 1)
  281. return state.scopes[state.scopes.length - 2].offset;
  282. else
  283. return scope.offset;
  284. },
  285. lineComment: "#",
  286. fold: "indent"
  287. };
  288. return external;
  289. });
  290. CodeMirror.defineMIME("text/x-python", "python");
  291. var words = function(str) { return str.split(" "); };
  292. CodeMirror.defineMIME("text/x-cython", {
  293. name: "python",
  294. extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
  295. "extern gil include nogil property public"+
  296. "readonly struct union DEF IF ELIF ELSE")
  297. });
  298. });