4 # Reason last stmt is continued (or C_NONE if it's not).
5 (C_NONE
, C_BACKSLASH
, C_STRING_FIRST_LINE
,
6 C_STRING_NEXT_LINES
, C_BRACKET
) = range(5)
8 if 0: # for throwaway debugging output
10 sys
.__stdout
__.write(" ".join(map(str, stuff
)) + "\n")
12 # Find what looks like the start of a popular stmt.
14 _synchre
= re
.compile(r
"""
33 """, re
.VERBOSE | re
.MULTILINE
).search
35 # Match blank line or non-indenting comment line.
37 _junkre
= re
.compile(r
"""
41 """, re
.VERBOSE
).match
43 # Match any flavor of string; the terminating quote is optional
44 # so that we're robust in the face of incomplete program text.
46 _match_stringre
= re
.compile(r
"""
53 | " [^
"\\\n]* (?: \\. [^"\\\n]* )* "?
61 | ' [^'\\\n]* (?: \\. [^'\\\n]* )* '?
62 """, re.VERBOSE | re.DOTALL).match
64 # Match a line that starts with something interesting;
65 # used to find the first item of a bracket structure.
67 _itemre = re.compile(r"""
69 [^\s#\\] # if we match, m.end()-1 is the interesting char
70 """, re.VERBOSE).match
72 # Match start of stmts that should be followed by a dedent.
74 _closere = re.compile(r"""
83 """, re.VERBOSE).match
85 # Chew up non-special chars as quickly as possible. If match is
86 # successful, m.end() less 1 is the index of the last boring char
87 # matched. If match is unsuccessful, the string starts with an
90 _chew_ordinaryre = re.compile(r"""
92 """, re.VERBOSE).match
94 # Build translation table to map uninteresting chars to "x", open
95 # brackets to "(", and close brackets to ")".
102 for ch in "\"'\\\n#":
104 _tran = ''.join(_tran)
108 UnicodeType = type(unicode(""))
114 def __init__(self, indentwidth, tabwidth):
115 self.indentwidth = indentwidth
116 self.tabwidth = tabwidth
118 def set_str(self, str):
119 assert len(str) == 0 or str[-1] == '\n'
120 if type(str) is UnicodeType:
121 # The parse functions have no idea what to do with Unicode, so
122 # replace all Unicode characters with "x". This is "safe"
123 # so long as the only characters germane to parsing the structure
124 # of Python are 7-bit ASCII. It's *necessary* because Unicode
125 # strings don't have a .translate() method that supports
130 for raw in map(ord, uniphooey):
131 push(raw < 127 and chr(raw) or "x")
136 # Return index of a good place to begin parsing, as close to the
137 # end of the string as possible. This will be the start of some
138 # popular stmt like "if" or "def". Return None if none found:
139 # the caller should pass more prior context then, if possible, or
140 # if not (the entire program text up until the point of interest
141 # has already been tried) pass 0 to set_lo.
143 # This will be reliable iff given a reliable is_char_in_string
144 # function, meaning that when it says "no", it's absolutely
145 # guaranteed that the char is not in a string.
147 def find_good_parse_start(self, is_char_in_string=None,
149 str, pos = self.str, None
151 if not is_char_in_string:
152 # no clue -- make the caller pass everything
155 # Peek back from the end for a good place to start,
156 # but don't try too often; pos will be left None, or
157 # bumped to a legitimate synch point.
159 for tries in range(5):
160 i = str.rfind(":\n", 0, limit)
163 i = str.rfind('\n', 0, i) + 1 # start of colon line
164 m = _synchre(str, i, limit)
165 if m and not is_char_in_string(m.start()):
170 # Nothing looks like a block-opener, or stuff does
171 # but is_char_in_string keeps returning true; most likely
172 # we're in or near a giant string, the colorizer hasn't
173 # caught up enough to be helpful, or there simply *aren't*
174 # any interesting stmts. In any of these cases we're
175 # going to have to parse the whole thing to be sure, so
176 # give it one last try from the start, but stop wasting
177 # time here regardless of the outcome.
179 if m and not is_char_in_string(m.start()):
183 # Peeking back worked; look forward until _synchre no longer
190 if not is_char_in_string(s):
196 # Throw away the start of the string. Intended to be called with
197 # find_good_parse_start's result.
199 def set_lo(self, lo):
200 assert lo == 0 or self.str[lo-1] == '\n'
202 self.str = self.str[lo:]
204 # As quickly as humanly possible <wink>, find the line numbers (0-
205 # based) of the non-continuation lines.
206 # Creates self.{goodlines, continuation}.
209 if self.study_level >= 1:
213 # Map all uninteresting characters to "x", all open brackets
214 # to "(", all close brackets to ")", then collapse runs of
215 # uninteresting characters. This can cut the number of chars
216 # by a factor of 10-40, and so greatly speed the following loop.
218 str = str.translate(_tran)
219 str = str.replace('xxxxxxxx', 'x')
220 str = str.replace('xxxx', 'x')
221 str = str.replace('xx', 'x')
222 str = str.replace('xx', 'x')
223 str = str.replace('\nx', '\n')
224 # note that replacing x\n with \n would be incorrect, because
225 # x may be preceded by a backslash
227 # March over the squashed version of the program, accumulating
228 # the line numbers of non-continued stmts, and determining
229 # whether & why the last stmt is a continuation.
230 continuation = C_NONE
231 level = lno = 0 # level is nesting level; lno is line number
232 self.goodlines = goodlines = [0]
233 push_good = goodlines.append
239 # cases are checked in decreasing order of frequency
247 # else we're in an unclosed bracket structure
257 # else the program is invalid, but we can't complain
260 if ch == '"' or ch == "'":
263 if str[i-1:i+2] == quote * 3:
275 if str[i-1:i+w] == quote:
282 # unterminated single-quoted string
295 # else comment char or paren inside string
298 # didn't break out of the loop, so we're still
300 if (lno - 1) == firstlno:
301 # before the previous \n in str, we were in the first
303 continuation = C_STRING_FIRST_LINE
305 continuation = C_STRING_NEXT_LINES
306 continue # with outer loop
309 # consume the comment
310 i = str.find('\n', i)
319 continuation = C_BACKSLASH
322 # The last stmt may be continued for all 3 reasons.
323 # String continuation takes precedence over bracket
324 # continuation, which beats backslash continuation.
325 if (continuation != C_STRING_FIRST_LINE
326 and continuation != C_STRING_NEXT_LINES and level > 0):
327 continuation = C_BRACKET
328 self.continuation = continuation
330 # Push the final line number as a sentinel value, regardless of
331 # whether it's continued.
332 assert (continuation == C_NONE) == (goodlines[-1] == lno)
333 if goodlines[-1] != lno:
336 def get_continuation_type(self):
338 return self.continuation
340 # study1 was sufficient to determine the continuation status,
341 # but doing more requires looking at every character. study2
342 # does this for the last interesting statement in the block.
344 # self.stmt_start, stmt_end
345 # slice indices of last interesting stmt
346 # self.stmt_bracketing
347 # the bracketing structure of the last interesting stmt;
348 # for example, for the statement "say(boo) or die", stmt_bracketing
349 # will be [(0, 0), (3, 1), (8, 0)]. Strings and comments are
350 # treated as brackets, for the matter.
352 # last non-whitespace character before optional trailing
354 # self.lastopenbracketpos
355 # if continuation is C_BRACKET, index of last open bracket
358 if self.study_level >= 2:
363 # Set p and q to slice indices of last interesting stmt.
364 str, goodlines = self.str, self.goodlines
365 i = len(goodlines) - 1
366 p = len(str) # index of newest line
369 # p is the index of the stmt at line number goodlines[i].
370 # Move p back to the stmt at line number goodlines[i-1].
372 for nothing in range(goodlines[i-1], goodlines[i]):
373 # tricky: sets p to 0 if no preceding newline
374 p = str.rfind('\n', 0, p-1) + 1
375 # The stmt str[p:q] isn't a continuation, but may be blank
376 # or a non-indenting comment line.
385 self.stmt_start, self.stmt_end = p, q
387 # Analyze this stmt, to find the last open bracket (if any)
388 # and last interesting character (if any).
390 stack = [] # stack of open bracket indices
391 push_stack = stack.append
392 bracketing = [(p, 0)]
394 # suck up all except ()[]{}'"#\\
395 m = _chew_ordinaryre(str, p, q)
397 # we skipped at least one boring char
399 # back up over totally boring whitespace
400 i = newp - 1 # index of last boring char
401 while i >= p and str[i] in " \t\n":
413 bracketing.append((p, len(stack)))
423 bracketing.append((p, len(stack)))
426 if ch == '"' or ch == "'":
428 # Note that study1 did this with a Python loop, but
429 # we use a regexp here; the reason is speed in both
430 # cases; the string may be huge, but study1 pre-squashed
431 # strings to a couple of characters per line. study1
432 # also needed to keep track of newlines, and we don't
434 bracketing.append((p, len(stack)+1))
436 p = _match_stringre(str, p, q).end()
437 bracketing.append((p, len(stack)))
441 # consume comment and trailing newline
442 bracketing.append((p, len(stack)+1))
443 p = str.find('\n', p, q) + 1
445 bracketing.append((p, len(stack)))
449 p = p+1 # beyond backslash
452 # the program is invalid, but can't complain
454 p = p+1 # beyond escaped char
460 self.lastopenbracketpos = stack[-1]
461 self.stmt_bracketing = tuple(bracketing)
463 # Assuming continuation is C_BRACKET, return the number
464 # of spaces the next line should be indented.
466 def compute_bracket_indent(self):
468 assert self.continuation == C_BRACKET
469 j = self.lastopenbracketpos
472 origi = i = str.rfind('\n', 0, j) + 1
473 j = j+1 # one beyond open bracket
474 # find first list item; set i to start of its line
478 j = m.end() - 1 # index of first interesting char
482 # this line is junk; advance to next line
483 i = j = str.find('\n', j) + 1
485 # nothing interesting follows the bracket;
486 # reproduce the bracket line's indentation + a level
488 while str[j] in " \t":
490 extra = self.indentwidth
491 return len(str[i:j].expandtabs(self.tabwidth)) + extra
493 # Return number of physical lines in last stmt (whether or not
494 # it's an interesting stmt! this is intended to be called when
495 # continuation is C_BACKSLASH).
497 def get_num_lines_in_stmt(self):
499 goodlines = self.goodlines
500 return goodlines[-1] - goodlines[-2]
502 # Assuming continuation is C_BACKSLASH, return the number of spaces
503 # the next line should be indented. Also assuming the new line is
504 # the first one following the initial line of the stmt.
506 def compute_backslash_indent(self):
508 assert self.continuation == C_BACKSLASH
511 while str[i] in " \t":
515 # See whether the initial line starts an assignment stmt; i.e.,
516 # look for an = operator
517 endpos = str.find('\n', startpos) + 1
528 elif ch == '"' or ch == "'":
529 i = _match_stringre(str, i, endpos).end()
532 elif level == 0 and ch == '=' and \
533 (i == 0 or str[i-1] not in "=<>!") and \
541 # found a legit =, but it may be the last interesting
543 i = i+1 # move beyond the =
544 found = re.match(r"\s*\\", str[i:endpos]) is None
547 # oh well ... settle for moving beyond the first chunk
548 # of non-whitespace chars
550 while str[i] not in " \t\n":
553 return len(str[self.stmt_start:i].expandtabs(\
556 # Return the leading whitespace on the initial line of the last
559 def get_base_indent_string(self):
561 i, n = self.stmt_start, self.stmt_end
564 while j < n and str[j] in " \t":
568 # Did the last interesting stmt open a block?
570 def is_block_opener(self):
572 return self.lastch == ':'
574 # Did the last interesting stmt close a block?
576 def is_block_closer(self):
578 return _closere(self.str, self.stmt_start) is not None
580 # index of last open bracket ({[, or None if none
581 lastopenbracketpos = None
583 def get_last_open_bracket_pos(self):
585 return self.lastopenbracketpos
587 # the structure of the bracketing of the last interesting statement,
588 # in the format defined in _study2, or None if the text didn't contain
590 stmt_bracketing = None
592 def get_last_stmt_bracketing(self):
594 return self.stmt_bracketing