python.js 13 KB

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