1
0

python.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. CodeMirror.defineMode("python", function(conf) {
  2. var ERRORCLASS = 'error';
  3. function wordRegexp(words) {
  4. return new RegExp("^((" + words.join(")|(") + "))\\b");
  5. }
  6. var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
  7. var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
  8. var doubleOperators = new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
  9. var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
  10. var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
  11. var 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 commontypes = ['bool', 'classmethod', 'complex', 'dict', 'enumerate',
  19. 'float', 'frozenset', 'int', 'list', 'object',
  20. 'property', 'reversed', 'set', 'slice', 'staticmethod',
  21. 'str', 'super', 'tuple', 'type'];
  22. var py2 = {'types': ['basestring', 'buffer', 'file', 'long', 'unicode',
  23. 'xrange'],
  24. 'keywords': ['exec', 'print']};
  25. var py3 = {'types': ['bytearray', 'bytes', 'filter', 'map', 'memoryview',
  26. 'open', 'range', 'zip'],
  27. 'keywords': ['nonlocal']};
  28. if (!!conf.mode.version && parseInt(conf.mode.version, 10) === 3) {
  29. commonkeywords = commonkeywords.concat(py3.keywords);
  30. commontypes = commontypes.concat(py3.types);
  31. var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
  32. } else {
  33. commonkeywords = commonkeywords.concat(py2.keywords);
  34. commontypes = commontypes.concat(py2.types);
  35. var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
  36. }
  37. var keywords = wordRegexp(commonkeywords);
  38. var types = wordRegexp(commontypes);
  39. var indentInfo = null;
  40. // tokenizers
  41. function tokenBase(stream, state) {
  42. // Handle scope changes
  43. if (stream.sol()) {
  44. var scopeOffset = state.scopes[0].offset;
  45. if (stream.eatSpace()) {
  46. var lineOffset = stream.indentation();
  47. if (lineOffset > scopeOffset) {
  48. indentInfo = 'indent';
  49. } else if (lineOffset < scopeOffset) {
  50. indentInfo = 'dedent';
  51. }
  52. return null;
  53. } else {
  54. if (scopeOffset > 0) {
  55. dedent(stream, state);
  56. }
  57. }
  58. }
  59. if (stream.eatSpace()) {
  60. return null;
  61. }
  62. var ch = stream.peek();
  63. // Handle Comments
  64. if (ch === '#') {
  65. stream.skipToEnd();
  66. return 'comment';
  67. }
  68. // Handle Number Literals
  69. if (stream.match(/^[0-9\.]/, false)) {
  70. var floatLiteral = false;
  71. // Floats
  72. if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
  73. if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
  74. if (stream.match(/^\.\d+/)) { floatLiteral = true; }
  75. if (floatLiteral) {
  76. // Float literals may be "imaginary"
  77. stream.eat(/J/i);
  78. return 'number';
  79. }
  80. // Integers
  81. var intLiteral = false;
  82. // Hex
  83. if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
  84. // Binary
  85. if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
  86. // Octal
  87. if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
  88. // Decimal
  89. if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
  90. // Decimal literals may be "imaginary"
  91. stream.eat(/J/i);
  92. // TODO - Can you have imaginary longs?
  93. intLiteral = true;
  94. }
  95. // Zero by itself with no other piece of number.
  96. if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
  97. if (intLiteral) {
  98. // Integer literals may be "long"
  99. stream.eat(/L/i);
  100. return 'number';
  101. }
  102. }
  103. // Handle Strings
  104. if (stream.match(stringPrefixes)) {
  105. state.tokenize = tokenStringFactory(stream.current());
  106. return state.tokenize(stream, state);
  107. }
  108. // Handle operators and Delimiters
  109. if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
  110. return null;
  111. }
  112. if (stream.match(doubleOperators)
  113. || stream.match(singleOperators)
  114. || stream.match(wordOperators)) {
  115. return 'operator';
  116. }
  117. if (stream.match(singleDelimiters)) {
  118. return null;
  119. }
  120. if (stream.match(types)) {
  121. return 'builtin';
  122. }
  123. if (stream.match(keywords)) {
  124. return 'keyword';
  125. }
  126. if (stream.match(identifiers)) {
  127. return 'variable';
  128. }
  129. // Handle non-detected items
  130. stream.next();
  131. return ERRORCLASS;
  132. }
  133. function tokenStringFactory(delimiter) {
  134. while ('rub'.indexOf(delimiter[0].toLowerCase()) >= 0) {
  135. delimiter = delimiter.substr(1);
  136. }
  137. var delim_re = new RegExp(delimiter);
  138. var singleline = delimiter.length == 1;
  139. var OUTCLASS = 'string';
  140. return function tokenString(stream, state) {
  141. while (!stream.eol()) {
  142. stream.eatWhile(/[^'"\\]/);
  143. if (stream.eat('\\')) {
  144. stream.next();
  145. if (singleline && stream.eol()) {
  146. return OUTCLASS;
  147. }
  148. } else if (stream.match(delim_re)) {
  149. state.tokenize = tokenBase;
  150. return OUTCLASS;
  151. } else {
  152. stream.eat(/['"]/);
  153. }
  154. }
  155. if (singleline) {
  156. if (conf.mode.singleLineStringErrors) {
  157. OUTCLASS = ERRORCLASS
  158. } else {
  159. state.tokenize = tokenBase;
  160. }
  161. }
  162. return OUTCLASS;
  163. };
  164. }
  165. function indent(stream, state, type) {
  166. type = type || 'py';
  167. var indentUnit = 0;
  168. if (type === 'py') {
  169. for (var i = 0; i < state.scopes.length; ++i) {
  170. if (state.scopes[i].type === 'py') {
  171. indentUnit = state.scopes[i].offset + conf.indentUnit;
  172. break;
  173. }
  174. }
  175. } else {
  176. indentUnit = stream.column() + stream.current().length;
  177. }
  178. state.scopes.unshift({
  179. offset: indentUnit,
  180. type: type
  181. });
  182. }
  183. function dedent(stream, state) {
  184. if (state.scopes.length == 1) return;
  185. if (state.scopes[0].type === 'py') {
  186. var _indent = stream.indentation();
  187. var _indent_index = -1;
  188. for (var i = 0; i < state.scopes.length; ++i) {
  189. if (_indent === state.scopes[i].offset) {
  190. _indent_index = i;
  191. break;
  192. }
  193. }
  194. if (_indent_index === -1) {
  195. return true;
  196. }
  197. while (state.scopes[0].offset !== _indent) {
  198. state.scopes.shift();
  199. }
  200. return false
  201. } else {
  202. state.scopes.shift();
  203. return false;
  204. }
  205. }
  206. function tokenLexer(stream, state) {
  207. indentInfo = null;
  208. var style = state.tokenize(stream, state);
  209. var current = stream.current();
  210. // Handle '.' connected identifiers
  211. if (current === '.') {
  212. style = state.tokenize(stream, state);
  213. current = stream.current();
  214. if (style === 'variable') {
  215. return 'variable';
  216. } else {
  217. return ERRORCLASS;
  218. }
  219. }
  220. // Handle decorators
  221. if (current === '@') {
  222. style = state.tokenize(stream, state);
  223. current = stream.current();
  224. if (style === 'variable'
  225. || current === '@staticmethod'
  226. || current === '@classmethod') {
  227. return 'meta';
  228. } else {
  229. return ERRORCLASS;
  230. }
  231. }
  232. // Handle scope changes.
  233. if (current === 'pass' || current === 'return') {
  234. state.dedent += 1;
  235. }
  236. if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
  237. || indentInfo === 'indent') {
  238. indent(stream, state);
  239. }
  240. var delimiter_index = '[({'.indexOf(current);
  241. if (delimiter_index !== -1) {
  242. indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
  243. }
  244. if (indentInfo === 'dedent') {
  245. if (dedent(stream, state)) {
  246. return ERRORCLASS;
  247. }
  248. }
  249. delimiter_index = '])}'.indexOf(current);
  250. if (delimiter_index !== -1) {
  251. if (dedent(stream, state)) {
  252. return ERRORCLASS;
  253. }
  254. }
  255. if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
  256. if (state.scopes.length > 1) state.scopes.shift();
  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'}],
  266. lastToken: null,
  267. lambda: false,
  268. dedent: 0
  269. };
  270. },
  271. token: function(stream, state) {
  272. var style = tokenLexer(stream, state);
  273. state.lastToken = {style:style, content: stream.current()};
  274. if (stream.eol() && stream.lambda) {
  275. state.lambda = false;
  276. }
  277. return style;
  278. },
  279. indent: function(state, textAfter) {
  280. if (state.tokenize != tokenBase) {
  281. return 0;
  282. }
  283. return state.scopes[0].offset;
  284. }
  285. };
  286. return external;
  287. });
  288. CodeMirror.defineMIME("text/x-python", "python");