##// END OF EJS Templates
patch SingleOperator in CodeMirror2
Matthias BUSSONNIER -
Show More
@@ -1,338 +1,341
1 1 CodeMirror.defineMode("python", function(conf, parserConf) {
2 2 var ERRORCLASS = 'error';
3 3
4 4 function wordRegexp(words) {
5 5 return new RegExp("^((" + words.join(")|(") + "))\\b");
6 6 }
7
8 var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
7
8 // IPython-specific changes: add '?' as recognized character.
9 var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\\?]");
10 // End IPython changes.
11
9 12 var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
10 13 var doubleOperators = new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
11 14 var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
12 15 var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
13 16 var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
14 17
15 18 var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
16 19 var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
17 20 'def', 'del', 'elif', 'else', 'except', 'finally',
18 21 'for', 'from', 'global', 'if', 'import',
19 22 'lambda', 'pass', 'raise', 'return',
20 23 'try', 'while', 'with', 'yield'];
21 24 var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr',
22 25 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
23 26 'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset',
24 27 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
25 28 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
26 29 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
27 30 'object', 'oct', 'open', 'ord', 'pow', 'property', 'range',
28 31 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
29 32 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
30 33 'type', 'vars', 'zip', '__import__', 'NotImplemented',
31 34 'Ellipsis', '__debug__'];
32 35 var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile',
33 36 'file', 'intern', 'long', 'raw_input', 'reduce', 'reload',
34 37 'unichr', 'unicode', 'xrange', 'False', 'True', 'None'],
35 38 'keywords': ['exec', 'print']};
36 39 var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'],
37 40 'keywords': ['nonlocal', 'False', 'True', 'None']};
38 41
39 42 if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
40 43 commonkeywords = commonkeywords.concat(py3.keywords);
41 44 commonBuiltins = commonBuiltins.concat(py3.builtins);
42 45 var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
43 46 } else {
44 47 commonkeywords = commonkeywords.concat(py2.keywords);
45 48 commonBuiltins = commonBuiltins.concat(py2.builtins);
46 49 var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
47 50 }
48 51 var keywords = wordRegexp(commonkeywords);
49 52 var builtins = wordRegexp(commonBuiltins);
50 53
51 54 var indentInfo = null;
52 55
53 56 // tokenizers
54 57 function tokenBase(stream, state) {
55 58 // Handle scope changes
56 59 if (stream.sol()) {
57 60 var scopeOffset = state.scopes[0].offset;
58 61 if (stream.eatSpace()) {
59 62 var lineOffset = stream.indentation();
60 63 if (lineOffset > scopeOffset) {
61 64 indentInfo = 'indent';
62 65 } else if (lineOffset < scopeOffset) {
63 66 indentInfo = 'dedent';
64 67 }
65 68 return null;
66 69 } else {
67 70 if (scopeOffset > 0) {
68 71 dedent(stream, state);
69 72 }
70 73 }
71 74 }
72 75 if (stream.eatSpace()) {
73 76 return null;
74 77 }
75 78
76 79 var ch = stream.peek();
77 80
78 81 // Handle Comments
79 82 if (ch === '#') {
80 83 stream.skipToEnd();
81 84 return 'comment';
82 85 }
83 86
84 87 // Handle Number Literals
85 88 if (stream.match(/^[0-9\.]/, false)) {
86 89 var floatLiteral = false;
87 90 // Floats
88 91 if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
89 92 if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
90 93 if (stream.match(/^\.\d+/)) { floatLiteral = true; }
91 94 if (floatLiteral) {
92 95 // Float literals may be "imaginary"
93 96 stream.eat(/J/i);
94 97 return 'number';
95 98 }
96 99 // Integers
97 100 var intLiteral = false;
98 101 // Hex
99 102 if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
100 103 // Binary
101 104 if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
102 105 // Octal
103 106 if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
104 107 // Decimal
105 108 if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
106 109 // Decimal literals may be "imaginary"
107 110 stream.eat(/J/i);
108 111 // TODO - Can you have imaginary longs?
109 112 intLiteral = true;
110 113 }
111 114 // Zero by itself with no other piece of number.
112 115 if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
113 116 if (intLiteral) {
114 117 // Integer literals may be "long"
115 118 stream.eat(/L/i);
116 119 return 'number';
117 120 }
118 121 }
119 122
120 123 // Handle Strings
121 124 if (stream.match(stringPrefixes)) {
122 125 state.tokenize = tokenStringFactory(stream.current());
123 126 return state.tokenize(stream, state);
124 127 }
125 128
126 129 // Handle operators and Delimiters
127 130 if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
128 131 return null;
129 132 }
130 133 if (stream.match(doubleOperators)
131 134 || stream.match(singleOperators)
132 135 || stream.match(wordOperators)) {
133 136 return 'operator';
134 137 }
135 138 if (stream.match(singleDelimiters)) {
136 139 return null;
137 140 }
138 141
139 142 if (stream.match(keywords)) {
140 143 return 'keyword';
141 144 }
142 145
143 146 if (stream.match(builtins)) {
144 147 return 'builtin';
145 148 }
146 149
147 150 if (stream.match(identifiers)) {
148 151 return 'variable';
149 152 }
150 153
151 154 // Handle non-detected items
152 155 stream.next();
153 156 return ERRORCLASS;
154 157 }
155 158
156 159 function tokenStringFactory(delimiter) {
157 160 while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
158 161 delimiter = delimiter.substr(1);
159 162 }
160 163 var singleline = delimiter.length == 1;
161 164 var OUTCLASS = 'string';
162 165
163 166 return function tokenString(stream, state) {
164 167 while (!stream.eol()) {
165 168 stream.eatWhile(/[^'"\\]/);
166 169 if (stream.eat('\\')) {
167 170 stream.next();
168 171 if (singleline && stream.eol()) {
169 172 return OUTCLASS;
170 173 }
171 174 } else if (stream.match(delimiter)) {
172 175 state.tokenize = tokenBase;
173 176 return OUTCLASS;
174 177 } else {
175 178 stream.eat(/['"]/);
176 179 }
177 180 }
178 181 if (singleline) {
179 182 if (parserConf.singleLineStringErrors) {
180 183 return ERRORCLASS;
181 184 } else {
182 185 state.tokenize = tokenBase;
183 186 }
184 187 }
185 188 return OUTCLASS;
186 189 };
187 190 }
188 191
189 192 function indent(stream, state, type) {
190 193 type = type || 'py';
191 194 var indentUnit = 0;
192 195 if (type === 'py') {
193 196 if (state.scopes[0].type !== 'py') {
194 197 state.scopes[0].offset = stream.indentation();
195 198 return;
196 199 }
197 200 for (var i = 0; i < state.scopes.length; ++i) {
198 201 if (state.scopes[i].type === 'py') {
199 202 indentUnit = state.scopes[i].offset + conf.indentUnit;
200 203 break;
201 204 }
202 205 }
203 206 } else {
204 207 indentUnit = stream.column() + stream.current().length;
205 208 }
206 209 state.scopes.unshift({
207 210 offset: indentUnit,
208 211 type: type
209 212 });
210 213 }
211 214
212 215 function dedent(stream, state, type) {
213 216 type = type || 'py';
214 217 if (state.scopes.length == 1) return;
215 218 if (state.scopes[0].type === 'py') {
216 219 var _indent = stream.indentation();
217 220 var _indent_index = -1;
218 221 for (var i = 0; i < state.scopes.length; ++i) {
219 222 if (_indent === state.scopes[i].offset) {
220 223 _indent_index = i;
221 224 break;
222 225 }
223 226 }
224 227 if (_indent_index === -1) {
225 228 return true;
226 229 }
227 230 while (state.scopes[0].offset !== _indent) {
228 231 state.scopes.shift();
229 232 }
230 233 return false
231 234 } else {
232 235 if (type === 'py') {
233 236 state.scopes[0].offset = stream.indentation();
234 237 return false;
235 238 } else {
236 239 if (state.scopes[0].type != type) {
237 240 return true;
238 241 }
239 242 state.scopes.shift();
240 243 return false;
241 244 }
242 245 }
243 246 }
244 247
245 248 function tokenLexer(stream, state) {
246 249 indentInfo = null;
247 250 var style = state.tokenize(stream, state);
248 251 var current = stream.current();
249 252
250 253 // Handle '.' connected identifiers
251 254 if (current === '.') {
252 255 style = stream.match(identifiers, false) ? null : ERRORCLASS;
253 256 if (style === null && state.lastToken === 'meta') {
254 257 // Apply 'meta' style to '.' connected identifiers when
255 258 // appropriate.
256 259 style = 'meta';
257 260 }
258 261 return style;
259 262 }
260 263
261 264 // Handle decorators
262 265 if (current === '@') {
263 266 return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;
264 267 }
265 268
266 269 if ((style === 'variable' || style === 'builtin')
267 270 && state.lastToken === 'meta') {
268 271 style = 'meta';
269 272 }
270 273
271 274 // Handle scope changes.
272 275 if (current === 'pass' || current === 'return') {
273 276 state.dedent += 1;
274 277 }
275 278 if (current === 'lambda') state.lambda = true;
276 279 if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
277 280 || indentInfo === 'indent') {
278 281 indent(stream, state);
279 282 }
280 283 var delimiter_index = '[({'.indexOf(current);
281 284 if (delimiter_index !== -1) {
282 285 indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
283 286 }
284 287 if (indentInfo === 'dedent') {
285 288 if (dedent(stream, state)) {
286 289 return ERRORCLASS;
287 290 }
288 291 }
289 292 delimiter_index = '])}'.indexOf(current);
290 293 if (delimiter_index !== -1) {
291 294 if (dedent(stream, state, current)) {
292 295 return ERRORCLASS;
293 296 }
294 297 }
295 298 if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
296 299 if (state.scopes.length > 1) state.scopes.shift();
297 300 state.dedent -= 1;
298 301 }
299 302
300 303 return style;
301 304 }
302 305
303 306 var external = {
304 307 startState: function(basecolumn) {
305 308 return {
306 309 tokenize: tokenBase,
307 310 scopes: [{offset:basecolumn || 0, type:'py'}],
308 311 lastToken: null,
309 312 lambda: false,
310 313 dedent: 0
311 314 };
312 315 },
313 316
314 317 token: function(stream, state) {
315 318 var style = tokenLexer(stream, state);
316 319
317 320 state.lastToken = style;
318 321
319 322 if (stream.eol() && stream.lambda) {
320 323 state.lambda = false;
321 324 }
322 325
323 326 return style;
324 327 },
325 328
326 329 indent: function(state, textAfter) {
327 330 if (state.tokenize != tokenBase) {
328 331 return 0;
329 332 }
330 333
331 334 return state.scopes[0].offset;
332 335 }
333 336
334 337 };
335 338 return external;
336 339 });
337 340
338 341 CodeMirror.defineMIME("text/x-python", "python");
General Comments 0
You need to be logged in to leave comments. Login now