1
0

python.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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)
  148. || stream.match(singleOperators)
  149. || stream.match(wordOperators))
  150. return "operator";
  151. if (stream.match(singleDelimiters))
  152. return null;
  153. if (stream.match(keywords))
  154. return "keyword";
  155. if (stream.match(builtins))
  156. return "builtin";
  157. if (stream.match(/^(self|cls)\b/))
  158. return "variable-2";
  159. if (stream.match(identifiers)) {
  160. if (state.lastToken == "def" || state.lastToken == "class")
  161. return "def";
  162. return "variable";
  163. }
  164. // Handle non-detected items
  165. stream.next();
  166. return ERRORCLASS;
  167. }
  168. function tokenStringFactory(delimiter) {
  169. while ("rub".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
  170. delimiter = delimiter.substr(1);
  171. var singleline = delimiter.length == 1;
  172. var OUTCLASS = "string";
  173. function tokenString(stream, state) {
  174. while (!stream.eol()) {
  175. stream.eatWhile(/[^'"\\]/);
  176. if (stream.eat("\\")) {
  177. stream.next();
  178. if (singleline && stream.eol())
  179. return OUTCLASS;
  180. } else if (stream.match(delimiter)) {
  181. state.tokenize = tokenBase;
  182. return OUTCLASS;
  183. } else {
  184. stream.eat(/['"]/);
  185. }
  186. }
  187. if (singleline) {
  188. if (parserConf.singleLineStringErrors)
  189. return ERRORCLASS;
  190. else
  191. state.tokenize = tokenBase;
  192. }
  193. return OUTCLASS;
  194. }
  195. tokenString.isString = true;
  196. return tokenString;
  197. }
  198. function pushScope(stream, state, type) {
  199. var offset = 0, align = null;
  200. if (type == "py") {
  201. while (top(state).type != "py")
  202. state.scopes.pop();
  203. }
  204. offset = top(state).offset + (type == "py" ? conf.indentUnit : hangingIndent);
  205. if (type != "py" && !stream.match(/^(\s|#.*)*$/, false))
  206. align = stream.column() + 1;
  207. state.scopes.push({offset: offset, type: type, align: align});
  208. }
  209. function dedent(stream, state) {
  210. var indented = stream.indentation();
  211. while (top(state).offset > indented) {
  212. if (top(state).type != "py") return true;
  213. state.scopes.pop();
  214. }
  215. return top(state).offset != indented;
  216. }
  217. function tokenLexer(stream, state) {
  218. var style = state.tokenize(stream, state);
  219. var current = stream.current();
  220. // Handle '.' connected identifiers
  221. if (current == ".") {
  222. style = stream.match(identifiers, false) ? null : ERRORCLASS;
  223. if (style == null && state.lastStyle == "meta") {
  224. // Apply 'meta' style to '.' connected identifiers when
  225. // appropriate.
  226. style = "meta";
  227. }
  228. return style;
  229. }
  230. // Handle decorators
  231. if (current == "@"){
  232. if(parserConf.version && parseInt(parserConf.version, 10) == 3){
  233. return stream.match(identifiers, false) ? "meta" : "operator";
  234. } else {
  235. return stream.match(identifiers, false) ? "meta" : ERRORCLASS;
  236. }
  237. }
  238. if ((style == "variable" || style == "builtin")
  239. && state.lastStyle == "meta")
  240. style = "meta";
  241. // Handle scope changes.
  242. if (current == "pass" || current == "return")
  243. state.dedent += 1;
  244. if (current == "lambda") state.lambda = true;
  245. if (current == ":" && !state.lambda && top(state).type == "py")
  246. pushScope(stream, state, "py");
  247. var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1;
  248. if (delimiter_index != -1)
  249. pushScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
  250. delimiter_index = "])}".indexOf(current);
  251. if (delimiter_index != -1) {
  252. if (top(state).type == current) state.scopes.pop();
  253. else return ERRORCLASS;
  254. }
  255. if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
  256. if (state.scopes.length > 1) state.scopes.pop();
  257. state.dedent -= 1;
  258. }
  259. return style;
  260. }
  261. var external = {
  262. startState: function(basecolumn) {
  263. return {
  264. tokenize: tokenBase,
  265. scopes: [{offset: basecolumn || 0, type: "py", align: null}],
  266. lastStyle: null,
  267. lastToken: null,
  268. lambda: false,
  269. dedent: 0
  270. };
  271. },
  272. token: function(stream, state) {
  273. var addErr = state.errorToken;
  274. if (addErr) state.errorToken = false;
  275. var style = tokenLexer(stream, state);
  276. state.lastStyle = style;
  277. var current = stream.current();
  278. if (current && style)
  279. state.lastToken = current;
  280. if (stream.eol() && state.lambda)
  281. state.lambda = false;
  282. return addErr ? style + " " + ERRORCLASS : style;
  283. },
  284. indent: function(state, textAfter) {
  285. if (state.tokenize != tokenBase)
  286. return state.tokenize.isString ? CodeMirror.Pass : 0;
  287. var scope = top(state);
  288. var closing = textAfter && textAfter.charAt(0) == scope.type;
  289. if (scope.align != null)
  290. return scope.align - (closing ? 1 : 0);
  291. else if (closing && state.scopes.length > 1)
  292. return state.scopes[state.scopes.length - 2].offset;
  293. else
  294. return scope.offset;
  295. },
  296. lineComment: "#",
  297. fold: "indent"
  298. };
  299. return external;
  300. });
  301. CodeMirror.defineMIME("text/x-python", "python");
  302. var words = function(str) { return str.split(" "); };
  303. CodeMirror.defineMIME("text/x-cython", {
  304. name: "python",
  305. extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
  306. "extern gil include nogil property public"+
  307. "readonly struct union DEF IF ELIF ELSE")
  308. });
  309. });