]> git.saurik.com Git - wxWidgets.git/blob - contrib/src/stc/scintilla/src/LexPython.cxx
221859035e353cca2f3e6377be2c48fadf5bc8c2
[wxWidgets.git] / contrib / src / stc / scintilla / src / LexPython.cxx
1 // Scintilla source code edit control
2 /** @file LexPython.cxx
3 ** Lexer for Python.
4 **/
5 // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
6 // The License.txt file describes the conditions under which this software may be distributed.
7
8 #include <stdlib.h>
9 #include <string.h>
10 #include <ctype.h>
11 #include <stdio.h>
12 #include <stdarg.h>
13
14 #include "Platform.h"
15
16 #include "PropSet.h"
17 #include "Accessor.h"
18 #include "StyleContext.h"
19 #include "KeyWords.h"
20 #include "Scintilla.h"
21 #include "SciLexer.h"
22
23 enum kwType { kwOther, kwClass, kwDef, kwImport };
24
25 static bool IsPyComment(Accessor &styler, int pos, int len) {
26 return len>0 && styler[pos]=='#';
27 }
28
29 static bool IsPyStringStart(int ch, int chNext, int chNext2) {
30 if (ch == '\'' || ch == '"')
31 return true;
32 if (ch == 'u' || ch == 'U') {
33 if (chNext == '"' || chNext == '\'')
34 return true;
35 if ((chNext == 'r' || chNext == 'R') && (chNext2 == '"' || chNext2 == '\''))
36 return true;
37 }
38 if ((ch == 'r' || ch == 'R') && (chNext == '"' || chNext == '\''))
39 return true;
40
41 return false;
42 }
43
44 /* Return the state to use for the string starting at i; *nextIndex will be set to the first index following the quote(s) */
45 static int GetPyStringState(Accessor &styler, int i, int *nextIndex) {
46 char ch = styler.SafeGetCharAt(i);
47 char chNext = styler.SafeGetCharAt(i + 1);
48
49 // Advance beyond r, u, or ur prefix, but bail if there are any unexpected chars
50 if (ch == 'r' || ch == 'R') {
51 i++;
52 ch = styler.SafeGetCharAt(i);
53 chNext = styler.SafeGetCharAt(i + 1);
54 }
55 else if (ch == 'u' || ch == 'U') {
56 if (chNext == 'r' || chNext == 'R')
57 i += 2;
58 else
59 i += 1;
60 ch = styler.SafeGetCharAt(i);
61 chNext = styler.SafeGetCharAt(i + 1);
62 }
63
64 if (ch != '"' && ch != '\'') {
65 *nextIndex = i + 1;
66 return SCE_P_DEFAULT;
67 }
68
69 if (ch == chNext && ch == styler.SafeGetCharAt(i + 2)) {
70 *nextIndex = i + 3;
71
72 if (ch == '"')
73 return SCE_P_TRIPLEDOUBLE;
74 else
75 return SCE_P_TRIPLE;
76 } else {
77 *nextIndex = i + 1;
78
79 if (ch == '"')
80 return SCE_P_STRING;
81 else
82 return SCE_P_CHARACTER;
83 }
84 }
85
86 inline bool IsAWordChar(int ch) {
87 return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
88 }
89
90 inline bool IsAWordStart(int ch) {
91 return (ch < 0x80) && (isalnum(ch) || ch == '_');
92 }
93
94 static void ColourisePyDoc(unsigned int startPos, int length, int initStyle,
95 WordList *keywordlists[], Accessor &styler) {
96
97 int endPos = startPos + length;
98
99 // Backtrack to previous line in case need to fix its tab whinging
100 int lineCurrent = styler.GetLine(startPos);
101 if (startPos > 0) {
102 if (lineCurrent > 0) {
103 startPos = styler.LineStart(lineCurrent-1);
104 if (startPos == 0)
105 initStyle = SCE_P_DEFAULT;
106 else
107 initStyle = styler.StyleAt(startPos-1);
108 }
109 }
110
111 WordList &keywords = *keywordlists[0];
112
113 const int whingeLevel = styler.GetPropertyInt("tab.timmy.whinge.level");
114
115 initStyle = initStyle & 31;
116 if (initStyle == SCE_P_STRINGEOL) {
117 initStyle = SCE_P_DEFAULT;
118 }
119
120 kwType kwLast = kwOther;
121 int spaceFlags = 0;
122 styler.IndentAmount(lineCurrent, &spaceFlags, IsPyComment);
123
124 // Python uses a different mask because bad indentation is marked by oring with 32
125 StyleContext sc(startPos, endPos-startPos, initStyle, styler, 0x7f);
126
127 for (; sc.More(); sc.Forward()) {
128
129 if (sc.atLineStart) {
130 const char chBad = static_cast<char>(64);
131 const char chGood = static_cast<char>(0);
132 char chFlags = chGood;
133 if (whingeLevel == 1) {
134 chFlags = (spaceFlags & wsInconsistent) ? chBad : chGood;
135 } else if (whingeLevel == 2) {
136 chFlags = (spaceFlags & wsSpaceTab) ? chBad : chGood;
137 } else if (whingeLevel == 3) {
138 chFlags = (spaceFlags & wsSpace) ? chBad : chGood;
139 } else if (whingeLevel == 4) {
140 chFlags = (spaceFlags & wsTab) ? chBad : chGood;
141 }
142 styler.SetFlags(chFlags, static_cast<char>(sc.state));
143 }
144
145 if (sc.atLineEnd) {
146 if ((sc.state == SCE_P_DEFAULT) ||
147 (sc.state == SCE_P_TRIPLE) ||
148 (sc.state == SCE_P_TRIPLEDOUBLE)) {
149 // Perform colourisation of white space and triple quoted strings at end of each line to allow
150 // tab marking to work inside white space and triple quoted strings
151 sc.ForwardSetState(sc.state);
152 }
153 lineCurrent++;
154 styler.IndentAmount(lineCurrent, &spaceFlags, IsPyComment);
155 if ((sc.state == SCE_P_STRING) || (sc.state == SCE_P_CHARACTER)) {
156 sc.ChangeState(SCE_P_STRINGEOL);
157 sc.ForwardSetState(SCE_P_DEFAULT);
158 }
159 }
160
161 // Check for a state end
162 if (sc.state == SCE_P_OPERATOR) {
163 kwLast = kwOther;
164 sc.SetState(SCE_C_DEFAULT);
165 } else if (sc.state == SCE_P_NUMBER) {
166 if (!IsAWordChar(sc.ch)) {
167 sc.SetState(SCE_P_DEFAULT);
168 }
169 } else if (sc.state == SCE_P_WORD) {
170 if ((sc.ch == '.') || (!IsAWordChar(sc.ch))) {
171 char s[100];
172 sc.GetCurrent(s, sizeof(s));
173 int style = SCE_P_IDENTIFIER;
174 if ((kwLast == kwImport) && (strcmp(s, "as") == 0)) {
175 style = SCE_P_WORD;
176 } else if (keywords.InList(s)) {
177 style = SCE_P_WORD;
178 } else if (kwLast == kwClass) {
179 style = SCE_P_CLASSNAME;
180 } else if (kwLast == kwDef) {
181 style = SCE_P_DEFNAME;
182 }
183 sc.ChangeState(style);
184 sc.SetState(SCE_P_DEFAULT);
185 if (style == SCE_P_WORD) {
186 if (0 == strcmp(s, "class"))
187 kwLast = kwClass;
188 else if (0 == strcmp(s, "def"))
189 kwLast = kwDef;
190 else if (0 == strcmp(s, "import"))
191 kwLast = kwImport;
192 else
193 kwLast = kwOther;
194 } else if (style == SCE_P_CLASSNAME) {
195 kwLast = kwOther;
196 } else if (style == SCE_P_DEFNAME) {
197 kwLast = kwOther;
198 }
199 }
200 } else if ((sc.state == SCE_P_COMMENTLINE) || (sc.state == SCE_P_COMMENTBLOCK)) {
201 if (sc.ch == '\r' || sc.ch == '\n') {
202 sc.SetState(SCE_P_DEFAULT);
203 }
204 } else if ((sc.state == SCE_P_STRING) || (sc.state == SCE_P_CHARACTER)) {
205 if (sc.ch == '\\') {
206 if ((sc.chNext == '\r') && (sc.GetRelative(2) == '\n')) {
207 sc.Forward();
208 }
209 sc.Forward();
210 } else if ((sc.state == SCE_P_STRING) && (sc.ch == '\"')) {
211 sc.ForwardSetState(SCE_P_DEFAULT);
212 } else if ((sc.state == SCE_P_CHARACTER) && (sc.ch == '\'')) {
213 sc.ForwardSetState(SCE_P_DEFAULT);
214 }
215 } else if (sc.state == SCE_P_TRIPLE) {
216 if (sc.ch == '\\') {
217 sc.Forward();
218 } else if (sc.Match("\'\'\'")) {
219 sc.Forward();
220 sc.Forward();
221 sc.ForwardSetState(SCE_P_DEFAULT);
222 }
223 } else if (sc.state == SCE_P_TRIPLEDOUBLE) {
224 if (sc.ch == '\\') {
225 sc.Forward();
226 } else if (sc.Match("\"\"\"")) {
227 sc.Forward();
228 sc.Forward();
229 sc.ForwardSetState(SCE_P_DEFAULT);
230 }
231 }
232
233 // Check for a new state starting character
234 if (sc.state == SCE_P_DEFAULT) {
235 if (isascii(sc.ch) && isoperator(static_cast<char>(sc.ch)) || sc.ch == '`') {
236 sc.SetState(SCE_P_OPERATOR);
237 } else if (sc.ch == '#') {
238 sc.SetState(sc.chNext == '#' ? SCE_P_COMMENTBLOCK : SCE_P_COMMENTLINE);
239 } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
240 sc.SetState(SCE_P_NUMBER);
241 } else if (IsPyStringStart(sc.ch, sc.chNext, sc.GetRelative(2))) {
242 int nextIndex = 0;
243 sc.SetState(GetPyStringState(styler, sc.currentPos, &nextIndex));
244 while (nextIndex > (sc.currentPos+1)) {
245 sc.Forward();
246 }
247 } else if (IsAWordStart(sc.ch)) {
248 sc.SetState(SCE_P_WORD);
249 }
250 }
251 }
252 sc.Complete();
253 }
254
255 static bool IsCommentLine(int line, Accessor &styler) {
256 int pos = styler.LineStart(line);
257 int eol_pos = styler.LineStart(line+1) - 1;
258 for (int i = pos; i < eol_pos; i++) {
259 char ch = styler[i];
260 if (ch == '#')
261 return true;
262 else if (ch != ' ' && ch != '\t')
263 return false;
264 }
265 return false;
266 }
267
268 static bool IsQuoteLine(int line, Accessor &styler) {
269 int style = styler.StyleAt(styler.LineStart(line)) & 31;
270 return ((style == SCE_P_TRIPLE) || (style== SCE_P_TRIPLEDOUBLE));
271 }
272
273
274 static void FoldPyDoc(unsigned int startPos, int length, int /*initStyle - unused*/,
275 WordList *[], Accessor &styler) {
276 const int maxPos = startPos + length;
277 const int maxLines = styler.GetLine(maxPos-1); // Requested last line
278 const int docLines = styler.GetLine(styler.Length() - 1); // Available last line
279 const bool foldComment = styler.GetPropertyInt("fold.comment.python");
280 const bool foldQuotes = styler.GetPropertyInt("fold.quotes.python");
281
282 // Backtrack to previous non-blank line so we can determine indent level
283 // for any white space lines (needed esp. within triple quoted strings)
284 // and so we can fix any preceding fold level (which is why we go back
285 // at least one line in all cases)
286 int spaceFlags = 0;
287 int lineCurrent = styler.GetLine(startPos);
288 int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);
289 while (lineCurrent > 0) {
290 lineCurrent--;
291 indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);
292 if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG) &&
293 (!IsCommentLine(lineCurrent, styler)) &&
294 (!IsQuoteLine(lineCurrent, styler)))
295 break;
296 }
297 int indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;
298
299 // Set up initial loop state
300 startPos = styler.LineStart(lineCurrent);
301 int prev_state = SCE_P_DEFAULT & 31;
302 if (lineCurrent >= 1)
303 prev_state = styler.StyleAt(startPos-1) & 31;
304 int prevQuote = foldQuotes && ((prev_state == SCE_P_TRIPLE) || (prev_state == SCE_P_TRIPLEDOUBLE));
305 int prevComment = 0;
306 if (lineCurrent >= 1)
307 prevComment = foldComment && IsCommentLine(lineCurrent - 1, styler);
308
309 // Process all characters to end of requested range or end of any triple quote
310 // or comment that hangs over the end of the range. Cap processing in all cases
311 // to end of document (in case of unclosed quote or comment at end).
312 while ((lineCurrent <= docLines) && ((lineCurrent <= maxLines) || prevQuote || prevComment)) {
313
314 // Gather info
315 int lev = indentCurrent;
316 int lineNext = lineCurrent + 1;
317 int indentNext = indentCurrent;
318 int quote = false;
319 if (lineNext <= docLines) {
320 // Information about next line is only available if not at end of document
321 indentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL);
322 int style = styler.StyleAt(styler.LineStart(lineNext)) & 31;
323 quote = foldQuotes && ((style == SCE_P_TRIPLE) || (style== SCE_P_TRIPLEDOUBLE));
324 }
325 const int quote_start = (quote && !prevQuote);
326 const int quote_continue = (quote && prevQuote);
327 const int comment = foldComment && IsCommentLine(lineCurrent, styler);
328 const int comment_start = (comment && !prevComment && (lineNext <= docLines) &&
329 IsCommentLine(lineNext, styler) && (lev > SC_FOLDLEVELBASE));
330 const int comment_continue = (comment && prevComment);
331 if ((!quote || !prevQuote) && !comment)
332 indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;
333 if (quote)
334 indentNext = indentCurrentLevel;
335 if (indentNext & SC_FOLDLEVELWHITEFLAG)
336 indentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel;
337
338 if (quote_start) {
339 // Place fold point at start of triple quoted string
340 lev |= SC_FOLDLEVELHEADERFLAG;
341 } else if (quote_continue || prevQuote) {
342 // Add level to rest of lines in the string
343 lev = lev + 1;
344 } else if (comment_start) {
345 // Place fold point at start of a block of comments
346 lev |= SC_FOLDLEVELHEADERFLAG;
347 } else if (comment_continue) {
348 // Add level to rest of lines in the block
349 lev = lev + 1;
350 }
351
352 // Skip past any blank lines for next indent level info; we skip also comments
353 // starting in column 0 which effectively folds them into surrounding code rather
354 // than screwing up folding.
355 const int saveIndentNext = indentNext;
356 while (!quote &&
357 (lineNext < docLines) &&
358 ((indentNext & SC_FOLDLEVELWHITEFLAG) ||
359 (lineNext <= docLines && styler[styler.LineStart(lineNext)] == '#'))) {
360
361 lineNext++;
362 indentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL);
363 }
364
365 // Next compute max indent level of current line and next non-blank line.
366 // This is the level to which we set all the intervening blank or comment lines.
367 const int skip_level = Platform::Maximum(indentCurrentLevel,
368 indentNext & SC_FOLDLEVELNUMBERMASK);
369
370 // Now set all the indent levels on the lines we skipped
371 int skipLine = lineCurrent + 1;
372 int skipIndentNext = saveIndentNext;
373 while (skipLine < lineNext) {
374 int skipLineLevel = skip_level;
375 if (skipIndentNext & SC_FOLDLEVELWHITEFLAG)
376 skipLineLevel = SC_FOLDLEVELWHITEFLAG | skipLineLevel;
377 styler.SetLevel(skipLine, skipLineLevel);
378 skipLine++;
379 skipIndentNext = styler.IndentAmount(skipLine, &spaceFlags, NULL);
380 }
381
382 // Set fold header on non-quote/non-comment line
383 if (!quote && !comment && !(indentCurrent & SC_FOLDLEVELWHITEFLAG) ) {
384 if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))
385 lev |= SC_FOLDLEVELHEADERFLAG;
386 }
387
388 // Keep track of triple quote and block comment state of previous line
389 prevQuote = quote;
390 prevComment = comment_start || comment_continue;
391
392 // Set fold level for this line and move to next line
393 styler.SetLevel(lineCurrent, lev);
394 indentCurrent = indentNext;
395 lineCurrent = lineNext;
396 }
397
398 // NOTE: Cannot set level of last line here because indentCurrent doesn't have
399 // header flag set; the loop above is crafted to take care of this case!
400 //styler.SetLevel(lineCurrent, indentCurrent);
401 }
402
403 LexerModule lmPython(SCLEX_PYTHON, ColourisePyDoc, "python", FoldPyDoc);