blob: cf32135c0b36cb34b9f116a63c609757c5957c82 [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 Rossumdef2c961999-05-21 04:38:27 +0000102 usetabs = 0
103 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;
107 # else searches back for closest preceding def or class.
108 context_use_ps1 = 0
109
Guido van Rossuma6be3871999-06-01 19:52:34 +0000110 # When searching backwards for the closest preceding def or class,
111 # 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.
116 # OTOH, if you happen to find a line that looks like a def or class
Guido van Rossumbbaba851999-06-01 19:55:34 +0000117 # in a multiline string, the parsing is utterly hosed. Can't think
118 # of a way to stop that without always reparsing from the start
119 # of the file. doctest.py is a killer example of this (IDLE is
120 # useless for editing that!).
Guido van Rossuma6be3871999-06-01 19:52:34 +0000121 num_context_lines = 50, 500, 5000000
122
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000123 def __init__(self, editwin):
Guido van Rossum808fa491999-06-02 11:05:19 +0000124 self.editwin = editwin
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000125 self.text = editwin.text
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000126
127 def config(self, **options):
128 for key, value in options.items():
Guido van Rossumdef2c961999-05-21 04:38:27 +0000129 if key == 'usetabs':
130 self.usetabs = value
131 elif key == 'indentwidth':
132 self.indentwidth = value
133 elif key == 'tabwidth':
134 self.tabwidth = value
Guido van Rossumbbaba851999-06-01 19:55:34 +0000135 elif key == 'context_use_ps1':
136 self.context_use_ps1 = value
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000137 else:
138 raise KeyError, "bad option name: %s" % `key`
139
Guido van Rossumdef2c961999-05-21 04:38:27 +0000140 # If ispythonsource and guess are true, guess a good value for
141 # indentwidth based on file content (if possible), and if
142 # indentwidth != tabwidth set usetabs false.
143 # In any case, adjust the Text widget's view of what a tab
144 # character means.
145
146 def set_indentation_params(self, ispythonsource, guess=1):
147 text = self.text
148
149 if guess and ispythonsource:
150 i = self.guess_indent()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000151 if 2 <= i <= 8:
152 self.indentwidth = i
153 if self.indentwidth != self.tabwidth:
154 self.usetabs = 0
155
156 current_tabs = text['tabs']
157 if current_tabs == "" and self.tabwidth == TK_TABWIDTH_DEFAULT:
158 pass
159 else:
160 # Reconfigure the Text widget by measuring the width
161 # of a tabwidth-length string in pixels, forcing the
162 # widget's tab stops to that.
163 need_tabs = text.tk.call("font", "measure", text['font'],
164 "-displayof", text.master,
165 "n" * self.tabwidth)
166 if current_tabs != need_tabs:
167 text.configure(tabs=need_tabs)
168
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000169 def smart_backspace_event(self, event):
170 text = self.text
171 try:
172 first = text.index("sel.first")
173 last = text.index("sel.last")
Guido van Rossum808fa491999-06-02 11:05:19 +0000174 except: # Was catching TclError, but this doesnt work for
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000175 first = last = None
176 if first and last:
177 text.delete(first, last)
178 text.mark_set("insert", first)
179 return "break"
Guido van Rossumdef2c961999-05-21 04:38:27 +0000180 # If we're at the end of leading whitespace, nuke one indent
181 # level, else one character.
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000182 chars = text.get("insert linestart", "insert")
Guido van Rossumdef2c961999-05-21 04:38:27 +0000183 raw, effective = classifyws(chars, self.tabwidth)
184 if 0 < raw == len(chars):
185 if effective >= self.indentwidth:
186 self.reindent_to(effective - self.indentwidth)
187 return "break"
188 text.delete("insert-1c")
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000189 return "break"
190
Guido van Rossum17c516e1999-04-19 16:23:15 +0000191 def smart_indent_event(self, event):
192 # if intraline selection:
193 # delete it
194 # elif multiline selection:
195 # do indent-region & return
Guido van Rossumdef2c961999-05-21 04:38:27 +0000196 # indent one level
Guido van Rossum17c516e1999-04-19 16:23:15 +0000197 text = self.text
198 try:
199 first = text.index("sel.first")
200 last = text.index("sel.last")
Guido van Rossum808fa491999-06-02 11:05:19 +0000201 except: # Was catching TclError, but this doesnt work for
Guido van Rossum17c516e1999-04-19 16:23:15 +0000202 first = last = None
Guido van Rossum318a70d1999-05-03 15:49:52 +0000203 text.undo_block_start()
204 try:
205 if first and last:
206 if index2line(first) != index2line(last):
207 return self.indent_region_event(event)
208 text.delete(first, last)
209 text.mark_set("insert", first)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000210 prefix = text.get("insert linestart", "insert")
211 raw, effective = classifyws(prefix, self.tabwidth)
212 if raw == len(prefix):
213 # only whitespace to the left
214 self.reindent_to(effective + self.indentwidth)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000215 else:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000216 if self.usetabs:
217 pad = '\t'
218 else:
219 effective = len(string.expandtabs(prefix,
220 self.tabwidth))
221 n = self.indentwidth
222 pad = ' ' * (n - effective % n)
223 text.insert("insert", pad)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000224 text.see("insert")
225 return "break"
226 finally:
227 text.undo_block_stop()
Guido van Rossum17c516e1999-04-19 16:23:15 +0000228
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000229 def newline_and_indent_event(self, event):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000230 text = self.text
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000231 try:
232 first = text.index("sel.first")
233 last = text.index("sel.last")
Guido van Rossum808fa491999-06-02 11:05:19 +0000234 except: # Was catching TclError, but this doesnt work for
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000235 first = last = None
Guido van Rossum318a70d1999-05-03 15:49:52 +0000236 text.undo_block_start()
237 try:
238 if first and last:
239 text.delete(first, last)
240 text.mark_set("insert", first)
241 line = text.get("insert linestart", "insert")
242 i, n = 0, len(line)
243 while i < n and line[i] in " \t":
244 i = i+1
Guido van Rossuma6be3871999-06-01 19:52:34 +0000245 if i == n:
246 # the cursor is in or at leading indentation; just inject
247 # an empty line at the start
248 text.insert("insert linestart", '\n')
249 return "break"
Guido van Rossum318a70d1999-05-03 15:49:52 +0000250 indent = line[:i]
Guido van Rossumbbaba851999-06-01 19:55:34 +0000251 # strip whitespace before insert point
Guido van Rossum318a70d1999-05-03 15:49:52 +0000252 i = 0
253 while line and line[-1] in " \t":
254 line = line[:-1]
Guido van Rossuma6be3871999-06-01 19:52:34 +0000255 i = i+1
Guido van Rossum318a70d1999-05-03 15:49:52 +0000256 if i:
257 text.delete("insert - %d chars" % i, "insert")
Guido van Rossumbbaba851999-06-01 19:55:34 +0000258 # strip whitespace after insert point
259 while text.get("insert") in " \t":
260 text.delete("insert")
261 # start new line
Guido van Rossuma6be3871999-06-01 19:52:34 +0000262 text.insert("insert", '\n')
Guido van Rossumd93f7391999-06-01 19:47:56 +0000263 # adjust indentation for continuations and block open/close
Guido van Rossuma6be3871999-06-01 19:52:34 +0000264 lno = index2line(text.index('insert'))
265 y = PyParse.Parser(self.indentwidth, self.tabwidth)
266 for context in self.num_context_lines:
267 startat = max(lno - context, 1)
268 rawtext = text.get(`startat` + ".0", "insert")
269 y.set_str(rawtext)
Guido van Rossumbbaba851999-06-01 19:55:34 +0000270 bod = y.find_last_def_or_class(self.context_use_ps1)
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
316 def indent_region_event(self, event):
317 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000318 for pos in range(len(lines)):
319 line = lines[pos]
320 if line:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000321 raw, effective = classifyws(line, self.tabwidth)
322 effective = effective + self.indentwidth
323 lines[pos] = self._make_blanks(effective) + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000324 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000325 return "break"
326
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000327 def dedent_region_event(self, event):
328 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000329 for pos in range(len(lines)):
330 line = lines[pos]
331 if line:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000332 raw, effective = classifyws(line, self.tabwidth)
333 effective = max(effective - self.indentwidth, 0)
334 lines[pos] = self._make_blanks(effective) + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000335 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000336 return "break"
337
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000338 def comment_region_event(self, event):
339 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000340 for pos in range(len(lines)):
341 line = lines[pos]
Guido van Rossumdef2c961999-05-21 04:38:27 +0000342 if line:
343 lines[pos] = '##' + line
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000344 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000345
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000346 def uncomment_region_event(self, event):
347 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000348 for pos in range(len(lines)):
349 line = lines[pos]
350 if not line:
351 continue
352 if line[:2] == '##':
353 line = line[2:]
354 elif line[:1] == '#':
355 line = line[1:]
356 lines[pos] = line
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000357 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000358
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000359 def tabify_region_event(self, event):
360 head, tail, chars, lines = self.get_region()
Guido van Rossumd93f7391999-06-01 19:47:56 +0000361 tabwidth = self._asktabwidth()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000362 for pos in range(len(lines)):
363 line = lines[pos]
364 if line:
Guido van Rossumd93f7391999-06-01 19:47:56 +0000365 raw, effective = classifyws(line, tabwidth)
366 ntabs, nspaces = divmod(effective, tabwidth)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000367 lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000368 self.set_region(head, tail, chars, lines)
369
370 def untabify_region_event(self, event):
371 head, tail, chars, lines = self.get_region()
Guido van Rossumd93f7391999-06-01 19:47:56 +0000372 tabwidth = self._asktabwidth()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000373 for pos in range(len(lines)):
Guido van Rossumd93f7391999-06-01 19:47:56 +0000374 lines[pos] = string.expandtabs(lines[pos], tabwidth)
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000375 self.set_region(head, tail, chars, lines)
376
Guido van Rossumdef2c961999-05-21 04:38:27 +0000377 def toggle_tabs_event(self, event):
Guido van Rossum808fa491999-06-02 11:05:19 +0000378 if self.editwin.askyesno(
Guido van Rossumd93f7391999-06-01 19:47:56 +0000379 "Toggle tabs",
Guido van Rossumdef2c961999-05-21 04:38:27 +0000380 "Turn tabs " + ("on", "off")[self.usetabs] + "?",
381 parent=self.text):
382 self.usetabs = not self.usetabs
383 return "break"
384
Guido van Rossumd93f7391999-06-01 19:47:56 +0000385 # XXX this isn't bound to anything -- see class tabwidth comments
Guido van Rossumdef2c961999-05-21 04:38:27 +0000386 def change_tabwidth_event(self, event):
Guido van Rossumd93f7391999-06-01 19:47:56 +0000387 new = self._asktabwidth()
388 if new != self.tabwidth:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000389 self.tabwidth = new
390 self.set_indentation_params(0, guess=0)
391 return "break"
392
393 def change_indentwidth_event(self, event):
Guido van Rossum808fa491999-06-02 11:05:19 +0000394 new = self.editwin.askinteger(
Guido van Rossumd93f7391999-06-01 19:47:56 +0000395 "Indent width",
396 "New indent width (1-16)",
397 parent=self.text,
398 initialvalue=self.indentwidth,
399 minvalue=1,
400 maxvalue=16)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000401 if new and new != self.indentwidth:
402 self.indentwidth = new
403 return "break"
404
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000405 def get_region(self):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000406 text = self.text
407 head = text.index("sel.first linestart")
408 tail = text.index("sel.last -1c lineend +1c")
409 if not (head and tail):
410 head = text.index("insert linestart")
411 tail = text.index("insert lineend +1c")
412 chars = text.get(head, tail)
413 lines = string.split(chars, "\n")
414 return head, tail, chars, lines
415
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000416 def set_region(self, head, tail, chars, lines):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000417 text = self.text
418 newchars = string.join(lines, "\n")
419 if newchars == chars:
420 text.bell()
421 return
422 text.tag_remove("sel", "1.0", "end")
423 text.mark_set("insert", head)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000424 text.undo_block_start()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000425 text.delete(head, tail)
426 text.insert(head, newchars)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000427 text.undo_block_stop()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000428 text.tag_add("sel", head, "insert")
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000429
Guido van Rossumdef2c961999-05-21 04:38:27 +0000430 # Make string that displays as n leading blanks.
431
432 def _make_blanks(self, n):
433 if self.usetabs:
434 ntabs, nspaces = divmod(n, self.tabwidth)
435 return '\t' * ntabs + ' ' * nspaces
436 else:
437 return ' ' * n
438
439 # Delete from beginning of line to insert point, then reinsert
440 # column logical (meaning use tabs if appropriate) spaces.
441
442 def reindent_to(self, column):
443 text = self.text
444 text.undo_block_start()
Guido van Rossuma6be3871999-06-01 19:52:34 +0000445 if text.compare("insert linestart", "!=", "insert"):
446 text.delete("insert linestart", "insert")
Guido van Rossumdef2c961999-05-21 04:38:27 +0000447 if column:
448 text.insert("insert", self._make_blanks(column))
449 text.undo_block_stop()
450
Guido van Rossumd93f7391999-06-01 19:47:56 +0000451 def _asktabwidth(self):
Guido van Rossum808fa491999-06-02 11:05:19 +0000452 return self.editwin.askinteger(
Guido van Rossumd93f7391999-06-01 19:47:56 +0000453 "Tab width",
454 "Spaces per tab?",
455 parent=self.text,
456 initialvalue=self.tabwidth,
457 minvalue=1,
458 maxvalue=16) or self.tabwidth
459
Guido van Rossumdef2c961999-05-21 04:38:27 +0000460 # Guess indentwidth from text content.
461 # Return guessed indentwidth. This should not be believed unless
462 # it's in a reasonable range (e.g., it will be 0 if no indented
463 # blocks are found).
464
465 def guess_indent(self):
466 opener, indented = IndentSearcher(self.text, self.tabwidth).run()
467 if opener and indented:
468 raw, indentsmall = classifyws(opener, self.tabwidth)
469 raw, indentlarge = classifyws(indented, self.tabwidth)
470 else:
471 indentsmall = indentlarge = 0
472 return indentlarge - indentsmall
Guido van Rossum17c516e1999-04-19 16:23:15 +0000473
474# "line.col" -> line, as an int
475def index2line(index):
476 return int(float(index))
Guido van Rossumdef2c961999-05-21 04:38:27 +0000477
478# Look at the leading whitespace in s.
479# Return pair (# of leading ws characters,
480# effective # of leading blanks after expanding
481# tabs to width tabwidth)
482
483def classifyws(s, tabwidth):
484 raw = effective = 0
485 for ch in s:
486 if ch == ' ':
487 raw = raw + 1
488 effective = effective + 1
489 elif ch == '\t':
490 raw = raw + 1
491 effective = (effective / tabwidth + 1) * tabwidth
492 else:
493 break
494 return raw, effective
495
496import tokenize
497_tokenize = tokenize
498del tokenize
499
500class IndentSearcher:
501
502 # .run() chews over the Text widget, looking for a block opener
503 # and the stmt following it. Returns a pair,
504 # (line containing block opener, line containing stmt)
505 # Either or both may be None.
506
507 def __init__(self, text, tabwidth):
508 self.text = text
509 self.tabwidth = tabwidth
510 self.i = self.finished = 0
511 self.blkopenline = self.indentedline = None
512
513 def readline(self):
514 if self.finished:
515 return ""
516 i = self.i = self.i + 1
517 mark = `i` + ".0"
518 if self.text.compare(mark, ">=", "end"):
519 return ""
520 return self.text.get(mark, mark + " lineend+1c")
521
522 def tokeneater(self, type, token, start, end, line,
523 INDENT=_tokenize.INDENT,
524 NAME=_tokenize.NAME,
525 OPENERS=('class', 'def', 'for', 'if', 'try', 'while')):
526 if self.finished:
527 pass
528 elif type == NAME and token in OPENERS:
529 self.blkopenline = line
530 elif type == INDENT and self.blkopenline:
531 self.indentedline = line
532 self.finished = 1
533
534 def run(self):
535 save_tabsize = _tokenize.tabsize
536 _tokenize.tabsize = self.tabwidth
537 try:
538 try:
539 _tokenize.tokenize(self.readline, self.tokeneater)
540 except _tokenize.TokenError:
541 # since we cut off the tokenizer early, we can trigger
542 # spurious errors
543 pass
544 finally:
545 _tokenize.tabsize = save_tabsize
546 return self.blkopenline, self.indentedline