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