blob: 7784254a944a74122d27bcc50e6930320e686505 [file] [log] [blame]
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +00001import string
Guido van Rossum808fa491999-06-02 11:05:19 +00002#from Tkinter import TclError
3#import tkMessageBox
4#import tkSimpleDialog
Guido van Rossumdef2c961999-05-21 04:38:27 +00005
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
Guido van Rossuma6be3871999-06-01 19:52:34 +000041import PyParse
42
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +000043class AutoIndent:
44
Guido van Rossum504b0bf1999-01-02 21:28:54 +000045 menudefs = [
46 ('edit', [
47 None,
48 ('_Indent region', '<<indent-region>>'),
49 ('_Dedent region', '<<dedent-region>>'),
50 ('Comment _out region', '<<comment-region>>'),
51 ('U_ncomment region', '<<uncomment-region>>'),
52 ('Tabify region', '<<tabify-region>>'),
53 ('Untabify region', '<<untabify-region>>'),
Guido van Rossumdef2c961999-05-21 04:38:27 +000054 ('Toggle tabs', '<<toggle-tabs>>'),
Guido van Rossumdef2c961999-05-21 04:38:27 +000055 ('New indent width', '<<change-indentwidth>>'),
Guido van Rossum504b0bf1999-01-02 21:28:54 +000056 ]),
57 ]
58
Guido van Rossum33f2b7b1999-01-03 00:47:35 +000059 keydefs = {
60 '<<smart-backspace>>': ['<Key-BackSpace>'],
Guido van Rossum504b0bf1999-01-02 21:28:54 +000061 '<<newline-and-indent>>': ['<Key-Return>', '<KP_Enter>'],
Guido van Rossum17c516e1999-04-19 16:23:15 +000062 '<<smart-indent>>': ['<Key-Tab>']
Guido van Rossum33f2b7b1999-01-03 00:47:35 +000063 }
64
65 windows_keydefs = {
Guido van Rossum504b0bf1999-01-02 21:28:54 +000066 '<<indent-region>>': ['<Control-bracketright>'],
67 '<<dedent-region>>': ['<Control-bracketleft>'],
68 '<<comment-region>>': ['<Alt-Key-3>'],
69 '<<uncomment-region>>': ['<Alt-Key-4>'],
70 '<<tabify-region>>': ['<Alt-Key-5>'],
71 '<<untabify-region>>': ['<Alt-Key-6>'],
Guido van Rossumdef2c961999-05-21 04:38:27 +000072 '<<toggle-tabs>>': ['<Alt-Key-t>'],
Guido van Rossumd93f7391999-06-01 19:47:56 +000073 '<<change-indentwidth>>': ['<Alt-Key-u>'],
Guido van Rossum504b0bf1999-01-02 21:28:54 +000074 }
75
76 unix_keydefs = {
Guido van Rossum504b0bf1999-01-02 21:28:54 +000077 '<<indent-region>>': ['<Alt-bracketright>',
78 '<Meta-bracketright>',
79 '<Control-bracketright>'],
80 '<<dedent-region>>': ['<Alt-bracketleft>',
81 '<Meta-bracketleft>',
82 '<Control-bracketleft>'],
83 '<<comment-region>>': ['<Alt-Key-3>', '<Meta-Key-3>'],
84 '<<uncomment-region>>': ['<Alt-Key-4>', '<Meta-Key-4>'],
85 '<<tabify-region>>': ['<Alt-Key-5>', '<Meta-Key-5>'],
86 '<<untabify-region>>': ['<Alt-Key-6>', '<Meta-Key-6>'],
Guido van Rossuma954ba11999-06-01 20:06:44 +000087 '<<toggle-tabs>>': ['<Alt-Key-t>'],
88 '<<change-indentwidth>>': ['<Alt-Key-u>'],
Guido van Rossum504b0bf1999-01-02 21:28:54 +000089 }
90
Guido van Rossumdef2c961999-05-21 04:38:27 +000091 # usetabs true -> literal tab characters are used by indent and
92 # dedent cmds, possibly mixed with spaces if
93 # indentwidth is not a multiple of tabwidth
94 # false -> tab characters are converted to spaces by indent
95 # and dedent cmds, and ditto TAB keystrokes
Guido van Rossumd93f7391999-06-01 19:47:56 +000096 # indentwidth is the number of characters per logical indent level.
97 # tabwidth is the display width of a literal tab character.
98 # CAUTION: telling Tk to use anything other than its default
99 # tab setting causes it to use an entirely different tabbing algorithm,
100 # treating tab stops as fixed distances from the left margin.
101 # Nobody expects this, so for now tabwidth should never be changed.
Guido van Rossum0fcd6351999-06-08 12:54:23 +0000102 usetabs = 1
Guido van Rossumdef2c961999-05-21 04:38:27 +0000103 indentwidth = 4
Guido van Rossumd93f7391999-06-01 19:47:56 +0000104 tabwidth = TK_TABWIDTH_DEFAULT
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000105
Guido van Rossumbbaba851999-06-01 19:55:34 +0000106 # If context_use_ps1 is true, parsing searches back for a ps1 line;
Guido van Rossumf4a15081999-06-03 14:32:16 +0000107 # else searches for a popular (if, def, ...) Python stmt.
Guido van Rossumbbaba851999-06-01 19:55:34 +0000108 context_use_ps1 = 0
109
Guido van Rossumf4a15081999-06-03 14:32:16 +0000110 # When searching backwards for a reliable place to begin parsing,
Guido van Rossuma6be3871999-06-01 19:52:34 +0000111 # first start num_context_lines[0] lines back, then
112 # num_context_lines[1] lines back if that didn't work, and so on.
113 # The last value should be huge (larger than the # of lines in a
114 # conceivable file).
115 # Making the initial values larger slows things down more often.
Guido van Rossuma6be3871999-06-01 19:52:34 +0000116 num_context_lines = 50, 500, 5000000
117
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000118 def __init__(self, editwin):
Guido van Rossum808fa491999-06-02 11:05:19 +0000119 self.editwin = editwin
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000120 self.text = editwin.text
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000121
122 def config(self, **options):
123 for key, value in options.items():
Guido van Rossumdef2c961999-05-21 04:38:27 +0000124 if key == 'usetabs':
125 self.usetabs = value
126 elif key == 'indentwidth':
127 self.indentwidth = value
128 elif key == 'tabwidth':
129 self.tabwidth = value
Guido van Rossumbbaba851999-06-01 19:55:34 +0000130 elif key == 'context_use_ps1':
131 self.context_use_ps1 = value
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000132 else:
133 raise KeyError, "bad option name: %s" % `key`
134
Guido van Rossumdef2c961999-05-21 04:38:27 +0000135 # If ispythonsource and guess are true, guess a good value for
136 # indentwidth based on file content (if possible), and if
137 # indentwidth != tabwidth set usetabs false.
138 # In any case, adjust the Text widget's view of what a tab
139 # character means.
140
141 def set_indentation_params(self, ispythonsource, guess=1):
142 text = self.text
143
144 if guess and ispythonsource:
145 i = self.guess_indent()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000146 if 2 <= i <= 8:
147 self.indentwidth = i
148 if self.indentwidth != self.tabwidth:
149 self.usetabs = 0
150
151 current_tabs = text['tabs']
152 if current_tabs == "" and self.tabwidth == TK_TABWIDTH_DEFAULT:
153 pass
154 else:
155 # Reconfigure the Text widget by measuring the width
156 # of a tabwidth-length string in pixels, forcing the
157 # widget's tab stops to that.
158 need_tabs = text.tk.call("font", "measure", text['font'],
159 "-displayof", text.master,
160 "n" * self.tabwidth)
161 if current_tabs != need_tabs:
162 text.configure(tabs=need_tabs)
163
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000164 def smart_backspace_event(self, event):
165 text = self.text
166 try:
167 first = text.index("sel.first")
168 last = text.index("sel.last")
Guido van Rossum808fa491999-06-02 11:05:19 +0000169 except: # Was catching TclError, but this doesnt work for
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000170 first = last = None
171 if first and last:
172 text.delete(first, last)
173 text.mark_set("insert", first)
174 return "break"
Guido van Rossumdef2c961999-05-21 04:38:27 +0000175 # If we're at the end of leading whitespace, nuke one indent
176 # level, else one character.
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000177 chars = text.get("insert linestart", "insert")
Guido van Rossumdef2c961999-05-21 04:38:27 +0000178 raw, effective = classifyws(chars, self.tabwidth)
179 if 0 < raw == len(chars):
180 if effective >= self.indentwidth:
181 self.reindent_to(effective - self.indentwidth)
182 return "break"
183 text.delete("insert-1c")
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000184 return "break"
185
Guido van Rossum17c516e1999-04-19 16:23:15 +0000186 def smart_indent_event(self, event):
187 # if intraline selection:
188 # delete it
189 # elif multiline selection:
190 # do indent-region & return
Guido van Rossumdef2c961999-05-21 04:38:27 +0000191 # indent one level
Guido van Rossum17c516e1999-04-19 16:23:15 +0000192 text = self.text
193 try:
194 first = text.index("sel.first")
195 last = text.index("sel.last")
Guido van Rossum808fa491999-06-02 11:05:19 +0000196 except: # Was catching TclError, but this doesnt work for
Guido van Rossum17c516e1999-04-19 16:23:15 +0000197 first = last = None
Guido van Rossum318a70d1999-05-03 15:49:52 +0000198 text.undo_block_start()
199 try:
200 if first and last:
201 if index2line(first) != index2line(last):
202 return self.indent_region_event(event)
203 text.delete(first, last)
204 text.mark_set("insert", first)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000205 prefix = text.get("insert linestart", "insert")
206 raw, effective = classifyws(prefix, self.tabwidth)
207 if raw == len(prefix):
208 # only whitespace to the left
209 self.reindent_to(effective + self.indentwidth)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000210 else:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000211 if self.usetabs:
212 pad = '\t'
213 else:
214 effective = len(string.expandtabs(prefix,
215 self.tabwidth))
216 n = self.indentwidth
217 pad = ' ' * (n - effective % n)
218 text.insert("insert", pad)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000219 text.see("insert")
220 return "break"
221 finally:
222 text.undo_block_stop()
Guido van Rossum17c516e1999-04-19 16:23:15 +0000223
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000224 def newline_and_indent_event(self, event):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000225 text = self.text
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000226 try:
227 first = text.index("sel.first")
228 last = text.index("sel.last")
Guido van Rossum808fa491999-06-02 11:05:19 +0000229 except: # Was catching TclError, but this doesnt work for
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000230 first = last = None
Guido van Rossum318a70d1999-05-03 15:49:52 +0000231 text.undo_block_start()
232 try:
233 if first and last:
234 text.delete(first, last)
235 text.mark_set("insert", first)
236 line = text.get("insert linestart", "insert")
237 i, n = 0, len(line)
238 while i < n and line[i] in " \t":
239 i = i+1
Guido van Rossuma6be3871999-06-01 19:52:34 +0000240 if i == n:
241 # the cursor is in or at leading indentation; just inject
242 # an empty line at the start
243 text.insert("insert linestart", '\n')
244 return "break"
Guido van Rossum318a70d1999-05-03 15:49:52 +0000245 indent = line[:i]
Guido van Rossumbbaba851999-06-01 19:55:34 +0000246 # strip whitespace before insert point
Guido van Rossum318a70d1999-05-03 15:49:52 +0000247 i = 0
248 while line and line[-1] in " \t":
249 line = line[:-1]
Guido van Rossuma6be3871999-06-01 19:52:34 +0000250 i = i+1
Guido van Rossum318a70d1999-05-03 15:49:52 +0000251 if i:
252 text.delete("insert - %d chars" % i, "insert")
Guido van Rossumbbaba851999-06-01 19:55:34 +0000253 # strip whitespace after insert point
254 while text.get("insert") in " \t":
255 text.delete("insert")
256 # start new line
Guido van Rossuma6be3871999-06-01 19:52:34 +0000257 text.insert("insert", '\n')
Guido van Rossumf4a15081999-06-03 14:32:16 +0000258
Guido van Rossumd93f7391999-06-01 19:47:56 +0000259 # adjust indentation for continuations and block open/close
Guido van Rossumf4a15081999-06-03 14:32:16 +0000260 # first need to find the last stmt
Guido van Rossuma6be3871999-06-01 19:52:34 +0000261 lno = index2line(text.index('insert'))
262 y = PyParse.Parser(self.indentwidth, self.tabwidth)
263 for context in self.num_context_lines:
264 startat = max(lno - context, 1)
Guido van Rossumf4a15081999-06-03 14:32:16 +0000265 startatindex = `startat` + ".0"
266 rawtext = text.get(startatindex, "insert")
Guido van Rossuma6be3871999-06-01 19:52:34 +0000267 y.set_str(rawtext)
Guido van Rossumf4a15081999-06-03 14:32:16 +0000268 bod = y.find_good_parse_start(
269 self.context_use_ps1,
270 self._build_char_in_string_func(startatindex))
Guido van Rossuma6be3871999-06-01 19:52:34 +0000271 if bod is not None or startat == 1:
272 break
273 y.set_lo(bod or 0)
274 c = y.get_continuation_type()
275 if c != PyParse.C_NONE:
276 # The current stmt hasn't ended yet.
277 if c == PyParse.C_STRING:
278 # inside a string; just mimic the current indent
279 text.insert("insert", indent)
280 elif c == PyParse.C_BRACKET:
281 # line up with the first (if any) element of the
282 # last open bracket structure; else indent one
283 # level beyond the indent of the line with the last
284 # open bracket
285 self.reindent_to(y.compute_bracket_indent())
286 elif c == PyParse.C_BACKSLASH:
287 # if more than one line in this stmt already, just
288 # mimic the current indent; else if initial line has
289 # a start on an assignment stmt, indent to beyond
290 # leftmost =; else to beyond first chunk of non-
291 # whitespace on initial line
292 if y.get_num_lines_in_stmt() > 1:
293 text.insert("insert", indent)
294 else:
295 self.reindent_to(y.compute_backslash_indent())
Guido van Rossumd93f7391999-06-01 19:47:56 +0000296 else:
Guido van Rossuma6be3871999-06-01 19:52:34 +0000297 assert 0, "bogus continuation type " + `c`
298 return "break"
299
300 # This line starts a brand new stmt; indent relative to
301 # indentation of initial line of closest preceding interesting
302 # stmt.
303 indent = y.get_base_indent_string()
304 text.insert("insert", indent)
305 if y.is_block_opener():
306 self.smart_indent_event(event)
307 elif indent and y.is_block_closer():
Guido van Rossum318a70d1999-05-03 15:49:52 +0000308 self.smart_backspace_event(event)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000309 return "break"
310 finally:
Guido van Rossuma6be3871999-06-01 19:52:34 +0000311 text.see("insert")
Guido van Rossum318a70d1999-05-03 15:49:52 +0000312 text.undo_block_stop()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000313
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000314 auto_indent = newline_and_indent_event
315
Guido van Rossumf4a15081999-06-03 14:32:16 +0000316 # Our editwin provides a is_char_in_string function that works with
317 # a Tk text index, but PyParse only knows about offsets into a string.
318 # This builds a function for PyParse that accepts an offset.
319
320 def _build_char_in_string_func(self, startindex):
321 def inner(offset, _startindex=startindex,
322 _icis=self.editwin.is_char_in_string):
323 return _icis(_startindex + "+%dc" % offset)
324 return inner
325
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000326 def indent_region_event(self, event):
327 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000328 for pos in range(len(lines)):
329 line = lines[pos]
330 if line:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000331 raw, effective = classifyws(line, self.tabwidth)
332 effective = effective + self.indentwidth
333 lines[pos] = self._make_blanks(effective) + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000334 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000335 return "break"
336
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000337 def dedent_region_event(self, event):
338 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000339 for pos in range(len(lines)):
340 line = lines[pos]
341 if line:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000342 raw, effective = classifyws(line, self.tabwidth)
343 effective = max(effective - self.indentwidth, 0)
344 lines[pos] = self._make_blanks(effective) + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000345 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000346 return "break"
347
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000348 def comment_region_event(self, event):
349 head, tail, chars, lines = self.get_region()
Guido van Rossume2571f21999-06-10 14:44:48 +0000350 for pos in range(len(lines) - 1):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000351 line = lines[pos]
Guido van Rossum0fcd6351999-06-08 12:54:23 +0000352 lines[pos] = '##' + line
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000353 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000354
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000355 def uncomment_region_event(self, event):
356 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000357 for pos in range(len(lines)):
358 line = lines[pos]
359 if not line:
360 continue
361 if line[:2] == '##':
362 line = line[2:]
363 elif line[:1] == '#':
364 line = line[1:]
365 lines[pos] = line
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000366 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000367
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000368 def tabify_region_event(self, event):
369 head, tail, chars, lines = self.get_region()
Guido van Rossumd93f7391999-06-01 19:47:56 +0000370 tabwidth = self._asktabwidth()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000371 for pos in range(len(lines)):
372 line = lines[pos]
373 if line:
Guido van Rossumd93f7391999-06-01 19:47:56 +0000374 raw, effective = classifyws(line, tabwidth)
375 ntabs, nspaces = divmod(effective, tabwidth)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000376 lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000377 self.set_region(head, tail, chars, lines)
378
379 def untabify_region_event(self, event):
380 head, tail, chars, lines = self.get_region()
Guido van Rossumd93f7391999-06-01 19:47:56 +0000381 tabwidth = self._asktabwidth()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000382 for pos in range(len(lines)):
Guido van Rossumd93f7391999-06-01 19:47:56 +0000383 lines[pos] = string.expandtabs(lines[pos], tabwidth)
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000384 self.set_region(head, tail, chars, lines)
385
Guido van Rossumdef2c961999-05-21 04:38:27 +0000386 def toggle_tabs_event(self, event):
Guido van Rossum808fa491999-06-02 11:05:19 +0000387 if self.editwin.askyesno(
Guido van Rossumd93f7391999-06-01 19:47:56 +0000388 "Toggle tabs",
Guido van Rossumdef2c961999-05-21 04:38:27 +0000389 "Turn tabs " + ("on", "off")[self.usetabs] + "?",
390 parent=self.text):
391 self.usetabs = not self.usetabs
392 return "break"
393
Guido van Rossumd93f7391999-06-01 19:47:56 +0000394 # XXX this isn't bound to anything -- see class tabwidth comments
Guido van Rossumdef2c961999-05-21 04:38:27 +0000395 def change_tabwidth_event(self, event):
Guido van Rossumd93f7391999-06-01 19:47:56 +0000396 new = self._asktabwidth()
397 if new != self.tabwidth:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000398 self.tabwidth = new
399 self.set_indentation_params(0, guess=0)
400 return "break"
401
402 def change_indentwidth_event(self, event):
Guido van Rossum808fa491999-06-02 11:05:19 +0000403 new = self.editwin.askinteger(
Guido van Rossumd93f7391999-06-01 19:47:56 +0000404 "Indent width",
405 "New indent width (1-16)",
406 parent=self.text,
407 initialvalue=self.indentwidth,
408 minvalue=1,
409 maxvalue=16)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000410 if new and new != self.indentwidth:
411 self.indentwidth = new
412 return "break"
413
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000414 def get_region(self):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000415 text = self.text
416 head = text.index("sel.first linestart")
417 tail = text.index("sel.last -1c lineend +1c")
418 if not (head and tail):
419 head = text.index("insert linestart")
420 tail = text.index("insert lineend +1c")
421 chars = text.get(head, tail)
422 lines = string.split(chars, "\n")
423 return head, tail, chars, lines
424
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000425 def set_region(self, head, tail, chars, lines):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000426 text = self.text
427 newchars = string.join(lines, "\n")
428 if newchars == chars:
429 text.bell()
430 return
431 text.tag_remove("sel", "1.0", "end")
432 text.mark_set("insert", head)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000433 text.undo_block_start()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000434 text.delete(head, tail)
435 text.insert(head, newchars)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000436 text.undo_block_stop()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000437 text.tag_add("sel", head, "insert")
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000438
Guido van Rossumdef2c961999-05-21 04:38:27 +0000439 # Make string that displays as n leading blanks.
440
441 def _make_blanks(self, n):
442 if self.usetabs:
443 ntabs, nspaces = divmod(n, self.tabwidth)
444 return '\t' * ntabs + ' ' * nspaces
445 else:
446 return ' ' * n
447
448 # Delete from beginning of line to insert point, then reinsert
449 # column logical (meaning use tabs if appropriate) spaces.
450
451 def reindent_to(self, column):
452 text = self.text
453 text.undo_block_start()
Guido van Rossuma6be3871999-06-01 19:52:34 +0000454 if text.compare("insert linestart", "!=", "insert"):
455 text.delete("insert linestart", "insert")
Guido van Rossumdef2c961999-05-21 04:38:27 +0000456 if column:
457 text.insert("insert", self._make_blanks(column))
458 text.undo_block_stop()
459
Guido van Rossumd93f7391999-06-01 19:47:56 +0000460 def _asktabwidth(self):
Guido van Rossum808fa491999-06-02 11:05:19 +0000461 return self.editwin.askinteger(
Guido van Rossumd93f7391999-06-01 19:47:56 +0000462 "Tab width",
463 "Spaces per tab?",
464 parent=self.text,
465 initialvalue=self.tabwidth,
466 minvalue=1,
467 maxvalue=16) or self.tabwidth
468
Guido van Rossumdef2c961999-05-21 04:38:27 +0000469 # Guess indentwidth from text content.
470 # Return guessed indentwidth. This should not be believed unless
471 # it's in a reasonable range (e.g., it will be 0 if no indented
472 # blocks are found).
473
474 def guess_indent(self):
475 opener, indented = IndentSearcher(self.text, self.tabwidth).run()
476 if opener and indented:
477 raw, indentsmall = classifyws(opener, self.tabwidth)
478 raw, indentlarge = classifyws(indented, self.tabwidth)
479 else:
480 indentsmall = indentlarge = 0
481 return indentlarge - indentsmall
Guido van Rossum17c516e1999-04-19 16:23:15 +0000482
483# "line.col" -> line, as an int
484def index2line(index):
485 return int(float(index))
Guido van Rossumdef2c961999-05-21 04:38:27 +0000486
487# Look at the leading whitespace in s.
488# Return pair (# of leading ws characters,
489# effective # of leading blanks after expanding
490# tabs to width tabwidth)
491
492def classifyws(s, tabwidth):
493 raw = effective = 0
494 for ch in s:
495 if ch == ' ':
496 raw = raw + 1
497 effective = effective + 1
498 elif ch == '\t':
499 raw = raw + 1
500 effective = (effective / tabwidth + 1) * tabwidth
501 else:
502 break
503 return raw, effective
504
505import tokenize
506_tokenize = tokenize
507del tokenize
508
509class IndentSearcher:
510
511 # .run() chews over the Text widget, looking for a block opener
512 # and the stmt following it. Returns a pair,
513 # (line containing block opener, line containing stmt)
514 # Either or both may be None.
515
516 def __init__(self, text, tabwidth):
517 self.text = text
518 self.tabwidth = tabwidth
519 self.i = self.finished = 0
520 self.blkopenline = self.indentedline = None
521
522 def readline(self):
523 if self.finished:
524 return ""
525 i = self.i = self.i + 1
526 mark = `i` + ".0"
527 if self.text.compare(mark, ">=", "end"):
528 return ""
529 return self.text.get(mark, mark + " lineend+1c")
530
531 def tokeneater(self, type, token, start, end, line,
532 INDENT=_tokenize.INDENT,
533 NAME=_tokenize.NAME,
534 OPENERS=('class', 'def', 'for', 'if', 'try', 'while')):
535 if self.finished:
536 pass
537 elif type == NAME and token in OPENERS:
538 self.blkopenline = line
539 elif type == INDENT and self.blkopenline:
540 self.indentedline = line
541 self.finished = 1
542
543 def run(self):
544 save_tabsize = _tokenize.tabsize
545 _tokenize.tabsize = self.tabwidth
546 try:
547 try:
548 _tokenize.tokenize(self.readline, self.tokeneater)
549 except _tokenize.TokenError:
550 # since we cut off the tokenizer early, we can trigger
551 # spurious errors
552 pass
553 finally:
554 _tokenize.tabsize = save_tabsize
555 return self.blkopenline, self.indentedline