blob: 66a0aec9b87806916d707cd3c70e6a5770e29b5b [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
Guido van Rossum504b0bf1999-01-02 21:28:54 +00006###$ event <<newline-and-indent>>
7###$ win <Key-Return>
8###$ win <KP_Enter>
9###$ unix <Key-Return>
10###$ unix <KP_Enter>
11
12###$ event <<indent-region>>
13###$ win <Control-bracketright>
14###$ unix <Alt-bracketright>
15###$ unix <Control-bracketright>
16
17###$ event <<dedent-region>>
18###$ win <Control-bracketleft>
19###$ unix <Alt-bracketleft>
20###$ unix <Control-bracketleft>
21
22###$ event <<comment-region>>
23###$ win <Alt-Key-3>
24###$ unix <Alt-Key-3>
25
26###$ event <<uncomment-region>>
27###$ win <Alt-Key-4>
28###$ unix <Alt-Key-4>
29
30###$ event <<tabify-region>>
31###$ win <Alt-Key-5>
32###$ unix <Alt-Key-5>
33
34###$ event <<untabify-region>>
35###$ win <Alt-Key-6>
36###$ unix <Alt-Key-6>
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +000037
Guido van Rossuma6be3871999-06-01 19:52:34 +000038import PyParse
39
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +000040class AutoIndent:
41
Guido van Rossum504b0bf1999-01-02 21:28:54 +000042 menudefs = [
43 ('edit', [
44 None,
45 ('_Indent region', '<<indent-region>>'),
46 ('_Dedent region', '<<dedent-region>>'),
47 ('Comment _out region', '<<comment-region>>'),
48 ('U_ncomment region', '<<uncomment-region>>'),
49 ('Tabify region', '<<tabify-region>>'),
50 ('Untabify region', '<<untabify-region>>'),
Guido van Rossumdef2c961999-05-21 04:38:27 +000051 ('Toggle tabs', '<<toggle-tabs>>'),
Guido van Rossumdef2c961999-05-21 04:38:27 +000052 ('New indent width', '<<change-indentwidth>>'),
Guido van Rossum504b0bf1999-01-02 21:28:54 +000053 ]),
54 ]
55
Guido van Rossum33f2b7b1999-01-03 00:47:35 +000056 keydefs = {
57 '<<smart-backspace>>': ['<Key-BackSpace>'],
Guido van Rossum504b0bf1999-01-02 21:28:54 +000058 '<<newline-and-indent>>': ['<Key-Return>', '<KP_Enter>'],
Guido van Rossum17c516e1999-04-19 16:23:15 +000059 '<<smart-indent>>': ['<Key-Tab>']
Guido van Rossum33f2b7b1999-01-03 00:47:35 +000060 }
61
62 windows_keydefs = {
Guido van Rossum504b0bf1999-01-02 21:28:54 +000063 '<<indent-region>>': ['<Control-bracketright>'],
64 '<<dedent-region>>': ['<Control-bracketleft>'],
65 '<<comment-region>>': ['<Alt-Key-3>'],
66 '<<uncomment-region>>': ['<Alt-Key-4>'],
67 '<<tabify-region>>': ['<Alt-Key-5>'],
68 '<<untabify-region>>': ['<Alt-Key-6>'],
Guido van Rossumdef2c961999-05-21 04:38:27 +000069 '<<toggle-tabs>>': ['<Alt-Key-t>'],
Guido van Rossumd93f7391999-06-01 19:47:56 +000070 '<<change-indentwidth>>': ['<Alt-Key-u>'],
Guido van Rossum504b0bf1999-01-02 21:28:54 +000071 }
72
73 unix_keydefs = {
Guido van Rossum504b0bf1999-01-02 21:28:54 +000074 '<<indent-region>>': ['<Alt-bracketright>',
75 '<Meta-bracketright>',
76 '<Control-bracketright>'],
77 '<<dedent-region>>': ['<Alt-bracketleft>',
78 '<Meta-bracketleft>',
79 '<Control-bracketleft>'],
80 '<<comment-region>>': ['<Alt-Key-3>', '<Meta-Key-3>'],
81 '<<uncomment-region>>': ['<Alt-Key-4>', '<Meta-Key-4>'],
82 '<<tabify-region>>': ['<Alt-Key-5>', '<Meta-Key-5>'],
83 '<<untabify-region>>': ['<Alt-Key-6>', '<Meta-Key-6>'],
Guido van Rossuma954ba11999-06-01 20:06:44 +000084 '<<toggle-tabs>>': ['<Alt-Key-t>'],
85 '<<change-indentwidth>>': ['<Alt-Key-u>'],
Guido van Rossum504b0bf1999-01-02 21:28:54 +000086 }
87
Guido van Rossumdef2c961999-05-21 04:38:27 +000088 # usetabs true -> literal tab characters are used by indent and
89 # dedent cmds, possibly mixed with spaces if
90 # indentwidth is not a multiple of tabwidth
91 # false -> tab characters are converted to spaces by indent
92 # and dedent cmds, and ditto TAB keystrokes
Guido van Rossumd93f7391999-06-01 19:47:56 +000093 # indentwidth is the number of characters per logical indent level.
94 # tabwidth is the display width of a literal tab character.
95 # CAUTION: telling Tk to use anything other than its default
96 # tab setting causes it to use an entirely different tabbing algorithm,
97 # treating tab stops as fixed distances from the left margin.
98 # Nobody expects this, so for now tabwidth should never be changed.
Guido van Rossum0fcd6351999-06-08 12:54:23 +000099 usetabs = 1
Guido van Rossumdef2c961999-05-21 04:38:27 +0000100 indentwidth = 4
Guido van Rossum13205601999-06-11 15:03:00 +0000101 tabwidth = 8 # for IDLE use, must remain 8 until Tk is fixed
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000102
Guido van Rossumbbaba851999-06-01 19:55:34 +0000103 # If context_use_ps1 is true, parsing searches back for a ps1 line;
Guido van Rossumf4a15081999-06-03 14:32:16 +0000104 # else searches for a popular (if, def, ...) Python stmt.
Guido van Rossumbbaba851999-06-01 19:55:34 +0000105 context_use_ps1 = 0
106
Guido van Rossumf4a15081999-06-03 14:32:16 +0000107 # When searching backwards for a reliable place to begin parsing,
Guido van Rossuma6be3871999-06-01 19:52:34 +0000108 # first start num_context_lines[0] lines back, then
109 # num_context_lines[1] lines back if that didn't work, and so on.
110 # The last value should be huge (larger than the # of lines in a
111 # conceivable file).
112 # Making the initial values larger slows things down more often.
Guido van Rossuma6be3871999-06-01 19:52:34 +0000113 num_context_lines = 50, 500, 5000000
114
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000115 def __init__(self, editwin):
Guido van Rossum808fa491999-06-02 11:05:19 +0000116 self.editwin = editwin
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000117 self.text = editwin.text
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000118
119 def config(self, **options):
120 for key, value in options.items():
Guido van Rossumdef2c961999-05-21 04:38:27 +0000121 if key == 'usetabs':
122 self.usetabs = value
123 elif key == 'indentwidth':
124 self.indentwidth = value
125 elif key == 'tabwidth':
126 self.tabwidth = value
Guido van Rossumbbaba851999-06-01 19:55:34 +0000127 elif key == 'context_use_ps1':
128 self.context_use_ps1 = value
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000129 else:
130 raise KeyError, "bad option name: %s" % `key`
131
Guido van Rossumdef2c961999-05-21 04:38:27 +0000132 # If ispythonsource and guess are true, guess a good value for
133 # indentwidth based on file content (if possible), and if
134 # indentwidth != tabwidth set usetabs false.
135 # In any case, adjust the Text widget's view of what a tab
136 # character means.
137
138 def set_indentation_params(self, ispythonsource, guess=1):
Guido van Rossumdef2c961999-05-21 04:38:27 +0000139 if guess and ispythonsource:
140 i = self.guess_indent()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000141 if 2 <= i <= 8:
142 self.indentwidth = i
143 if self.indentwidth != self.tabwidth:
144 self.usetabs = 0
145
Guido van Rossum13205601999-06-11 15:03:00 +0000146 self.editwin.set_tabwidth(self.tabwidth)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000147
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000148 def smart_backspace_event(self, event):
149 text = self.text
Guido van Rossum13205601999-06-11 15:03:00 +0000150 first, last = self.editwin.get_selection_indices()
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000151 if first and last:
152 text.delete(first, last)
153 text.mark_set("insert", first)
154 return "break"
Guido van Rossum13205601999-06-11 15:03:00 +0000155 # Delete whitespace left, until hitting a real char or closest
156 # preceding virtual tab stop.
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000157 chars = text.get("insert linestart", "insert")
Guido van Rossum13205601999-06-11 15:03:00 +0000158 if chars == '':
159 if text.compare("insert", ">", "1.0"):
160 # easy: delete preceding newline
161 text.delete("insert-1c")
162 else:
163 text.bell() # at start of buffer
164 return "break"
165 if chars[-1] not in " \t":
166 # easy: delete preceding real char
167 text.delete("insert-1c")
168 return "break"
169 # Ick. It may require *inserting* spaces if we back up over a
170 # tab character! This is written to be clear, not fast.
171 expand, tabwidth = string.expandtabs, self.tabwidth
172 have = len(expand(chars, tabwidth))
173 assert have > 0
174 want = int((have - 1) / self.indentwidth) * self.indentwidth
175 ncharsdeleted = 0
176 while 1:
177 chars = chars[:-1]
178 ncharsdeleted = ncharsdeleted + 1
179 have = len(expand(chars, tabwidth))
180 if have <= want or chars[-1] not in " \t":
181 break
182 text.undo_block_start()
183 text.delete("insert-%dc" % ncharsdeleted, "insert")
184 if have < want:
185 text.insert("insert", ' ' * (want - have))
186 text.undo_block_stop()
Guido van Rossum33f2b7b1999-01-03 00:47:35 +0000187 return "break"
188
Guido van Rossum17c516e1999-04-19 16:23:15 +0000189 def smart_indent_event(self, event):
190 # if intraline selection:
191 # delete it
192 # elif multiline selection:
193 # do indent-region & return
Guido van Rossumdef2c961999-05-21 04:38:27 +0000194 # indent one level
Guido van Rossum17c516e1999-04-19 16:23:15 +0000195 text = self.text
Guido van Rossum13205601999-06-11 15:03:00 +0000196 first, last = self.editwin.get_selection_indices()
Guido van Rossum318a70d1999-05-03 15:49:52 +0000197 text.undo_block_start()
198 try:
199 if first and last:
200 if index2line(first) != index2line(last):
201 return self.indent_region_event(event)
202 text.delete(first, last)
203 text.mark_set("insert", first)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000204 prefix = text.get("insert linestart", "insert")
205 raw, effective = classifyws(prefix, self.tabwidth)
206 if raw == len(prefix):
207 # only whitespace to the left
208 self.reindent_to(effective + self.indentwidth)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000209 else:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000210 if self.usetabs:
211 pad = '\t'
212 else:
213 effective = len(string.expandtabs(prefix,
214 self.tabwidth))
215 n = self.indentwidth
216 pad = ' ' * (n - effective % n)
217 text.insert("insert", pad)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000218 text.see("insert")
219 return "break"
220 finally:
221 text.undo_block_stop()
Guido van Rossum17c516e1999-04-19 16:23:15 +0000222
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000223 def newline_and_indent_event(self, event):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000224 text = self.text
Guido van Rossum13205601999-06-11 15:03:00 +0000225 first, last = self.editwin.get_selection_indices()
Guido van Rossum318a70d1999-05-03 15:49:52 +0000226 text.undo_block_start()
227 try:
228 if first and last:
229 text.delete(first, last)
230 text.mark_set("insert", first)
231 line = text.get("insert linestart", "insert")
232 i, n = 0, len(line)
233 while i < n and line[i] in " \t":
234 i = i+1
Guido van Rossuma6be3871999-06-01 19:52:34 +0000235 if i == n:
236 # the cursor is in or at leading indentation; just inject
237 # an empty line at the start
238 text.insert("insert linestart", '\n')
239 return "break"
Guido van Rossum318a70d1999-05-03 15:49:52 +0000240 indent = line[:i]
Guido van Rossumbbaba851999-06-01 19:55:34 +0000241 # strip whitespace before insert point
Guido van Rossum318a70d1999-05-03 15:49:52 +0000242 i = 0
243 while line and line[-1] in " \t":
244 line = line[:-1]
Guido van Rossuma6be3871999-06-01 19:52:34 +0000245 i = i+1
Guido van Rossum318a70d1999-05-03 15:49:52 +0000246 if i:
247 text.delete("insert - %d chars" % i, "insert")
Guido van Rossumbbaba851999-06-01 19:55:34 +0000248 # strip whitespace after insert point
249 while text.get("insert") in " \t":
250 text.delete("insert")
251 # start new line
Guido van Rossuma6be3871999-06-01 19:52:34 +0000252 text.insert("insert", '\n')
Guido van Rossumf4a15081999-06-03 14:32:16 +0000253
Guido van Rossum13205601999-06-11 15:03:00 +0000254 # adjust indentation for continuations and block
255 # open/close first need to find the last stmt
Guido van Rossuma6be3871999-06-01 19:52:34 +0000256 lno = index2line(text.index('insert'))
257 y = PyParse.Parser(self.indentwidth, self.tabwidth)
258 for context in self.num_context_lines:
259 startat = max(lno - context, 1)
Guido van Rossumf4a15081999-06-03 14:32:16 +0000260 startatindex = `startat` + ".0"
261 rawtext = text.get(startatindex, "insert")
Guido van Rossuma6be3871999-06-01 19:52:34 +0000262 y.set_str(rawtext)
Guido van Rossumf4a15081999-06-03 14:32:16 +0000263 bod = y.find_good_parse_start(
264 self.context_use_ps1,
265 self._build_char_in_string_func(startatindex))
Guido van Rossuma6be3871999-06-01 19:52:34 +0000266 if bod is not None or startat == 1:
267 break
268 y.set_lo(bod or 0)
269 c = y.get_continuation_type()
270 if c != PyParse.C_NONE:
271 # The current stmt hasn't ended yet.
272 if c == PyParse.C_STRING:
273 # inside a string; just mimic the current indent
274 text.insert("insert", indent)
275 elif c == PyParse.C_BRACKET:
276 # line up with the first (if any) element of the
277 # last open bracket structure; else indent one
Guido van Rossum13205601999-06-11 15:03:00 +0000278 # level beyond the indent of the line with the
279 # last open bracket
Guido van Rossuma6be3871999-06-01 19:52:34 +0000280 self.reindent_to(y.compute_bracket_indent())
281 elif c == PyParse.C_BACKSLASH:
282 # if more than one line in this stmt already, just
Guido van Rossum13205601999-06-11 15:03:00 +0000283 # mimic the current indent; else if initial line
284 # has a start on an assignment stmt, indent to
285 # beyond leftmost =; else to beyond first chunk of
286 # non-whitespace on initial line
Guido van Rossuma6be3871999-06-01 19:52:34 +0000287 if y.get_num_lines_in_stmt() > 1:
288 text.insert("insert", indent)
289 else:
290 self.reindent_to(y.compute_backslash_indent())
Guido van Rossumd93f7391999-06-01 19:47:56 +0000291 else:
Guido van Rossuma6be3871999-06-01 19:52:34 +0000292 assert 0, "bogus continuation type " + `c`
293 return "break"
294
295 # This line starts a brand new stmt; indent relative to
Guido van Rossum13205601999-06-11 15:03:00 +0000296 # indentation of initial line of closest preceding
297 # interesting stmt.
Guido van Rossuma6be3871999-06-01 19:52:34 +0000298 indent = y.get_base_indent_string()
299 text.insert("insert", indent)
300 if y.is_block_opener():
301 self.smart_indent_event(event)
302 elif indent and y.is_block_closer():
Guido van Rossum318a70d1999-05-03 15:49:52 +0000303 self.smart_backspace_event(event)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000304 return "break"
305 finally:
Guido van Rossuma6be3871999-06-01 19:52:34 +0000306 text.see("insert")
Guido van Rossum318a70d1999-05-03 15:49:52 +0000307 text.undo_block_stop()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000308
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000309 auto_indent = newline_and_indent_event
310
Guido van Rossum13205601999-06-11 15:03:00 +0000311 # Our editwin provides a is_char_in_string function that works
312 # with a Tk text index, but PyParse only knows about offsets into
313 # a string. This builds a function for PyParse that accepts an
314 # offset.
Guido van Rossumf4a15081999-06-03 14:32:16 +0000315
316 def _build_char_in_string_func(self, startindex):
317 def inner(offset, _startindex=startindex,
318 _icis=self.editwin.is_char_in_string):
319 return _icis(_startindex + "+%dc" % offset)
320 return inner
321
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000322 def indent_region_event(self, event):
323 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000324 for pos in range(len(lines)):
325 line = lines[pos]
326 if line:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000327 raw, effective = classifyws(line, self.tabwidth)
328 effective = effective + self.indentwidth
329 lines[pos] = self._make_blanks(effective) + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000330 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000331 return "break"
332
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000333 def dedent_region_event(self, event):
334 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000335 for pos in range(len(lines)):
336 line = lines[pos]
337 if line:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000338 raw, effective = classifyws(line, self.tabwidth)
339 effective = max(effective - self.indentwidth, 0)
340 lines[pos] = self._make_blanks(effective) + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000341 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000342 return "break"
343
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000344 def comment_region_event(self, event):
345 head, tail, chars, lines = self.get_region()
Guido van Rossume2571f21999-06-10 14:44:48 +0000346 for pos in range(len(lines) - 1):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000347 line = lines[pos]
Guido van Rossum0fcd6351999-06-08 12:54:23 +0000348 lines[pos] = '##' + line
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000349 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000350
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000351 def uncomment_region_event(self, event):
352 head, tail, chars, lines = self.get_region()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000353 for pos in range(len(lines)):
354 line = lines[pos]
355 if not line:
356 continue
357 if line[:2] == '##':
358 line = line[2:]
359 elif line[:1] == '#':
360 line = line[1:]
361 lines[pos] = line
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000362 self.set_region(head, tail, chars, lines)
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000363
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000364 def tabify_region_event(self, event):
365 head, tail, chars, lines = self.get_region()
Guido van Rossumd93f7391999-06-01 19:47:56 +0000366 tabwidth = self._asktabwidth()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000367 for pos in range(len(lines)):
368 line = lines[pos]
369 if line:
Guido van Rossumd93f7391999-06-01 19:47:56 +0000370 raw, effective = classifyws(line, tabwidth)
371 ntabs, nspaces = divmod(effective, tabwidth)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000372 lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:]
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000373 self.set_region(head, tail, chars, lines)
374
375 def untabify_region_event(self, event):
376 head, tail, chars, lines = self.get_region()
Guido van Rossumd93f7391999-06-01 19:47:56 +0000377 tabwidth = self._asktabwidth()
Guido van Rossumdef2c961999-05-21 04:38:27 +0000378 for pos in range(len(lines)):
Guido van Rossumd93f7391999-06-01 19:47:56 +0000379 lines[pos] = string.expandtabs(lines[pos], tabwidth)
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000380 self.set_region(head, tail, chars, lines)
381
Guido van Rossumdef2c961999-05-21 04:38:27 +0000382 def toggle_tabs_event(self, event):
Guido van Rossum808fa491999-06-02 11:05:19 +0000383 if self.editwin.askyesno(
Guido van Rossumd93f7391999-06-01 19:47:56 +0000384 "Toggle tabs",
Guido van Rossumdef2c961999-05-21 04:38:27 +0000385 "Turn tabs " + ("on", "off")[self.usetabs] + "?",
386 parent=self.text):
387 self.usetabs = not self.usetabs
388 return "break"
389
Guido van Rossumd93f7391999-06-01 19:47:56 +0000390 # XXX this isn't bound to anything -- see class tabwidth comments
Guido van Rossumdef2c961999-05-21 04:38:27 +0000391 def change_tabwidth_event(self, event):
Guido van Rossumd93f7391999-06-01 19:47:56 +0000392 new = self._asktabwidth()
393 if new != self.tabwidth:
Guido van Rossumdef2c961999-05-21 04:38:27 +0000394 self.tabwidth = new
395 self.set_indentation_params(0, guess=0)
396 return "break"
397
398 def change_indentwidth_event(self, event):
Guido van Rossum808fa491999-06-02 11:05:19 +0000399 new = self.editwin.askinteger(
Guido van Rossumd93f7391999-06-01 19:47:56 +0000400 "Indent width",
401 "New indent width (1-16)",
402 parent=self.text,
403 initialvalue=self.indentwidth,
404 minvalue=1,
405 maxvalue=16)
Guido van Rossumdef2c961999-05-21 04:38:27 +0000406 if new and new != self.indentwidth:
407 self.indentwidth = new
408 return "break"
409
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000410 def get_region(self):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000411 text = self.text
Guido van Rossum13205601999-06-11 15:03:00 +0000412 first, last = self.editwin.get_selection_indices()
413 if first and last:
414 head = text.index(first + " linestart")
415 tail = text.index(last + "-1c lineend +1c")
416 else:
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000417 head = text.index("insert linestart")
418 tail = text.index("insert lineend +1c")
419 chars = text.get(head, tail)
420 lines = string.split(chars, "\n")
421 return head, tail, chars, lines
422
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000423 def set_region(self, head, tail, chars, lines):
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000424 text = self.text
425 newchars = string.join(lines, "\n")
426 if newchars == chars:
427 text.bell()
428 return
429 text.tag_remove("sel", "1.0", "end")
430 text.mark_set("insert", head)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000431 text.undo_block_start()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000432 text.delete(head, tail)
433 text.insert(head, newchars)
Guido van Rossum318a70d1999-05-03 15:49:52 +0000434 text.undo_block_stop()
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +0000435 text.tag_add("sel", head, "insert")
Guido van Rossum504b0bf1999-01-02 21:28:54 +0000436
Guido van Rossumdef2c961999-05-21 04:38:27 +0000437 # Make string that displays as n leading blanks.
438
439 def _make_blanks(self, n):
440 if self.usetabs:
441 ntabs, nspaces = divmod(n, self.tabwidth)
442 return '\t' * ntabs + ' ' * nspaces
443 else:
444 return ' ' * n
445
446 # Delete from beginning of line to insert point, then reinsert
447 # column logical (meaning use tabs if appropriate) spaces.
448
449 def reindent_to(self, column):
450 text = self.text
451 text.undo_block_start()
Guido van Rossuma6be3871999-06-01 19:52:34 +0000452 if text.compare("insert linestart", "!=", "insert"):
453 text.delete("insert linestart", "insert")
Guido van Rossumdef2c961999-05-21 04:38:27 +0000454 if column:
455 text.insert("insert", self._make_blanks(column))
456 text.undo_block_stop()
457
Guido van Rossumd93f7391999-06-01 19:47:56 +0000458 def _asktabwidth(self):
Guido van Rossum808fa491999-06-02 11:05:19 +0000459 return self.editwin.askinteger(
Guido van Rossumd93f7391999-06-01 19:47:56 +0000460 "Tab width",
461 "Spaces per tab?",
462 parent=self.text,
463 initialvalue=self.tabwidth,
464 minvalue=1,
465 maxvalue=16) or self.tabwidth
466
Guido van Rossumdef2c961999-05-21 04:38:27 +0000467 # Guess indentwidth from text content.
468 # Return guessed indentwidth. This should not be believed unless
469 # it's in a reasonable range (e.g., it will be 0 if no indented
470 # blocks are found).
471
472 def guess_indent(self):
473 opener, indented = IndentSearcher(self.text, self.tabwidth).run()
474 if opener and indented:
475 raw, indentsmall = classifyws(opener, self.tabwidth)
476 raw, indentlarge = classifyws(indented, self.tabwidth)
477 else:
478 indentsmall = indentlarge = 0
479 return indentlarge - indentsmall
Guido van Rossum17c516e1999-04-19 16:23:15 +0000480
481# "line.col" -> line, as an int
482def index2line(index):
483 return int(float(index))
Guido van Rossumdef2c961999-05-21 04:38:27 +0000484
485# Look at the leading whitespace in s.
486# Return pair (# of leading ws characters,
487# effective # of leading blanks after expanding
488# tabs to width tabwidth)
489
490def classifyws(s, tabwidth):
491 raw = effective = 0
492 for ch in s:
493 if ch == ' ':
494 raw = raw + 1
495 effective = effective + 1
496 elif ch == '\t':
497 raw = raw + 1
498 effective = (effective / tabwidth + 1) * tabwidth
499 else:
500 break
501 return raw, effective
502
503import tokenize
504_tokenize = tokenize
505del tokenize
506
507class IndentSearcher:
508
509 # .run() chews over the Text widget, looking for a block opener
510 # and the stmt following it. Returns a pair,
511 # (line containing block opener, line containing stmt)
512 # Either or both may be None.
513
514 def __init__(self, text, tabwidth):
515 self.text = text
516 self.tabwidth = tabwidth
517 self.i = self.finished = 0
518 self.blkopenline = self.indentedline = None
519
520 def readline(self):
521 if self.finished:
522 return ""
523 i = self.i = self.i + 1
524 mark = `i` + ".0"
525 if self.text.compare(mark, ">=", "end"):
526 return ""
527 return self.text.get(mark, mark + " lineend+1c")
528
529 def tokeneater(self, type, token, start, end, line,
530 INDENT=_tokenize.INDENT,
531 NAME=_tokenize.NAME,
532 OPENERS=('class', 'def', 'for', 'if', 'try', 'while')):
533 if self.finished:
534 pass
535 elif type == NAME and token in OPENERS:
536 self.blkopenline = line
537 elif type == INDENT and self.blkopenline:
538 self.indentedline = line
539 self.finished = 1
540
541 def run(self):
542 save_tabsize = _tokenize.tabsize
543 _tokenize.tabsize = self.tabwidth
544 try:
545 try:
546 _tokenize.tokenize(self.readline, self.tokeneater)
547 except _tokenize.TokenError:
548 # since we cut off the tokenizer early, we can trigger
549 # spurious errors
550 pass
551 finally:
552 _tokenize.tabsize = save_tabsize
553 return self.blkopenline, self.indentedline