blob: f86089826547c16be71af2a8a6fbebdc690f140b [file] [log] [blame]
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +00001import string
Guido van Rossum504b0bf1999-01-02 21:28:54 +00002from Tkinter import TclError
Guido van Rossumdef2c961999-05-21 04:38:27 +00003import tkMessageBox
4import tkSimpleDialog
5
6# The default tab setting for a Text widget, in average-width characters.
7TK_TABWIDTH_DEFAULT = 8
Guido van Rossum504b0bf1999-01-02 21:28:54 +00008
9###$ event <<newline-and-indent>>
10###$ win <Key-Return>
11###$ win <KP_Enter>
12###$ unix <Key-Return>
13###$ unix <KP_Enter>
14
15###$ event <<indent-region>>
16###$ win <Control-bracketright>
17###$ unix <Alt-bracketright>
18###$ unix <Control-bracketright>
19
20###$ event <<dedent-region>>
21###$ win <Control-bracketleft>
22###$ unix <Alt-bracketleft>
23###$ unix <Control-bracketleft>
24
25###$ event <<comment-region>>
26###$ win <Alt-Key-3>
27###$ unix <Alt-Key-3>
28
29###$ event <<uncomment-region>>
30###$ win <Alt-Key-4>
31###$ unix <Alt-Key-4>
32
33###$ event <<tabify-region>>
34###$ win <Alt-Key-5>
35###$ unix <Alt-Key-5>
36
37###$ event <<untabify-region>>
38###$ win <Alt-Key-6>
39###$ unix <Alt-Key-6>
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +000040
41class AutoIndent:
42
Guido van Rossum504b0bf1999-01-02 21:28:54 +000043 menudefs = [
44 ('edit', [
45 None,
46 ('_Indent region', '<<indent-region>>'),
47 ('_Dedent region', '<<dedent-region>>'),
48 ('Comment _out region', '<<comment-region>>'),
49 ('U_ncomment region', '<<uncomment-region>>'),
50 ('Tabify region', '<<tabify-region>>'),
51 ('Untabify region', '<<untabify-region>>'),
Guido van Rossumdef2c961999-05-21 04:38:27 +000052 ('Toggle tabs', '<<toggle-tabs>>'),
Guido van Rossumdef2c961999-05-21 04:38:27 +000053 ('New indent width', '<<change-indentwidth>>'),
Guido van Rossum504b0bf1999-01-02 21:28:54 +000054 ]),
55 ]
56
Guido van Rossum33f2b7b1999-01-03 00:47:35 +000057 keydefs = {
58 '<<smart-backspace>>': ['<Key-BackSpace>'],
Guido van Rossum504b0bf1999-01-02 21:28:54 +000059 '<<newline-and-indent>>': ['<Key-Return>', '<KP_Enter>'],
Guido van Rossum17c516e1999-04-19 16:23:15 +000060 '<<smart-indent>>': ['<Key-Tab>']
Guido van Rossum33f2b7b1999-01-03 00:47:35 +000061 }
62
63 windows_keydefs = {
Guido van Rossum504b0bf1999-01-02 21:28:54 +000064 '<<indent-region>>': ['<Control-bracketright>'],
65 '<<dedent-region>>': ['<Control-bracketleft>'],
66 '<<comment-region>>': ['<Alt-Key-3>'],
67 '<<uncomment-region>>': ['<Alt-Key-4>'],
68 '<<tabify-region>>': ['<Alt-Key-5>'],
69 '<<untabify-region>>': ['<Alt-Key-6>'],
Guido van Rossumdef2c961999-05-21 04:38:27 +000070 '<<toggle-tabs>>': ['<Alt-Key-t>'],
Guido van Rossumd93f7391999-06-01 19:47:56 +000071 '<<change-indentwidth>>': ['<Alt-Key-u>'],
Guido van Rossum504b0bf1999-01-02 21:28:54 +000072 }
73
74 unix_keydefs = {
Guido van Rossum504b0bf1999-01-02 21:28:54 +000075 '<<indent-region>>': ['<Alt-bracketright>',
76 '<Meta-bracketright>',
77 '<Control-bracketright>'],
78 '<<dedent-region>>': ['<Alt-bracketleft>',
79 '<Meta-bracketleft>',
80 '<Control-bracketleft>'],
81 '<<comment-region>>': ['<Alt-Key-3>', '<Meta-Key-3>'],
82 '<<uncomment-region>>': ['<Alt-Key-4>', '<Meta-Key-4>'],
83 '<<tabify-region>>': ['<Alt-Key-5>', '<Meta-Key-5>'],
84 '<<untabify-region>>': ['<Alt-Key-6>', '<Meta-Key-6>'],
85 }
86
Guido van Rossumdef2c961999-05-21 04:38:27 +000087 # usetabs true -> literal tab characters are used by indent and
88 # dedent cmds, possibly mixed with spaces if
89 # indentwidth is not a multiple of tabwidth
90 # false -> tab characters are converted to spaces by indent
91 # and dedent cmds, and ditto TAB keystrokes
Guido van Rossumd93f7391999-06-01 19:47:56 +000092 # indentwidth is the number of characters per logical indent level.
93 # tabwidth is the display width of a literal tab character.
94 # CAUTION: telling Tk to use anything other than its default
95 # tab setting causes it to use an entirely different tabbing algorithm,
96 # treating tab stops as fixed distances from the left margin.
97 # Nobody expects this, so for now tabwidth should never be changed.
Guido van Rossumdef2c961999-05-21 04:38:27 +000098 usetabs = 0
99 indentwidth = 4
Guido van Rossumd93f7391999-06-01 19:47:56 +0000100 tabwidth = TK_TABWIDTH_DEFAULT
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000101
102 def __init__(self, editwin):
103 self.text = editwin.text
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000104
105 def config(self, **options):
106 for key, value in options.items():
Guido van Rossumdef2c961999-05-21 04:38:27 +0000107 if key == 'usetabs':
108 self.usetabs = value
109 elif key == 'indentwidth':
110 self.indentwidth = value
111 elif key == 'tabwidth':
112 self.tabwidth = value
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000113 else:
114 raise KeyError, "bad option name: %s" % `key`
115
Guido van Rossumdef2c961999-05-21 04:38:27 +0000116 # If ispythonsource and guess are true, guess a good value for
117 # indentwidth based on file content (if possible), and if
118 # indentwidth != tabwidth set usetabs false.
119 # In any case, adjust the Text widget's view of what a tab
120 # character means.
121
122 def set_indentation_params(self, ispythonsource, guess=1):
123 text = self.text
124
125 if guess and ispythonsource:
126 i = self.guess_indent()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000127 if 2 <= i <= 8:
128 self.indentwidth = i
129 if self.indentwidth != self.tabwidth:
130 self.usetabs = 0
131
132 current_tabs = text['tabs']
133 if current_tabs == "" and self.tabwidth == TK_TABWIDTH_DEFAULT:
134 pass
135 else:
136 # Reconfigure the Text widget by measuring the width
137 # of a tabwidth-length string in pixels, forcing the
138 # widget's tab stops to that.
139 need_tabs = text.tk.call("font", "measure", text['font'],
140 "-displayof", text.master,
141 "n" * self.tabwidth)
142 if current_tabs != need_tabs:
143 text.configure(tabs=need_tabs)
144
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000145 def smart_backspace_event(self, event):
146 text = self.text
147 try:
148 first = text.index("sel.first")
149 last = text.index("sel.last")
150 except TclError:
151 first = last = None
152 if first and last:
153 text.delete(first, last)
154 text.mark_set("insert", first)
155 return "break"
Guido van Rossumdef2c961999-05-21 04:38:27 +0000156 # If we're at the end of leading whitespace, nuke one indent
157 # level, else one character.
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000158 chars = text.get("insert linestart", "insert")
Guido van Rossumdef2c961999-05-21 04:38:27 +0000159 raw, effective = classifyws(chars, self.tabwidth)
160 if 0 < raw == len(chars):
161 if effective >= self.indentwidth:
162 self.reindent_to(effective - self.indentwidth)
163 return "break"
164 text.delete("insert-1c")
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000165 return "break"
166
Guido van Rossum17c516e1999-04-19 16:23:15 +0000167 def smart_indent_event(self, event):
168 # if intraline selection:
169 # delete it
170 # elif multiline selection:
171 # do indent-region & return
Guido van Rossumdef2c961999-05-21 04:38:27 +0000172 # indent one level
Guido van Rossum17c516e1999-04-19 16:23:15 +0000173 text = self.text
174 try:
175 first = text.index("sel.first")
176 last = text.index("sel.last")
177 except TclError:
178 first = last = None
Guido van Rossum318a70d1999-05-03 15:49:52 +0000179 text.undo_block_start()
180 try:
181 if first and last:
182 if index2line(first) != index2line(last):
183 return self.indent_region_event(event)
184 text.delete(first, last)
185 text.mark_set("insert", first)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000186 prefix = text.get("insert linestart", "insert")
187 raw, effective = classifyws(prefix, self.tabwidth)
188 if raw == len(prefix):
189 # only whitespace to the left
190 self.reindent_to(effective + self.indentwidth)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000191 else:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000192 if self.usetabs:
193 pad = '\t'
194 else:
195 effective = len(string.expandtabs(prefix,
196 self.tabwidth))
197 n = self.indentwidth
198 pad = ' ' * (n - effective % n)
199 text.insert("insert", pad)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000200 text.see("insert")
201 return "break"
202 finally:
203 text.undo_block_stop()
Guido van Rossum17c516e1999-04-19 16:23:15 +0000204
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000205 def newline_and_indent_event(self, event):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000206 text = self.text
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000207 try:
208 first = text.index("sel.first")
209 last = text.index("sel.last")
210 except TclError:
211 first = last = None
Guido van Rossum318a70d1999-05-03 15:49:52 +0000212 text.undo_block_start()
213 try:
214 if first and last:
215 text.delete(first, last)
216 text.mark_set("insert", first)
217 line = text.get("insert linestart", "insert")
218 i, n = 0, len(line)
219 while i < n and line[i] in " \t":
220 i = i+1
221 indent = line[:i]
222 # strip trailing whitespace
223 i = 0
224 while line and line[-1] in " \t":
225 line = line[:-1]
226 i = i + 1
227 if i:
228 text.delete("insert - %d chars" % i, "insert")
Guido van Rossumdef2c961999-05-21 04:38:27 +0000229 # XXX this reproduces the current line's indentation,
230 # without regard for usetabs etc; could instead insert
231 # "\n" + self._make_blanks(classifyws(indent)[1]).
Guido van Rossum318a70d1999-05-03 15:49:52 +0000232 text.insert("insert", "\n" + indent)
Guido van Rossumd93f7391999-06-01 19:47:56 +0000233
234 # adjust indentation for continuations and block open/close
235 x = LineStudier(line)
236 if x.is_block_opener():
Guido van Rossum318a70d1999-05-03 15:49:52 +0000237 self.smart_indent_event(event)
Guido van Rossumd93f7391999-06-01 19:47:56 +0000238 elif x.is_bracket_continued():
239 # if there's something interesting after the last open
240 # bracket, line up with it; else just indent one level
241 i = x.last_open_bracket_index() + 1
242 while i < n and line[i] in " \t":
243 i = i + 1
244 if i < n and line[i] not in "#\n\\":
245 effective = len(string.expandtabs(line[:i],
246 self.tabwidth))
247 else:
248 raw, effective = classifyws(indent, self.tabwidth)
249 effective = effective + self.indentwidth
250 self.reindent_to(effective)
251 elif x.is_backslash_continued():
252 # local info isn't enough to do anything intelligent here;
253 # e.g., if it's the 2nd line a backslash block we want to
254 # indent extra, but if it's the 3rd we don't want to indent
255 # at all; rather than make endless mistakes, leave it alone
256 pass
257 elif indent and x.is_block_closer():
Guido van Rossum318a70d1999-05-03 15:49:52 +0000258 self.smart_backspace_event(event)
259 text.see("insert")
260 return "break"
261 finally:
262 text.undo_block_stop()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000263
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000264 auto_indent = newline_and_indent_event
265
266 def indent_region_event(self, event):
267 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000268 for pos in range(len(lines)):
269 line = lines[pos]
270 if line:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000271 raw, effective = classifyws(line, self.tabwidth)
272 effective = effective + self.indentwidth
273 lines[pos] = self._make_blanks(effective) + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000274 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000275 return "break"
276
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000277 def dedent_region_event(self, event):
278 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000279 for pos in range(len(lines)):
280 line = lines[pos]
281 if line:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000282 raw, effective = classifyws(line, self.tabwidth)
283 effective = max(effective - self.indentwidth, 0)
284 lines[pos] = self._make_blanks(effective) + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000285 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000286 return "break"
287
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000288 def comment_region_event(self, event):
289 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000290 for pos in range(len(lines)):
291 line = lines[pos]
Guido van Rossumdef2c961999-05-21 04:38:27 +0000292 if line:
293 lines[pos] = '##' + line
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000294 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000295
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000296 def uncomment_region_event(self, event):
297 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000298 for pos in range(len(lines)):
299 line = lines[pos]
300 if not line:
301 continue
302 if line[:2] == '##':
303 line = line[2:]
304 elif line[:1] == '#':
305 line = line[1:]
306 lines[pos] = line
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000307 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000308
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000309 def tabify_region_event(self, event):
310 head, tail, chars, lines = self.get_region()
Guido van Rossumd93f7391999-06-01 19:47:56 +0000311 tabwidth = self._asktabwidth()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000312 for pos in range(len(lines)):
313 line = lines[pos]
314 if line:
Guido van Rossumd93f7391999-06-01 19:47:56 +0000315 raw, effective = classifyws(line, tabwidth)
316 ntabs, nspaces = divmod(effective, tabwidth)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000317 lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000318 self.set_region(head, tail, chars, lines)
319
320 def untabify_region_event(self, event):
321 head, tail, chars, lines = self.get_region()
Guido van Rossumd93f7391999-06-01 19:47:56 +0000322 tabwidth = self._asktabwidth()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000323 for pos in range(len(lines)):
Guido van Rossumd93f7391999-06-01 19:47:56 +0000324 lines[pos] = string.expandtabs(lines[pos], tabwidth)
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000325 self.set_region(head, tail, chars, lines)
326
Guido van Rossumdef2c961999-05-21 04:38:27 +0000327 def toggle_tabs_event(self, event):
Guido van Rossumd93f7391999-06-01 19:47:56 +0000328 if tkMessageBox.askyesno(
329 "Toggle tabs",
Guido van Rossumdef2c961999-05-21 04:38:27 +0000330 "Turn tabs " + ("on", "off")[self.usetabs] + "?",
331 parent=self.text):
332 self.usetabs = not self.usetabs
333 return "break"
334
Guido van Rossumd93f7391999-06-01 19:47:56 +0000335 # XXX this isn't bound to anything -- see class tabwidth comments
Guido van Rossumdef2c961999-05-21 04:38:27 +0000336 def change_tabwidth_event(self, event):
Guido van Rossumd93f7391999-06-01 19:47:56 +0000337 new = self._asktabwidth()
338 if new != self.tabwidth:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000339 self.tabwidth = new
340 self.set_indentation_params(0, guess=0)
341 return "break"
342
343 def change_indentwidth_event(self, event):
Guido van Rossumd93f7391999-06-01 19:47:56 +0000344 new = tkSimpleDialog.askinteger(
345 "Indent width",
346 "New indent width (1-16)",
347 parent=self.text,
348 initialvalue=self.indentwidth,
349 minvalue=1,
350 maxvalue=16)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000351 if new and new != self.indentwidth:
352 self.indentwidth = new
353 return "break"
354
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000355 def get_region(self):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000356 text = self.text
357 head = text.index("sel.first linestart")
358 tail = text.index("sel.last -1c lineend +1c")
359 if not (head and tail):
360 head = text.index("insert linestart")
361 tail = text.index("insert lineend +1c")
362 chars = text.get(head, tail)
363 lines = string.split(chars, "\n")
364 return head, tail, chars, lines
365
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000366 def set_region(self, head, tail, chars, lines):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000367 text = self.text
368 newchars = string.join(lines, "\n")
369 if newchars == chars:
370 text.bell()
371 return
372 text.tag_remove("sel", "1.0", "end")
373 text.mark_set("insert", head)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000374 text.undo_block_start()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000375 text.delete(head, tail)
376 text.insert(head, newchars)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000377 text.undo_block_stop()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000378 text.tag_add("sel", head, "insert")
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000379
Guido van Rossumdef2c961999-05-21 04:38:27 +0000380 # Make string that displays as n leading blanks.
381
382 def _make_blanks(self, n):
383 if self.usetabs:
384 ntabs, nspaces = divmod(n, self.tabwidth)
385 return '\t' * ntabs + ' ' * nspaces
386 else:
387 return ' ' * n
388
389 # Delete from beginning of line to insert point, then reinsert
390 # column logical (meaning use tabs if appropriate) spaces.
391
392 def reindent_to(self, column):
393 text = self.text
394 text.undo_block_start()
395 text.delete("insert linestart", "insert")
396 if column:
397 text.insert("insert", self._make_blanks(column))
398 text.undo_block_stop()
399
Guido van Rossumd93f7391999-06-01 19:47:56 +0000400 def _asktabwidth(self):
401 return tkSimpleDialog.askinteger(
402 "Tab width",
403 "Spaces per tab?",
404 parent=self.text,
405 initialvalue=self.tabwidth,
406 minvalue=1,
407 maxvalue=16) or self.tabwidth
408
Guido van Rossumdef2c961999-05-21 04:38:27 +0000409 # Guess indentwidth from text content.
410 # Return guessed indentwidth. This should not be believed unless
411 # it's in a reasonable range (e.g., it will be 0 if no indented
412 # blocks are found).
413
414 def guess_indent(self):
415 opener, indented = IndentSearcher(self.text, self.tabwidth).run()
416 if opener and indented:
417 raw, indentsmall = classifyws(opener, self.tabwidth)
418 raw, indentlarge = classifyws(indented, self.tabwidth)
419 else:
420 indentsmall = indentlarge = 0
421 return indentlarge - indentsmall
Guido van Rossum17c516e1999-04-19 16:23:15 +0000422
423# "line.col" -> line, as an int
424def index2line(index):
425 return int(float(index))
Guido van Rossumdef2c961999-05-21 04:38:27 +0000426
427# Look at the leading whitespace in s.
428# Return pair (# of leading ws characters,
429# effective # of leading blanks after expanding
430# tabs to width tabwidth)
431
432def classifyws(s, tabwidth):
433 raw = effective = 0
434 for ch in s:
435 if ch == ' ':
436 raw = raw + 1
437 effective = effective + 1
438 elif ch == '\t':
439 raw = raw + 1
440 effective = (effective / tabwidth + 1) * tabwidth
441 else:
442 break
443 return raw, effective
444
Guido van Rossumd93f7391999-06-01 19:47:56 +0000445class LineStudier:
Guido van Rossum8234dfc1999-06-01 15:03:30 +0000446
Guido van Rossumd93f7391999-06-01 19:47:56 +0000447 # set to false by self.study(); the other vars retain default values
448 # until then
449 needstudying = 1
450
451 # line ends with an unescaped backslash not in string or comment?
452 backslash_continued = 0
453
454 # line ends with an unterminated string?
455 string_continued = 0
456
457 # the last "interesting" character on a line: the last non-ws char
458 # before an optional trailing comment; if backslash_continued, lastch
459 # precedes the final backslash; if string_continued, the required
460 # string-closer (", """, ', ''')
461 lastch = ""
462
463 # index of rightmost unmatched ([{ not in a string or comment
464 lastopenbrackpos = -1
465
466 import re
467 _is_block_closer_re = re.compile(r"""
468 \s*
469 ( return
470 | break
471 | continue
472 | raise
473 | pass
474 )
475 \b
476 """, re.VERBOSE).match
477
478 # colon followed by optional comment
479 _looks_like_opener_re = re.compile(r":\s*(#.*)?$").search
480 del re
481
482
483 def __init__(self, line):
484 if line[-1:] == '\n':
485 line = line[:-1]
486 self.line = line
487 self.stack = []
488
489 def is_continued(self):
490 return self.is_block_opener() or \
491 self.is_backslash_continued() or \
492 self.is_bracket_continued() or \
493 self.is_string_continued()
494
495 def is_block_opener(self):
496 if not self._looks_like_opener_re(self.line):
497 return 0
498 # Looks like an opener, but possible we're in a comment
499 # x = 3 # and then:
500 # or a string
501 # x = ":#"
502 # If no comment character, we're not in a comment <duh>, and the
503 # colon is the last non-ws char on the line so it's not in a
504 # (single-line) string either.
505 if string.find(self.line, '#') < 0:
506 return 1
507 self.study()
508 return self.lastch == ":"
509
510 def is_backslash_continued(self):
511 self.study()
512 return self.backslash_continued
513
514 def is_bracket_continued(self):
515 self.study()
516 return self.lastopenbrackpos >= 0
517
518 def is_string_continued(self):
519 self.study()
520 return self.string_continued
521
522 def is_block_closer(self):
523 return self._is_block_closer_re(self.line)
524
525 def last_open_bracket_index(self):
526 assert self.stack
527 return self.lastopenbrackpos
528
529 def study(self):
530 if not self.needstudying:
531 return
532 self.needstudying = 0
533 line = self.line
534 i, n = 0, len(line)
535 while i < n:
536 ch = line[i]
537 if ch == '\\':
538 i = i+1
539 if i == n:
540 self.backslash_continued = 1
Guido van Rossum8234dfc1999-06-01 15:03:30 +0000541 else:
Guido van Rossumd93f7391999-06-01 19:47:56 +0000542 self.lastch = ch + line[i]
Guido van Rossum8234dfc1999-06-01 15:03:30 +0000543 i = i+1
Guido van Rossumd93f7391999-06-01 19:47:56 +0000544
545 elif ch in "\"'":
546 # consume string
547 w = 1 # width of string quote
548 if line[i:i+3] in ('"""', "'''"):
549 w = 3
550 ch = ch * 3
551 i = i+w
552 self.lastch = ch
553 while i < n:
554 if line[i] == '\\':
555 i = i+2
556 elif line[i:i+w] == ch:
557 i = i+w
558 break
559 else:
560 i = i+1
561 else:
562 self.string_continued = 1
563
564 elif ch == '#':
565 break
566
567 else:
568 if ch not in string.whitespace:
569 self.lastch = ch
570 if ch in "([(":
571 self.stack.append(i)
572 elif ch in ")]}" and self.stack:
573 if line[self.stack[-1]] + ch in ("()", "[]", "{}"):
574 del self.stack[-1]
575 i = i+1
576 # end while i < n:
577
578 if self.stack:
579 self.lastopenbrackpos = self.stack[-1]
Guido van Rossum8234dfc1999-06-01 15:03:30 +0000580
Guido van Rossumdef2c961999-05-21 04:38:27 +0000581import tokenize
582_tokenize = tokenize
583del tokenize
584
585class IndentSearcher:
586
587 # .run() chews over the Text widget, looking for a block opener
588 # and the stmt following it. Returns a pair,
589 # (line containing block opener, line containing stmt)
590 # Either or both may be None.
591
592 def __init__(self, text, tabwidth):
593 self.text = text
594 self.tabwidth = tabwidth
595 self.i = self.finished = 0
596 self.blkopenline = self.indentedline = None
597
598 def readline(self):
599 if self.finished:
600 return ""
601 i = self.i = self.i + 1
602 mark = `i` + ".0"
603 if self.text.compare(mark, ">=", "end"):
604 return ""
605 return self.text.get(mark, mark + " lineend+1c")
606
607 def tokeneater(self, type, token, start, end, line,
608 INDENT=_tokenize.INDENT,
609 NAME=_tokenize.NAME,
610 OPENERS=('class', 'def', 'for', 'if', 'try', 'while')):
611 if self.finished:
612 pass
613 elif type == NAME and token in OPENERS:
614 self.blkopenline = line
615 elif type == INDENT and self.blkopenline:
616 self.indentedline = line
617 self.finished = 1
618
619 def run(self):
620 save_tabsize = _tokenize.tabsize
621 _tokenize.tabsize = self.tabwidth
622 try:
623 try:
624 _tokenize.tokenize(self.readline, self.tokeneater)
625 except _tokenize.TokenError:
626 # since we cut off the tokenizer early, we can trigger
627 # spurious errors
628 pass
629 finally:
630 _tokenize.tabsize = save_tabsize
631 return self.blkopenline, self.indentedline