blob: 7f5b3ad56e68a59c72fd16b74dc2492f517cd1ab [file] [log] [blame]
David Scherer7aced172000-08-15 01:13:23 +00001import sys
2import os
David Scherer7aced172000-08-15 01:13:23 +00003import re
4import imp
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +00005from itertools import count
Georg Brandl6634bf22008-05-20 07:13:37 +00006from Tkinter import *
7import tkSimpleDialog
8import tkMessageBox
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00009from MultiCall import MultiCallCreator
Kurt B. Kaiserfd182cd2001-07-14 03:58:25 +000010
11import webbrowser
David Scherer7aced172000-08-15 01:13:23 +000012import idlever
13import WindowList
Steven M. Gavac5976402002-01-04 03:06:08 +000014import SearchDialog
15import GrepDialog
16import ReplaceDialog
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +000017import PyParse
Steven M. Gavadc72f482002-01-03 11:51:07 +000018from configHandler import idleConf
Steven M. Gava3b55a892001-11-21 05:56:26 +000019import aboutDialog, textView, configDialog
Ronald Oussoren19302d92006-06-11 14:33:36 +000020import macosxSupport
David Scherer7aced172000-08-15 01:13:23 +000021
22# The default tab setting for a Text widget, in average-width characters.
23TK_TABWIDTH_DEFAULT = 8
24
Kurt B. Kaiserf13447f2009-04-23 02:36:01 +000025def _sphinx_version():
26 "Format sys.version_info to produce the Sphinx version string used to install the chm docs"
27 major, minor, micro, level, serial = sys.version_info
28 release = '%s%s' % (major, minor)
29 if micro:
Benjamin Petersonfb234632009-06-13 15:42:23 +000030 release += '%s' % (micro,)
31 if level == 'candidate':
32 release += 'rc%s' % (serial,)
33 elif level != 'final':
Kurt B. Kaiserf13447f2009-04-23 02:36:01 +000034 release += '%s%s' % (level[0], serial)
35 return release
36
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +000037def _find_module(fullname, path=None):
38 """Version of imp.find_module() that handles hierarchical module names"""
39
40 file = None
41 for tgt in fullname.split('.'):
42 if file is not None:
43 file.close() # close intermediate files
44 (file, filename, descr) = imp.find_module(tgt, path)
45 if descr[2] == imp.PY_SOURCE:
46 break # find but not load the source file
47 module = imp.load_module(tgt, file, filename, descr)
Kurt B. Kaiser69e8afc2003-01-10 21:25:20 +000048 try:
49 path = module.__path__
50 except AttributeError:
51 raise ImportError, 'No source for module ' + module.__name__
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +000052 return file, filename, descr
53
Kurt B. Kaiserdcba6622004-12-21 22:10:32 +000054class EditorWindow(object):
David Scherer7aced172000-08-15 01:13:23 +000055 from Percolator import Percolator
56 from ColorDelegator import ColorDelegator
57 from UndoDelegator import UndoDelegator
Martin v. Löwis307021f2005-11-27 16:59:04 +000058 from IOBinding import IOBinding, filesystemencoding, encoding
David Scherer7aced172000-08-15 01:13:23 +000059 import Bindings
Georg Brandl6634bf22008-05-20 07:13:37 +000060 from Tkinter import Toplevel
David Scherer7aced172000-08-15 01:13:23 +000061 from MultiStatusBar import MultiStatusBar
62
Kurt B. Kaiser114713d2003-01-10 05:07:24 +000063 help_url = None
David Scherer7aced172000-08-15 01:13:23 +000064
65 def __init__(self, flist=None, filename=None, key=None, root=None):
Kurt B. Kaiser114713d2003-01-10 05:07:24 +000066 if EditorWindow.help_url is None:
Thomas Heller84ef1532003-09-23 20:53:10 +000067 dochome = os.path.join(sys.prefix, 'Doc', 'index.html')
Kurt B. Kaiser114713d2003-01-10 05:07:24 +000068 if sys.platform.count('linux'):
69 # look for html docs in a couple of standard places
70 pyver = 'python-docs-' + '%s.%s.%s' % sys.version_info[:3]
71 if os.path.isdir('/var/www/html/python/'): # "python2" rpm
72 dochome = '/var/www/html/python/index.html'
73 else:
74 basepath = '/usr/share/doc/' # standard location
75 dochome = os.path.join(basepath, pyver,
76 'Doc', 'index.html')
Kurt B. Kaiser8aa23922004-07-15 04:54:57 +000077 elif sys.platform[:3] == 'win':
Kurt B. Kaiser090e6362004-07-21 03:33:58 +000078 chmfile = os.path.join(sys.prefix, 'Doc',
Kurt B. Kaiserf13447f2009-04-23 02:36:01 +000079 'Python%s.chm' % _sphinx_version())
Thomas Heller84ef1532003-09-23 20:53:10 +000080 if os.path.isfile(chmfile):
81 dochome = chmfile
Ronald Oussoren19302d92006-06-11 14:33:36 +000082 elif macosxSupport.runningAsOSXApp():
83 # documentation is stored inside the python framework
84 dochome = os.path.join(sys.prefix,
85 'Resources/English.lproj/Documentation/index.html')
Kurt B. Kaiser114713d2003-01-10 05:07:24 +000086 dochome = os.path.normpath(dochome)
87 if os.path.isfile(dochome):
88 EditorWindow.help_url = dochome
Ronald Oussoren19302d92006-06-11 14:33:36 +000089 if sys.platform == 'darwin':
90 # Safari requires real file:-URLs
91 EditorWindow.help_url = 'file://' + EditorWindow.help_url
Kurt B. Kaiser114713d2003-01-10 05:07:24 +000092 else:
Raymond Hettinger7b4c2be2009-01-20 10:46:23 +000093 EditorWindow.help_url = "http://docs.python.org/%d.%d" % sys.version_info[:2]
Steven M. Gavadc72f482002-01-03 11:51:07 +000094 currentTheme=idleConf.CurrentTheme()
David Scherer7aced172000-08-15 01:13:23 +000095 self.flist = flist
96 root = root or flist.root
97 self.root = root
Kurt B. Kaiserb3c4d162006-07-24 17:13:23 +000098 try:
99 sys.ps1
100 except AttributeError:
101 sys.ps1 = '>>> '
David Scherer7aced172000-08-15 01:13:23 +0000102 self.menubar = Menu(root)
Kurt B. Kaiser183403a2004-08-22 05:14:32 +0000103 self.top = top = WindowList.ListedToplevel(root, menu=self.menubar)
Steven M. Gava0c5bc8c2002-03-27 02:25:44 +0000104 if flist:
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000105 self.tkinter_vars = flist.vars
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000106 #self.top.instance_dict makes flist.inversedict avalable to
Steven M. Gava0c5bc8c2002-03-27 02:25:44 +0000107 #configDialog.py so it can access all EditorWindow instaces
Kurt B. Kaisera2946a42006-07-24 18:05:51 +0000108 self.top.instance_dict = flist.inversedict
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000109 else:
110 self.tkinter_vars = {} # keys: Tkinter event names
111 # values: Tkinter variable instances
Kurt B. Kaisera2946a42006-07-24 18:05:51 +0000112 self.top.instance_dict = {}
113 self.recent_files_path = os.path.join(idleConf.GetUserCfgDir(),
Steven M. Gava1d46e402002-03-27 08:40:46 +0000114 'recent-files.lst')
David Scherer7aced172000-08-15 01:13:23 +0000115 self.text_frame = text_frame = Frame(top)
Martin v. Löwis4ebbefe2006-11-22 08:50:02 +0000116 self.vbar = vbar = Scrollbar(text_frame, name='vbar')
Kurt B. Kaiser1061e722003-01-04 01:43:53 +0000117 self.width = idleConf.GetOption('main','EditorWindow','width')
Kurt B. Kaiserce465112009-03-30 16:22:00 +0000118 text_options = {
119 'name': 'text',
120 'padx': 5,
121 'wrap': 'none',
122 'width': self.width,
123 'height': idleConf.GetOption('main', 'EditorWindow', 'height')}
124 if TkVersion >= 8.5:
125 # Starting with tk 8.5 we have to set the new tabstyle option
126 # to 'wordprocessor' to achieve the same display of tabs as in
127 # older tk versions.
128 text_options['tabstyle'] = 'wordprocessor'
129 self.text = text = MultiCallCreator(Text)(text_frame, **text_options)
Kurt B. Kaiser183403a2004-08-22 05:14:32 +0000130 self.top.focused_widget = self.text
David Scherer7aced172000-08-15 01:13:23 +0000131
132 self.createmenubar()
133 self.apply_bindings()
134
135 self.top.protocol("WM_DELETE_WINDOW", self.close)
136 self.top.bind("<<close-window>>", self.close_event)
Ronald Oussoren17db4952006-07-23 09:41:09 +0000137 if macosxSupport.runningAsOSXApp():
138 # Command-W on editorwindows doesn't work without this.
Ronald Oussoren3075e162006-07-25 20:28:55 +0000139 text.bind('<<close-window>>', self.close_event)
Kurt B. Kaiser84f48032002-09-26 22:13:22 +0000140 text.bind("<<cut>>", self.cut)
141 text.bind("<<copy>>", self.copy)
142 text.bind("<<paste>>", self.paste)
David Scherer7aced172000-08-15 01:13:23 +0000143 text.bind("<<center-insert>>", self.center_insert_event)
144 text.bind("<<help>>", self.help_dialog)
David Scherer7aced172000-08-15 01:13:23 +0000145 text.bind("<<python-docs>>", self.python_docs)
146 text.bind("<<about-idle>>", self.about_dialog)
Steven M. Gava3b55a892001-11-21 05:56:26 +0000147 text.bind("<<open-config-dialog>>", self.config_dialog)
David Scherer7aced172000-08-15 01:13:23 +0000148 text.bind("<<open-module>>", self.open_module)
149 text.bind("<<do-nothing>>", lambda event: "break")
150 text.bind("<<select-all>>", self.select_all)
151 text.bind("<<remove-selection>>", self.remove_selection)
Steven M. Gavac5976402002-01-04 03:06:08 +0000152 text.bind("<<find>>", self.find_event)
153 text.bind("<<find-again>>", self.find_again_event)
154 text.bind("<<find-in-files>>", self.find_in_files_event)
155 text.bind("<<find-selection>>", self.find_selection_event)
156 text.bind("<<replace>>", self.replace_event)
157 text.bind("<<goto-line>>", self.goto_line_event)
David Scherer7aced172000-08-15 01:13:23 +0000158 text.bind("<3>", self.right_menu_event)
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +0000159 text.bind("<<smart-backspace>>",self.smart_backspace_event)
160 text.bind("<<newline-and-indent>>",self.newline_and_indent_event)
161 text.bind("<<smart-indent>>",self.smart_indent_event)
162 text.bind("<<indent-region>>",self.indent_region_event)
163 text.bind("<<dedent-region>>",self.dedent_region_event)
164 text.bind("<<comment-region>>",self.comment_region_event)
165 text.bind("<<uncomment-region>>",self.uncomment_region_event)
166 text.bind("<<tabify-region>>",self.tabify_region_event)
167 text.bind("<<untabify-region>>",self.untabify_region_event)
168 text.bind("<<toggle-tabs>>",self.toggle_tabs_event)
169 text.bind("<<change-indentwidth>>",self.change_indentwidth_event)
Kurt B. Kaiser5ec186b2003-01-17 04:04:06 +0000170 text.bind("<Left>", self.move_at_edge_if_selection(0))
171 text.bind("<Right>", self.move_at_edge_if_selection(1))
Kurt B. Kaiser3069dbb2005-01-28 00:16:16 +0000172 text.bind("<<del-word-left>>", self.del_word_left)
173 text.bind("<<del-word-right>>", self.del_word_right)
Kurt B. Kaiser93cdae52008-04-27 21:07:41 +0000174 text.bind("<<beginning-of-line>>", self.home_callback)
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000175
David Scherer7aced172000-08-15 01:13:23 +0000176 if flist:
177 flist.inversedict[self] = key
178 if key:
179 flist.dict[key] = self
Kurt B. Kaiserd2f48612003-06-05 02:34:04 +0000180 text.bind("<<open-new-window>>", self.new_callback)
David Scherer7aced172000-08-15 01:13:23 +0000181 text.bind("<<close-all-windows>>", self.flist.close_all_callback)
182 text.bind("<<open-class-browser>>", self.open_class_browser)
183 text.bind("<<open-path-browser>>", self.open_path_browser)
184
Steven M. Gava898a3652001-10-07 11:10:44 +0000185 self.set_status_bar()
David Scherer7aced172000-08-15 01:13:23 +0000186 vbar['command'] = text.yview
187 vbar.pack(side=RIGHT, fill=Y)
David Scherer7aced172000-08-15 01:13:23 +0000188 text['yscrollcommand'] = vbar.set
Kurt B. Kaiseracdef852005-01-31 03:34:26 +0000189 fontWeight = 'normal'
190 if idleConf.GetOption('main', 'EditorWindow', 'font-bold', type='bool'):
Steven M. Gavab1585412002-03-12 00:21:56 +0000191 fontWeight='bold'
Kurt B. Kaiseracdef852005-01-31 03:34:26 +0000192 text.config(font=(idleConf.GetOption('main', 'EditorWindow', 'font'),
193 idleConf.GetOption('main', 'EditorWindow', 'font-size'),
194 fontWeight))
David Scherer7aced172000-08-15 01:13:23 +0000195 text_frame.pack(side=LEFT, fill=BOTH, expand=1)
196 text.pack(side=TOP, fill=BOTH, expand=1)
197 text.focus_set()
198
Kurt B. Kaiser6af44982005-01-19 00:22:59 +0000199 # usetabs true -> literal tab characters are used by indent and
200 # dedent cmds, possibly mixed with spaces if
201 # indentwidth is not a multiple of tabwidth,
202 # which will cause Tabnanny to nag!
203 # false -> tab characters are converted to spaces by indent
204 # and dedent cmds, and ditto TAB keystrokes
Kurt B. Kaiseracdef852005-01-31 03:34:26 +0000205 # Although use-spaces=0 can be configured manually in config-main.def,
206 # configuration of tabs v. spaces is not supported in the configuration
207 # dialog. IDLE promotes the preferred Python indentation: use spaces!
208 usespaces = idleConf.GetOption('main', 'Indent', 'use-spaces', type='bool')
209 self.usetabs = not usespaces
Kurt B. Kaiser6af44982005-01-19 00:22:59 +0000210
211 # tabwidth is the display width of a literal tab character.
212 # CAUTION: telling Tk to use anything other than its default
213 # tab setting causes it to use an entirely different tabbing algorithm,
214 # treating tab stops as fixed distances from the left margin.
215 # Nobody expects this, so for now tabwidth should never be changed.
Kurt B. Kaiseracdef852005-01-31 03:34:26 +0000216 self.tabwidth = 8 # must remain 8 until Tk is fixed.
217
218 # indentwidth is the number of screen characters per indent level.
219 # The recommended Python indentation is four spaces.
220 self.indentwidth = self.tabwidth
221 self.set_notabs_indentwidth()
Kurt B. Kaiser6af44982005-01-19 00:22:59 +0000222
223 # If context_use_ps1 is true, parsing searches back for a ps1 line;
224 # else searches for a popular (if, def, ...) Python stmt.
225 self.context_use_ps1 = False
226
227 # When searching backwards for a reliable place to begin parsing,
228 # first start num_context_lines[0] lines back, then
229 # num_context_lines[1] lines back if that didn't work, and so on.
230 # The last value should be huge (larger than the # of lines in a
231 # conceivable file).
232 # Making the initial values larger slows things down more often.
233 self.num_context_lines = 50, 500, 5000000
234
David Scherer7aced172000-08-15 01:13:23 +0000235 self.per = per = self.Percolator(text)
Kurt B. Kaiserdc1e7092002-07-11 04:33:41 +0000236
237 self.undo = undo = self.UndoDelegator()
238 per.insertfilter(undo)
239 text.undo_block_start = undo.undo_block_start
240 text.undo_block_stop = undo.undo_block_stop
241 undo.set_saved_change_hook(self.saved_change_hook)
242
243 # IOBinding implements file I/O and printing functionality
David Scherer7aced172000-08-15 01:13:23 +0000244 self.io = io = self.IOBinding(self)
Kurt B. Kaiserdc1e7092002-07-11 04:33:41 +0000245 io.set_filename_change_hook(self.filename_change_hook)
246
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000247 # Create the recent files submenu
248 self.recent_files_menu = Menu(self.menubar)
249 self.menudict['file'].insert_cascade(3, label='Recent Files',
250 underline=0,
251 menu=self.recent_files_menu)
252 self.update_recent_files_list()
David Scherer7aced172000-08-15 01:13:23 +0000253
Kurt B. Kaiserf05fa332008-02-15 22:25:09 +0000254 self.color = None # initialized below in self.ResetColorizer
David Scherer7aced172000-08-15 01:13:23 +0000255 if filename:
Kurt B. Kaiserd2f48612003-06-05 02:34:04 +0000256 if os.path.exists(filename) and not os.path.isdir(filename):
David Scherer7aced172000-08-15 01:13:23 +0000257 io.loadfile(filename)
258 else:
259 io.set_filename(filename)
Kurt B. Kaiserf05fa332008-02-15 22:25:09 +0000260 self.ResetColorizer()
David Scherer7aced172000-08-15 01:13:23 +0000261 self.saved_change_hook()
262
Kurt B. Kaiser6af44982005-01-19 00:22:59 +0000263 self.set_indentation_params(self.ispythonsource(filename))
264
David Scherer7aced172000-08-15 01:13:23 +0000265 self.load_extensions()
266
267 menu = self.menudict.get('windows')
268 if menu:
269 end = menu.index("end")
270 if end is None:
271 end = -1
272 if end >= 0:
273 menu.add_separator()
274 end = end + 1
275 self.wmenu_end = end
276 WindowList.register_callback(self.postwindowsmenu)
277
278 # Some abstractions so IDLE extensions are cross-IDE
279 self.askyesno = tkMessageBox.askyesno
280 self.askinteger = tkSimpleDialog.askinteger
281 self.showerror = tkMessageBox.showerror
282
Martin v. Löwis307021f2005-11-27 16:59:04 +0000283 def _filename_to_unicode(self, filename):
284 """convert filename to unicode in order to display it in Tk"""
285 if isinstance(filename, unicode) or not filename:
286 return filename
287 else:
288 try:
289 return filename.decode(self.filesystemencoding)
290 except UnicodeDecodeError:
291 # XXX
292 try:
293 return filename.decode(self.encoding)
294 except UnicodeDecodeError:
295 # byte-to-byte conversion
296 return filename.decode('iso8859-1')
297
Kurt B. Kaiserd2f48612003-06-05 02:34:04 +0000298 def new_callback(self, event):
299 dirname, basename = self.io.defaultfilename()
300 self.flist.new(dirname)
301 return "break"
302
Kurt B. Kaiser93cdae52008-04-27 21:07:41 +0000303 def home_callback(self, event):
304 if (event.state & 12) != 0 and event.keysym == "Home":
305 # state&1==shift, state&4==control, state&8==alt
306 return # <Modifier-Home>; fall back to class binding
307
308 if self.text.index("iomark") and \
309 self.text.compare("iomark", "<=", "insert lineend") and \
310 self.text.compare("insert linestart", "<=", "iomark"):
311 insertpt = int(self.text.index("iomark").split(".")[1])
312 else:
313 line = self.text.get("insert linestart", "insert lineend")
314 for insertpt in xrange(len(line)):
315 if line[insertpt] not in (' ','\t'):
316 break
317 else:
318 insertpt=len(line)
319
320 lineat = int(self.text.index("insert").split('.')[1])
321
322 if insertpt == lineat:
323 insertpt = 0
324
325 dest = "insert linestart+"+str(insertpt)+"c"
326
327 if (event.state&1) == 0:
328 # shift not pressed
329 self.text.tag_remove("sel", "1.0", "end")
330 else:
331 if not self.text.index("sel.first"):
332 self.text.mark_set("anchor","insert")
333
334 first = self.text.index(dest)
335 last = self.text.index("anchor")
336
337 if self.text.compare(first,">",last):
338 first,last = last,first
339
340 self.text.tag_remove("sel", "1.0", "end")
341 self.text.tag_add("sel", first, last)
342
343 self.text.mark_set("insert", dest)
344 self.text.see("insert")
345 return "break"
346
David Scherer7aced172000-08-15 01:13:23 +0000347 def set_status_bar(self):
Steven M. Gava898a3652001-10-07 11:10:44 +0000348 self.status_bar = self.MultiStatusBar(self.top)
Ronald Oussoren19302d92006-06-11 14:33:36 +0000349 if macosxSupport.runningAsOSXApp():
350 # Insert some padding to avoid obscuring some of the statusbar
351 # by the resize widget.
352 self.status_bar.set_label('_padding1', ' ', side=RIGHT)
David Scherer7aced172000-08-15 01:13:23 +0000353 self.status_bar.set_label('column', 'Col: ?', side=RIGHT)
354 self.status_bar.set_label('line', 'Ln: ?', side=RIGHT)
355 self.status_bar.pack(side=BOTTOM, fill=X)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000356 self.text.bind("<<set-line-and-column>>", self.set_line_and_column)
357 self.text.event_add("<<set-line-and-column>>",
358 "<KeyRelease>", "<ButtonRelease>")
David Scherer7aced172000-08-15 01:13:23 +0000359 self.text.after_idle(self.set_line_and_column)
360
361 def set_line_and_column(self, event=None):
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +0000362 line, column = self.text.index(INSERT).split('.')
David Scherer7aced172000-08-15 01:13:23 +0000363 self.status_bar.set_label('column', 'Col: %s' % column)
364 self.status_bar.set_label('line', 'Ln: %s' % line)
365
David Scherer7aced172000-08-15 01:13:23 +0000366 menu_specs = [
367 ("file", "_File"),
368 ("edit", "_Edit"),
369 ("format", "F_ormat"),
370 ("run", "_Run"),
Kurt B. Kaiser1061e722003-01-04 01:43:53 +0000371 ("options", "_Options"),
David Scherer7aced172000-08-15 01:13:23 +0000372 ("windows", "_Windows"),
373 ("help", "_Help"),
374 ]
375
Ronald Oussoren19302d92006-06-11 14:33:36 +0000376 if macosxSupport.runningAsOSXApp():
377 del menu_specs[-3]
378 menu_specs[-2] = ("windows", "_Window")
379
380
David Scherer7aced172000-08-15 01:13:23 +0000381 def createmenubar(self):
382 mbar = self.menubar
383 self.menudict = menudict = {}
384 for name, label in self.menu_specs:
385 underline, label = prepstr(label)
386 menudict[name] = menu = Menu(mbar, name=name)
387 mbar.add_cascade(label=label, menu=menu, underline=underline)
Ronald Oussoren19302d92006-06-11 14:33:36 +0000388
Ronald Oussorena97063a2009-03-04 21:35:05 +0000389 if macosxSupport.runningAsOSXApp():
Ronald Oussoren19302d92006-06-11 14:33:36 +0000390 # Insert the application menu
391 menudict['application'] = menu = Menu(mbar, name='apple')
392 mbar.add_cascade(label='IDLE', menu=menu)
393
David Scherer7aced172000-08-15 01:13:23 +0000394 self.fill_menus()
Kurt B. Kaiser8e92bf72003-01-14 22:03:31 +0000395 self.base_helpmenu_length = self.menudict['help'].index(END)
396 self.reset_help_menu_entries()
David Scherer7aced172000-08-15 01:13:23 +0000397
398 def postwindowsmenu(self):
399 # Only called when Windows menu exists
David Scherer7aced172000-08-15 01:13:23 +0000400 menu = self.menudict['windows']
401 end = menu.index("end")
402 if end is None:
403 end = -1
404 if end > self.wmenu_end:
405 menu.delete(self.wmenu_end+1, end)
406 WindowList.add_windows_to_menu(menu)
407
408 rmenu = None
409
410 def right_menu_event(self, event):
411 self.text.tag_remove("sel", "1.0", "end")
412 self.text.mark_set("insert", "@%d,%d" % (event.x, event.y))
413 if not self.rmenu:
414 self.make_rmenu()
415 rmenu = self.rmenu
416 self.event = event
417 iswin = sys.platform[:3] == 'win'
418 if iswin:
419 self.text.config(cursor="arrow")
420 rmenu.tk_popup(event.x_root, event.y_root)
421 if iswin:
422 self.text.config(cursor="ibeam")
423
424 rmenu_specs = [
425 # ("Label", "<<virtual-event>>"), ...
426 ("Close", "<<close-window>>"), # Example
427 ]
428
429 def make_rmenu(self):
430 rmenu = Menu(self.text, tearoff=0)
431 for label, eventname in self.rmenu_specs:
432 def command(text=self.text, eventname=eventname):
433 text.event_generate(eventname)
434 rmenu.add_command(label=label, command=command)
435 self.rmenu = rmenu
436
437 def about_dialog(self, event=None):
Kurt B. Kaiserd78b2302003-06-12 04:03:49 +0000438 aboutDialog.AboutDialog(self.top,'About IDLE')
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000439
Steven M. Gava3b55a892001-11-21 05:56:26 +0000440 def config_dialog(self, event=None):
441 configDialog.ConfigDialog(self.top,'Settings')
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000442
David Scherer7aced172000-08-15 01:13:23 +0000443 def help_dialog(self, event=None):
Steven M. Gavab9d07b52001-07-31 11:11:38 +0000444 fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt')
Kurt B. Kaiserd5f49102007-10-04 02:53:07 +0000445 textView.view_file(self.top,'Help',fn)
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000446
Kurt B. Kaiser114713d2003-01-10 05:07:24 +0000447 def python_docs(self, event=None):
Kurt B. Kaiser8aa23922004-07-15 04:54:57 +0000448 if sys.platform[:3] == 'win':
Steven M. Gava931625d2002-04-22 00:38:26 +0000449 os.startfile(self.help_url)
Kurt B. Kaiser114713d2003-01-10 05:07:24 +0000450 else:
451 webbrowser.open(self.help_url)
Kurt B. Kaiser8aa23922004-07-15 04:54:57 +0000452 return "break"
David Scherer7aced172000-08-15 01:13:23 +0000453
Kurt B. Kaiser84f48032002-09-26 22:13:22 +0000454 def cut(self,event):
455 self.text.event_generate("<<Cut>>")
456 return "break"
457
458 def copy(self,event):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000459 if not self.text.tag_ranges("sel"):
460 # There is no selection, so do nothing and maybe interrupt.
461 return
Kurt B. Kaiser84f48032002-09-26 22:13:22 +0000462 self.text.event_generate("<<Copy>>")
463 return "break"
464
465 def paste(self,event):
466 self.text.event_generate("<<Paste>>")
Kurt B. Kaiser631fee62007-10-10 01:06:47 +0000467 self.text.see("insert")
Kurt B. Kaiser84f48032002-09-26 22:13:22 +0000468 return "break"
469
David Scherer7aced172000-08-15 01:13:23 +0000470 def select_all(self, event=None):
471 self.text.tag_add("sel", "1.0", "end-1c")
472 self.text.mark_set("insert", "1.0")
473 self.text.see("insert")
474 return "break"
475
476 def remove_selection(self, event=None):
477 self.text.tag_remove("sel", "1.0", "end")
478 self.text.see("insert")
479
Kurt B. Kaiser5ec186b2003-01-17 04:04:06 +0000480 def move_at_edge_if_selection(self, edge_index):
481 """Cursor move begins at start or end of selection
482
483 When a left/right cursor key is pressed create and return to Tkinter a
484 function which causes a cursor move from the associated edge of the
485 selection.
486
487 """
488 self_text_index = self.text.index
489 self_text_mark_set = self.text.mark_set
490 edges_table = ("sel.first+1c", "sel.last-1c")
491 def move_at_edge(event):
492 if (event.state & 5) == 0: # no shift(==1) or control(==4) pressed
493 try:
494 self_text_index("sel.first")
495 self_text_mark_set("insert", edges_table[edge_index])
496 except TclError:
497 pass
498 return move_at_edge
499
Kurt B. Kaiser3069dbb2005-01-28 00:16:16 +0000500 def del_word_left(self, event):
501 self.text.event_generate('<Meta-Delete>')
502 return "break"
503
504 def del_word_right(self, event):
505 self.text.event_generate('<Meta-d>')
506 return "break"
507
Steven M. Gavac5976402002-01-04 03:06:08 +0000508 def find_event(self, event):
509 SearchDialog.find(self.text)
510 return "break"
511
512 def find_again_event(self, event):
513 SearchDialog.find_again(self.text)
514 return "break"
515
516 def find_selection_event(self, event):
517 SearchDialog.find_selection(self.text)
518 return "break"
519
520 def find_in_files_event(self, event):
521 GrepDialog.grep(self.text, self.io, self.flist)
522 return "break"
523
524 def replace_event(self, event):
525 ReplaceDialog.replace(self.text)
526 return "break"
527
528 def goto_line_event(self, event):
529 text = self.text
530 lineno = tkSimpleDialog.askinteger("Goto",
531 "Go to line number:",parent=text)
532 if lineno is None:
533 return "break"
534 if lineno <= 0:
535 text.bell()
536 return "break"
537 text.mark_set("insert", "%d.0" % lineno)
538 text.see("insert")
539
David Scherer7aced172000-08-15 01:13:23 +0000540 def open_module(self, event=None):
541 # XXX Shouldn't this be in IOBinding or in FileList?
542 try:
543 name = self.text.get("sel.first", "sel.last")
544 except TclError:
545 name = ""
546 else:
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +0000547 name = name.strip()
Guido van Rossum852f35b2003-06-05 11:36:55 +0000548 name = tkSimpleDialog.askstring("Module",
549 "Enter the name of a Python module\n"
550 "to search on sys.path and open:",
551 parent=self.text, initialvalue=name)
552 if name:
553 name = name.strip()
David Scherer7aced172000-08-15 01:13:23 +0000554 if not name:
Guido van Rossum852f35b2003-06-05 11:36:55 +0000555 return
David Scherer7aced172000-08-15 01:13:23 +0000556 # XXX Ought to insert current file's directory in front of path
557 try:
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +0000558 (f, file, (suffix, mode, type)) = _find_module(name)
David Scherer7aced172000-08-15 01:13:23 +0000559 except (NameError, ImportError), msg:
560 tkMessageBox.showerror("Import error", str(msg), parent=self.text)
561 return
562 if type != imp.PY_SOURCE:
563 tkMessageBox.showerror("Unsupported type",
564 "%s is not a source module" % name, parent=self.text)
565 return
566 if f:
567 f.close()
568 if self.flist:
569 self.flist.open(file)
570 else:
571 self.io.loadfile(file)
572
573 def open_class_browser(self, event=None):
574 filename = self.io.filename
575 if not filename:
576 tkMessageBox.showerror(
577 "No filename",
578 "This buffer has no associated filename",
579 master=self.text)
580 self.text.focus_set()
581 return None
582 head, tail = os.path.split(filename)
583 base, ext = os.path.splitext(tail)
584 import ClassBrowser
585 ClassBrowser.ClassBrowser(self.flist, base, [head])
586
587 def open_path_browser(self, event=None):
588 import PathBrowser
589 PathBrowser.PathBrowser(self.flist)
590
591 def gotoline(self, lineno):
592 if lineno is not None and lineno > 0:
593 self.text.mark_set("insert", "%d.0" % lineno)
594 self.text.tag_remove("sel", "1.0", "end")
595 self.text.tag_add("sel", "insert", "insert +1l")
596 self.center()
597
598 def ispythonsource(self, filename):
Kurt B. Kaiserdf506ea2005-06-12 04:33:30 +0000599 if not filename or os.path.isdir(filename):
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +0000600 return True
David Scherer7aced172000-08-15 01:13:23 +0000601 base, ext = os.path.splitext(os.path.basename(filename))
602 if os.path.normcase(ext) in (".py", ".pyw"):
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +0000603 return True
David Scherer7aced172000-08-15 01:13:23 +0000604 try:
605 f = open(filename)
606 line = f.readline()
607 f.close()
608 except IOError:
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +0000609 return False
Kurt B. Kaiser83a35602002-12-20 17:18:03 +0000610 return line.startswith('#!') and line.find('python') >= 0
David Scherer7aced172000-08-15 01:13:23 +0000611
612 def close_hook(self):
613 if self.flist:
Kurt B. Kaiser0b634ef2007-10-04 02:09:17 +0000614 self.flist.unregister_maybe_terminate(self)
615 self.flist = None
David Scherer7aced172000-08-15 01:13:23 +0000616
617 def set_close_hook(self, close_hook):
618 self.close_hook = close_hook
619
620 def filename_change_hook(self):
621 if self.flist:
622 self.flist.filename_changed_edit(self)
623 self.saved_change_hook()
Kurt B. Kaiser260cb902003-06-06 21:58:38 +0000624 self.top.update_windowlist_registry(self)
Kurt B. Kaiserf05fa332008-02-15 22:25:09 +0000625 self.ResetColorizer()
David Scherer7aced172000-08-15 01:13:23 +0000626
Kurt B. Kaiserf05fa332008-02-15 22:25:09 +0000627 def _addcolorizer(self):
David Scherer7aced172000-08-15 01:13:23 +0000628 if self.color:
629 return
Kurt B. Kaiserf05fa332008-02-15 22:25:09 +0000630 if self.ispythonsource(self.io.filename):
631 self.color = self.ColorDelegator()
632 # can add more colorizers here...
633 if self.color:
634 self.per.removefilter(self.undo)
635 self.per.insertfilter(self.color)
636 self.per.insertfilter(self.undo)
David Scherer7aced172000-08-15 01:13:23 +0000637
Kurt B. Kaiserf05fa332008-02-15 22:25:09 +0000638 def _rmcolorizer(self):
David Scherer7aced172000-08-15 01:13:23 +0000639 if not self.color:
640 return
Kurt B. Kaiserdf506ea2005-06-12 04:33:30 +0000641 self.color.removecolors()
David Scherer7aced172000-08-15 01:13:23 +0000642 self.per.removefilter(self.color)
643 self.color = None
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000644
Steven M. Gavab77d3432002-03-02 07:16:21 +0000645 def ResetColorizer(self):
Kurt B. Kaiserf05fa332008-02-15 22:25:09 +0000646 "Update the colour theme"
647 # Called from self.filename_change_hook and from configDialog.py
648 self._rmcolorizer()
649 self._addcolorizer()
Kurt B. Kaiser73360a32004-03-08 18:15:31 +0000650 theme = idleConf.GetOption('main','Theme','name')
Kurt B. Kaiserf05fa332008-02-15 22:25:09 +0000651 normal_colors = idleConf.GetHighlight(theme, 'normal')
652 cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg')
653 select_colors = idleConf.GetHighlight(theme, 'hilite')
654 self.text.config(
655 foreground=normal_colors['foreground'],
656 background=normal_colors['background'],
657 insertbackground=cursor_color,
658 selectforeground=select_colors['foreground'],
659 selectbackground=select_colors['background'],
660 )
David Scherer7aced172000-08-15 01:13:23 +0000661
Steven M. Gavab1585412002-03-12 00:21:56 +0000662 def ResetFont(self):
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000663 "Update the text widgets' font if it is changed"
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000664 # Called from configDialog.py
Steven M. Gavab1585412002-03-12 00:21:56 +0000665 fontWeight='normal'
666 if idleConf.GetOption('main','EditorWindow','font-bold',type='bool'):
667 fontWeight='bold'
668 self.text.config(font=(idleConf.GetOption('main','EditorWindow','font'),
669 idleConf.GetOption('main','EditorWindow','font-size'),
670 fontWeight))
671
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000672 def RemoveKeybindings(self):
673 "Remove the keybindings before they are changed."
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000674 # Called from configDialog.py
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000675 self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
Steven M. Gavadbfe92c2002-03-18 02:38:44 +0000676 for event, keylist in keydefs.items():
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000677 self.text.event_delete(event, *keylist)
678 for extensionName in self.get_standard_extension_names():
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000679 xkeydefs = idleConf.GetExtensionBindings(extensionName)
680 if xkeydefs:
681 for event, keylist in xkeydefs.items():
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000682 self.text.event_delete(event, *keylist)
683
684 def ApplyKeybindings(self):
685 "Update the keybindings after they are changed"
686 # Called from configDialog.py
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000687 self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
Steven M. Gavadbfe92c2002-03-18 02:38:44 +0000688 self.apply_bindings()
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000689 for extensionName in self.get_standard_extension_names():
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000690 xkeydefs = idleConf.GetExtensionBindings(extensionName)
691 if xkeydefs:
692 self.apply_bindings(xkeydefs)
Steven M. Gavadbfe92c2002-03-18 02:38:44 +0000693 #update menu accelerators
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000694 menuEventDict = {}
Steven M. Gavadbfe92c2002-03-18 02:38:44 +0000695 for menu in self.Bindings.menudefs:
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000696 menuEventDict[menu[0]] = {}
Steven M. Gavadbfe92c2002-03-18 02:38:44 +0000697 for item in menu[1]:
698 if item:
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000699 menuEventDict[menu[0]][prepstr(item[0])[1]] = item[1]
Steven M. Gavadbfe92c2002-03-18 02:38:44 +0000700 for menubarItem in self.menudict.keys():
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000701 menu = self.menudict[menubarItem]
702 end = menu.index(END) + 1
703 for index in range(0, end):
704 if menu.type(index) == 'command':
705 accel = menu.entrycget(index, 'accelerator')
Steven M. Gavadbfe92c2002-03-18 02:38:44 +0000706 if accel:
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000707 itemName = menu.entrycget(index, 'label')
708 event = ''
Steven M. Gavadbfe92c2002-03-18 02:38:44 +0000709 if menuEventDict.has_key(menubarItem):
710 if menuEventDict[menubarItem].has_key(itemName):
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000711 event = menuEventDict[menubarItem][itemName]
Steven M. Gavadbfe92c2002-03-18 02:38:44 +0000712 if event:
Kurt B. Kaiser5a67f9b2005-11-22 01:47:14 +0000713 accel = get_accelerator(keydefs, event)
714 menu.entryconfig(index, accelerator=accel)
Steven M. Gavadbfe92c2002-03-18 02:38:44 +0000715
Kurt B. Kaiseracdef852005-01-31 03:34:26 +0000716 def set_notabs_indentwidth(self):
717 "Update the indentwidth if changed and not using tabs in this window"
718 # Called from configDialog.py
719 if not self.usetabs:
720 self.indentwidth = idleConf.GetOption('main', 'Indent','num-spaces',
721 type='int')
722
Kurt B. Kaiser8e92bf72003-01-14 22:03:31 +0000723 def reset_help_menu_entries(self):
724 "Update the additional help entries on the Help menu"
725 help_list = idleConf.GetAllExtraHelpSourcesList()
726 helpmenu = self.menudict['help']
727 # first delete the extra help entries, if any
728 helpmenu_length = helpmenu.index(END)
729 if helpmenu_length > self.base_helpmenu_length:
730 helpmenu.delete((self.base_helpmenu_length + 1), helpmenu_length)
731 # then rebuild them
732 if help_list:
733 helpmenu.add_separator()
734 for entry in help_list:
735 cmd = self.__extra_help_callback(entry[1])
736 helpmenu.add_command(label=entry[0], command=cmd)
737 # and update the menu dictionary
738 self.menudict['help'] = helpmenu
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000739
Kurt B. Kaiser8e92bf72003-01-14 22:03:31 +0000740 def __extra_help_callback(self, helpfile):
741 "Create a callback with the helpfile value frozen at definition time"
742 def display_extra_help(helpfile=helpfile):
Georg Brandlb2afe852006-06-09 20:43:48 +0000743 if not helpfile.startswith(('www', 'http')):
Kurt B. Kaiser8aa23922004-07-15 04:54:57 +0000744 url = os.path.normpath(helpfile)
745 if sys.platform[:3] == 'win':
746 os.startfile(helpfile)
747 else:
748 webbrowser.open(helpfile)
Kurt B. Kaiser8e92bf72003-01-14 22:03:31 +0000749 return display_extra_help
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000750
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000751 def update_recent_files_list(self, new_file=None):
752 "Load and update the recent files list and menus"
753 rf_list = []
754 if os.path.exists(self.recent_files_path):
755 rf_list_file = open(self.recent_files_path,'r')
Steven M. Gava1d46e402002-03-27 08:40:46 +0000756 try:
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000757 rf_list = rf_list_file.readlines()
Steven M. Gava1d46e402002-03-27 08:40:46 +0000758 finally:
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000759 rf_list_file.close()
760 if new_file:
761 new_file = os.path.abspath(new_file) + '\n'
762 if new_file in rf_list:
763 rf_list.remove(new_file) # move to top
764 rf_list.insert(0, new_file)
765 # clean and save the recent files list
766 bad_paths = []
767 for path in rf_list:
768 if '\0' in path or not os.path.exists(path[0:-1]):
769 bad_paths.append(path)
770 rf_list = [path for path in rf_list if path not in bad_paths]
771 ulchars = "1234567890ABCDEFGHIJK"
772 rf_list = rf_list[0:len(ulchars)]
773 rf_file = open(self.recent_files_path, 'w')
Steven M. Gava1d46e402002-03-27 08:40:46 +0000774 try:
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000775 rf_file.writelines(rf_list)
Steven M. Gava1d46e402002-03-27 08:40:46 +0000776 finally:
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000777 rf_file.close()
778 # for each edit window instance, construct the recent files menu
779 for instance in self.top.instance_dict.keys():
780 menu = instance.recent_files_menu
781 menu.delete(1, END) # clear, and rebuild:
782 for i, file in zip(count(), rf_list):
783 file_name = file[0:-1] # zap \n
Martin v. Löwis307021f2005-11-27 16:59:04 +0000784 # make unicode string to display non-ASCII chars correctly
785 ufile_name = self._filename_to_unicode(file_name)
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000786 callback = instance.__recent_file_callback(file_name)
Martin v. Löwis307021f2005-11-27 16:59:04 +0000787 menu.add_command(label=ulchars[i] + " " + ufile_name,
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000788 command=callback,
789 underline=0)
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000790
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000791 def __recent_file_callback(self, file_name):
792 def open_recent_file(fn_closure=file_name):
793 self.io.open(editFile=fn_closure)
794 return open_recent_file
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000795
David Scherer7aced172000-08-15 01:13:23 +0000796 def saved_change_hook(self):
797 short = self.short_title()
798 long = self.long_title()
799 if short and long:
800 title = short + " - " + long
801 elif short:
802 title = short
803 elif long:
804 title = long
805 else:
806 title = "Untitled"
807 icon = short or long or title
808 if not self.get_saved():
809 title = "*%s*" % title
810 icon = "*%s" % icon
811 self.top.wm_title(title)
812 self.top.wm_iconname(icon)
813
814 def get_saved(self):
815 return self.undo.get_saved()
816
817 def set_saved(self, flag):
818 self.undo.set_saved(flag)
819
820 def reset_undo(self):
821 self.undo.reset_undo()
822
823 def short_title(self):
824 filename = self.io.filename
825 if filename:
826 filename = os.path.basename(filename)
Martin v. Löwis307021f2005-11-27 16:59:04 +0000827 # return unicode string to display non-ASCII chars correctly
828 return self._filename_to_unicode(filename)
David Scherer7aced172000-08-15 01:13:23 +0000829
830 def long_title(self):
Martin v. Löwis307021f2005-11-27 16:59:04 +0000831 # return unicode string to display non-ASCII chars correctly
832 return self._filename_to_unicode(self.io.filename or "")
David Scherer7aced172000-08-15 01:13:23 +0000833
834 def center_insert_event(self, event):
835 self.center()
836
837 def center(self, mark="insert"):
838 text = self.text
839 top, bot = self.getwindowlines()
840 lineno = self.getlineno(mark)
841 height = bot - top
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +0000842 newtop = max(1, lineno - height//2)
David Scherer7aced172000-08-15 01:13:23 +0000843 text.yview(float(newtop))
844
845 def getwindowlines(self):
846 text = self.text
847 top = self.getlineno("@0,0")
848 bot = self.getlineno("@0,65535")
849 if top == bot and text.winfo_height() == 1:
850 # Geometry manager hasn't run yet
851 height = int(text['height'])
852 bot = top + height - 1
853 return top, bot
854
855 def getlineno(self, mark="insert"):
856 text = self.text
857 return int(float(text.index(mark)))
858
Kurt B. Kaiser1061e722003-01-04 01:43:53 +0000859 def get_geometry(self):
860 "Return (width, height, x, y)"
861 geom = self.top.wm_geometry()
862 m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
863 tuple = (map(int, m.groups()))
864 return tuple
865
David Scherer7aced172000-08-15 01:13:23 +0000866 def close_event(self, event):
867 self.close()
868
869 def maybesave(self):
870 if self.io:
Steven M. Gava67716b52002-02-26 02:31:03 +0000871 if not self.get_saved():
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +0000872 if self.top.state()!='normal':
Steven M. Gava67716b52002-02-26 02:31:03 +0000873 self.top.deiconify()
874 self.top.lower()
875 self.top.lift()
David Scherer7aced172000-08-15 01:13:23 +0000876 return self.io.maybesave()
877
878 def close(self):
David Scherer7aced172000-08-15 01:13:23 +0000879 reply = self.maybesave()
Matthias Klosea398e2d2007-01-11 11:44:04 +0000880 if str(reply) != "cancel":
David Scherer7aced172000-08-15 01:13:23 +0000881 self._close()
882 return reply
883
884 def _close(self):
Steven M. Gava1d46e402002-03-27 08:40:46 +0000885 if self.io.filename:
Kurt B. Kaisercf6f1b62004-04-11 03:16:07 +0000886 self.update_recent_files_list(new_file=self.io.filename)
David Scherer7aced172000-08-15 01:13:23 +0000887 WindowList.unregister_callback(self.postwindowsmenu)
David Scherer7aced172000-08-15 01:13:23 +0000888 self.unload_extensions()
Kurt B. Kaiser0b634ef2007-10-04 02:09:17 +0000889 self.io.close()
890 self.io = None
891 self.undo = None
David Scherer7aced172000-08-15 01:13:23 +0000892 if self.color:
Kurt B. Kaiser0b634ef2007-10-04 02:09:17 +0000893 self.color.close(False)
894 self.color = None
David Scherer7aced172000-08-15 01:13:23 +0000895 self.text = None
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000896 self.tkinter_vars = None
Kurt B. Kaiser0b634ef2007-10-04 02:09:17 +0000897 self.per.close()
898 self.per = None
899 self.top.destroy()
900 if self.close_hook:
901 # unless override: unregister from flist, terminate if last window
902 self.close_hook()
David Scherer7aced172000-08-15 01:13:23 +0000903
904 def load_extensions(self):
905 self.extensions = {}
906 self.load_standard_extensions()
907
908 def unload_extensions(self):
909 for ins in self.extensions.values():
910 if hasattr(ins, "close"):
911 ins.close()
912 self.extensions = {}
913
914 def load_standard_extensions(self):
915 for name in self.get_standard_extension_names():
916 try:
917 self.load_extension(name)
918 except:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000919 print "Failed to load extension", repr(name)
David Scherer7aced172000-08-15 01:13:23 +0000920 import traceback
921 traceback.print_exc()
922
923 def get_standard_extension_names(self):
Kurt B. Kaiser4d5bc602004-06-06 01:29:22 +0000924 return idleConf.GetExtensions(editor_only=True)
David Scherer7aced172000-08-15 01:13:23 +0000925
926 def load_extension(self, name):
Kurt B. Kaiserb00e89f2005-01-18 00:54:58 +0000927 try:
928 mod = __import__(name, globals(), locals(), [])
929 except ImportError:
930 print "\nFailed to import extension: ", name
931 return
David Scherer7aced172000-08-15 01:13:23 +0000932 cls = getattr(mod, name)
Kurt B. Kaiser4d5bc602004-06-06 01:29:22 +0000933 keydefs = idleConf.GetExtensionBindings(name)
934 if hasattr(cls, "menudefs"):
935 self.fill_menus(cls.menudefs, keydefs)
David Scherer7aced172000-08-15 01:13:23 +0000936 ins = cls(self)
937 self.extensions[name] = ins
David Scherer7aced172000-08-15 01:13:23 +0000938 if keydefs:
939 self.apply_bindings(keydefs)
940 for vevent in keydefs.keys():
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +0000941 methodname = vevent.replace("-", "_")
David Scherer7aced172000-08-15 01:13:23 +0000942 while methodname[:1] == '<':
943 methodname = methodname[1:]
944 while methodname[-1:] == '>':
945 methodname = methodname[:-1]
946 methodname = methodname + "_event"
947 if hasattr(ins, methodname):
948 self.text.bind(vevent, getattr(ins, methodname))
David Scherer7aced172000-08-15 01:13:23 +0000949
950 def apply_bindings(self, keydefs=None):
951 if keydefs is None:
952 keydefs = self.Bindings.default_keydefs
953 text = self.text
954 text.keydefs = keydefs
955 for event, keylist in keydefs.items():
956 if keylist:
Raymond Hettinger931237e2003-07-09 18:48:24 +0000957 text.event_add(event, *keylist)
David Scherer7aced172000-08-15 01:13:23 +0000958
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000959 def fill_menus(self, menudefs=None, keydefs=None):
Kurt B. Kaiser83118c62002-06-24 17:03:37 +0000960 """Add appropriate entries to the menus and submenus
961
962 Menus that are absent or None in self.menudict are ignored.
963 """
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000964 if menudefs is None:
965 menudefs = self.Bindings.menudefs
David Scherer7aced172000-08-15 01:13:23 +0000966 if keydefs is None:
967 keydefs = self.Bindings.default_keydefs
968 menudict = self.menudict
969 text = self.text
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000970 for mname, entrylist in menudefs:
David Scherer7aced172000-08-15 01:13:23 +0000971 menu = menudict.get(mname)
972 if not menu:
973 continue
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000974 for entry in entrylist:
975 if not entry:
David Scherer7aced172000-08-15 01:13:23 +0000976 menu.add_separator()
977 else:
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000978 label, eventname = entry
David Scherer7aced172000-08-15 01:13:23 +0000979 checkbutton = (label[:1] == '!')
980 if checkbutton:
981 label = label[1:]
982 underline, label = prepstr(label)
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000983 accelerator = get_accelerator(keydefs, eventname)
984 def command(text=text, eventname=eventname):
985 text.event_generate(eventname)
David Scherer7aced172000-08-15 01:13:23 +0000986 if checkbutton:
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000987 var = self.get_var_obj(eventname, BooleanVar)
David Scherer7aced172000-08-15 01:13:23 +0000988 menu.add_checkbutton(label=label, underline=underline,
989 command=command, accelerator=accelerator,
990 variable=var)
991 else:
992 menu.add_command(label=label, underline=underline,
Kurt B. Kaiser84f48032002-09-26 22:13:22 +0000993 command=command,
994 accelerator=accelerator)
David Scherer7aced172000-08-15 01:13:23 +0000995
996 def getvar(self, name):
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000997 var = self.get_var_obj(name)
David Scherer7aced172000-08-15 01:13:23 +0000998 if var:
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +0000999 value = var.get()
1000 return value
1001 else:
1002 raise NameError, name
David Scherer7aced172000-08-15 01:13:23 +00001003
1004 def setvar(self, name, value, vartype=None):
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +00001005 var = self.get_var_obj(name, vartype)
David Scherer7aced172000-08-15 01:13:23 +00001006 if var:
1007 var.set(value)
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +00001008 else:
1009 raise NameError, name
David Scherer7aced172000-08-15 01:13:23 +00001010
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +00001011 def get_var_obj(self, name, vartype=None):
1012 var = self.tkinter_vars.get(name)
David Scherer7aced172000-08-15 01:13:23 +00001013 if not var and vartype:
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +00001014 # create a Tkinter variable object with self.text as master:
1015 self.tkinter_vars[name] = var = vartype(self.text)
David Scherer7aced172000-08-15 01:13:23 +00001016 return var
1017
1018 # Tk implementations of "virtual text methods" -- each platform
1019 # reusing IDLE's support code needs to define these for its GUI's
1020 # flavor of widget.
1021
1022 # Is character at text_index in a Python string? Return 0 for
1023 # "guaranteed no", true for anything else. This info is expensive
1024 # to compute ab initio, but is probably already known by the
1025 # platform's colorizer.
1026
1027 def is_char_in_string(self, text_index):
1028 if self.color:
1029 # Return true iff colorizer hasn't (re)gotten this far
1030 # yet, or the character is tagged as being in a string
1031 return self.text.tag_prevrange("TODO", text_index) or \
1032 "STRING" in self.text.tag_names(text_index)
1033 else:
1034 # The colorizer is missing: assume the worst
1035 return 1
1036
1037 # If a selection is defined in the text widget, return (start,
1038 # end) as Tkinter text indices, otherwise return (None, None)
1039 def get_selection_indices(self):
1040 try:
1041 first = self.text.index("sel.first")
1042 last = self.text.index("sel.last")
1043 return first, last
1044 except TclError:
1045 return None, None
1046
1047 # Return the text widget's current view of what a tab stop means
1048 # (equivalent width in spaces).
1049
1050 def get_tabwidth(self):
1051 current = self.text['tabs'] or TK_TABWIDTH_DEFAULT
1052 return int(current)
1053
1054 # Set the text widget's current view of what a tab stop means.
1055
1056 def set_tabwidth(self, newtabwidth):
1057 text = self.text
1058 if self.get_tabwidth() != newtabwidth:
1059 pixels = text.tk.call("font", "measure", text["font"],
1060 "-displayof", text.master,
Kurt B. Kaiserafdf71b2001-07-13 03:35:32 +00001061 "n" * newtabwidth)
David Scherer7aced172000-08-15 01:13:23 +00001062 text.configure(tabs=pixels)
1063
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001064 # If ispythonsource and guess are true, guess a good value for
1065 # indentwidth based on file content (if possible), and if
1066 # indentwidth != tabwidth set usetabs false.
1067 # In any case, adjust the Text widget's view of what a tab
1068 # character means.
1069
Kurt B. Kaiser6af44982005-01-19 00:22:59 +00001070 def set_indentation_params(self, ispythonsource, guess=True):
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001071 if guess and ispythonsource:
1072 i = self.guess_indent()
1073 if 2 <= i <= 8:
1074 self.indentwidth = i
1075 if self.indentwidth != self.tabwidth:
Kurt B. Kaiser6af44982005-01-19 00:22:59 +00001076 self.usetabs = False
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001077 self.set_tabwidth(self.tabwidth)
1078
1079 def smart_backspace_event(self, event):
1080 text = self.text
1081 first, last = self.get_selection_indices()
1082 if first and last:
1083 text.delete(first, last)
1084 text.mark_set("insert", first)
1085 return "break"
1086 # Delete whitespace left, until hitting a real char or closest
1087 # preceding virtual tab stop.
1088 chars = text.get("insert linestart", "insert")
1089 if chars == '':
1090 if text.compare("insert", ">", "1.0"):
1091 # easy: delete preceding newline
1092 text.delete("insert-1c")
1093 else:
1094 text.bell() # at start of buffer
1095 return "break"
1096 if chars[-1] not in " \t":
1097 # easy: delete preceding real char
1098 text.delete("insert-1c")
1099 return "break"
1100 # Ick. It may require *inserting* spaces if we back up over a
1101 # tab character! This is written to be clear, not fast.
Kurt B. Kaiser1b3c2692002-09-15 21:31:30 +00001102 tabwidth = self.tabwidth
1103 have = len(chars.expandtabs(tabwidth))
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001104 assert have > 0
1105 want = ((have - 1) // self.indentwidth) * self.indentwidth
Kurt B. Kaiser4ada7ad2002-12-29 22:03:38 +00001106 # Debug prompt is multilined....
1107 last_line_of_prompt = sys.ps1.split('\n')[-1]
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001108 ncharsdeleted = 0
1109 while 1:
Kurt B. Kaiser4ada7ad2002-12-29 22:03:38 +00001110 if chars == last_line_of_prompt:
Kurt B. Kaiser1bdca5e2002-12-16 22:25:10 +00001111 break
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001112 chars = chars[:-1]
1113 ncharsdeleted = ncharsdeleted + 1
Kurt B. Kaiser1b3c2692002-09-15 21:31:30 +00001114 have = len(chars.expandtabs(tabwidth))
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001115 if have <= want or chars[-1] not in " \t":
1116 break
1117 text.undo_block_start()
1118 text.delete("insert-%dc" % ncharsdeleted, "insert")
1119 if have < want:
1120 text.insert("insert", ' ' * (want - have))
1121 text.undo_block_stop()
1122 return "break"
1123
1124 def smart_indent_event(self, event):
1125 # if intraline selection:
1126 # delete it
1127 # elif multiline selection:
Kurt B. Kaiser6af44982005-01-19 00:22:59 +00001128 # do indent-region
1129 # else:
1130 # indent one level
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001131 text = self.text
1132 first, last = self.get_selection_indices()
1133 text.undo_block_start()
1134 try:
1135 if first and last:
1136 if index2line(first) != index2line(last):
1137 return self.indent_region_event(event)
1138 text.delete(first, last)
1139 text.mark_set("insert", first)
1140 prefix = text.get("insert linestart", "insert")
1141 raw, effective = classifyws(prefix, self.tabwidth)
1142 if raw == len(prefix):
1143 # only whitespace to the left
1144 self.reindent_to(effective + self.indentwidth)
1145 else:
Kurt B. Kaiser6af44982005-01-19 00:22:59 +00001146 # tab to the next 'stop' within or to right of line's text:
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001147 if self.usetabs:
1148 pad = '\t'
1149 else:
Kurt B. Kaiser1b3c2692002-09-15 21:31:30 +00001150 effective = len(prefix.expandtabs(self.tabwidth))
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001151 n = self.indentwidth
1152 pad = ' ' * (n - effective % n)
1153 text.insert("insert", pad)
1154 text.see("insert")
1155 return "break"
1156 finally:
1157 text.undo_block_stop()
1158
1159 def newline_and_indent_event(self, event):
1160 text = self.text
1161 first, last = self.get_selection_indices()
1162 text.undo_block_start()
1163 try:
1164 if first and last:
1165 text.delete(first, last)
1166 text.mark_set("insert", first)
1167 line = text.get("insert linestart", "insert")
1168 i, n = 0, len(line)
1169 while i < n and line[i] in " \t":
1170 i = i+1
1171 if i == n:
Kurt B. Kaiser4ada7ad2002-12-29 22:03:38 +00001172 # the cursor is in or at leading indentation in a continuation
1173 # line; just inject an empty line at the start
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001174 text.insert("insert linestart", '\n')
1175 return "break"
1176 indent = line[:i]
Kurt B. Kaiser4ada7ad2002-12-29 22:03:38 +00001177 # strip whitespace before insert point unless it's in the prompt
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001178 i = 0
Kurt B. Kaiser4ada7ad2002-12-29 22:03:38 +00001179 last_line_of_prompt = sys.ps1.split('\n')[-1]
1180 while line and line[-1] in " \t" and line != last_line_of_prompt:
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001181 line = line[:-1]
1182 i = i+1
1183 if i:
1184 text.delete("insert - %d chars" % i, "insert")
1185 # strip whitespace after insert point
1186 while text.get("insert") in " \t":
1187 text.delete("insert")
1188 # start new line
1189 text.insert("insert", '\n')
1190
1191 # adjust indentation for continuations and block
1192 # open/close first need to find the last stmt
1193 lno = index2line(text.index('insert'))
1194 y = PyParse.Parser(self.indentwidth, self.tabwidth)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00001195 if not self.context_use_ps1:
1196 for context in self.num_context_lines:
1197 startat = max(lno - context, 1)
1198 startatindex = `startat` + ".0"
1199 rawtext = text.get(startatindex, "insert")
1200 y.set_str(rawtext)
1201 bod = y.find_good_parse_start(
1202 self.context_use_ps1,
1203 self._build_char_in_string_func(startatindex))
1204 if bod is not None or startat == 1:
1205 break
1206 y.set_lo(bod or 0)
1207 else:
1208 r = text.tag_prevrange("console", "insert")
1209 if r:
1210 startatindex = r[1]
1211 else:
1212 startatindex = "1.0"
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001213 rawtext = text.get(startatindex, "insert")
1214 y.set_str(rawtext)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00001215 y.set_lo(0)
1216
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001217 c = y.get_continuation_type()
1218 if c != PyParse.C_NONE:
1219 # The current stmt hasn't ended yet.
Kurt B. Kaiserb61602c2005-11-15 07:20:06 +00001220 if c == PyParse.C_STRING_FIRST_LINE:
1221 # after the first line of a string; do not indent at all
1222 pass
1223 elif c == PyParse.C_STRING_NEXT_LINES:
1224 # inside a string which started before this line;
1225 # just mimic the current indent
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001226 text.insert("insert", indent)
1227 elif c == PyParse.C_BRACKET:
1228 # line up with the first (if any) element of the
1229 # last open bracket structure; else indent one
1230 # level beyond the indent of the line with the
1231 # last open bracket
1232 self.reindent_to(y.compute_bracket_indent())
1233 elif c == PyParse.C_BACKSLASH:
1234 # if more than one line in this stmt already, just
1235 # mimic the current indent; else if initial line
1236 # has a start on an assignment stmt, indent to
1237 # beyond leftmost =; else to beyond first chunk of
1238 # non-whitespace on initial line
1239 if y.get_num_lines_in_stmt() > 1:
1240 text.insert("insert", indent)
1241 else:
1242 self.reindent_to(y.compute_backslash_indent())
1243 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001244 assert 0, "bogus continuation type %r" % (c,)
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001245 return "break"
1246
1247 # This line starts a brand new stmt; indent relative to
1248 # indentation of initial line of closest preceding
1249 # interesting stmt.
1250 indent = y.get_base_indent_string()
1251 text.insert("insert", indent)
1252 if y.is_block_opener():
1253 self.smart_indent_event(event)
1254 elif indent and y.is_block_closer():
1255 self.smart_backspace_event(event)
1256 return "break"
1257 finally:
1258 text.see("insert")
1259 text.undo_block_stop()
1260
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001261 # Our editwin provides a is_char_in_string function that works
1262 # with a Tk text index, but PyParse only knows about offsets into
1263 # a string. This builds a function for PyParse that accepts an
1264 # offset.
1265
1266 def _build_char_in_string_func(self, startindex):
1267 def inner(offset, _startindex=startindex,
1268 _icis=self.is_char_in_string):
1269 return _icis(_startindex + "+%dc" % offset)
1270 return inner
1271
1272 def indent_region_event(self, event):
1273 head, tail, chars, lines = self.get_region()
1274 for pos in range(len(lines)):
1275 line = lines[pos]
1276 if line:
1277 raw, effective = classifyws(line, self.tabwidth)
1278 effective = effective + self.indentwidth
1279 lines[pos] = self._make_blanks(effective) + line[raw:]
1280 self.set_region(head, tail, chars, lines)
1281 return "break"
1282
1283 def dedent_region_event(self, event):
1284 head, tail, chars, lines = self.get_region()
1285 for pos in range(len(lines)):
1286 line = lines[pos]
1287 if line:
1288 raw, effective = classifyws(line, self.tabwidth)
1289 effective = max(effective - self.indentwidth, 0)
1290 lines[pos] = self._make_blanks(effective) + line[raw:]
1291 self.set_region(head, tail, chars, lines)
1292 return "break"
1293
1294 def comment_region_event(self, event):
1295 head, tail, chars, lines = self.get_region()
1296 for pos in range(len(lines) - 1):
1297 line = lines[pos]
1298 lines[pos] = '##' + line
1299 self.set_region(head, tail, chars, lines)
1300
1301 def uncomment_region_event(self, event):
1302 head, tail, chars, lines = self.get_region()
1303 for pos in range(len(lines)):
1304 line = lines[pos]
1305 if not line:
1306 continue
1307 if line[:2] == '##':
1308 line = line[2:]
1309 elif line[:1] == '#':
1310 line = line[1:]
1311 lines[pos] = line
1312 self.set_region(head, tail, chars, lines)
1313
1314 def tabify_region_event(self, event):
1315 head, tail, chars, lines = self.get_region()
1316 tabwidth = self._asktabwidth()
1317 for pos in range(len(lines)):
1318 line = lines[pos]
1319 if line:
1320 raw, effective = classifyws(line, tabwidth)
1321 ntabs, nspaces = divmod(effective, tabwidth)
1322 lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:]
1323 self.set_region(head, tail, chars, lines)
1324
1325 def untabify_region_event(self, event):
1326 head, tail, chars, lines = self.get_region()
1327 tabwidth = self._asktabwidth()
1328 for pos in range(len(lines)):
Kurt B. Kaiser1b3c2692002-09-15 21:31:30 +00001329 lines[pos] = lines[pos].expandtabs(tabwidth)
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001330 self.set_region(head, tail, chars, lines)
1331
1332 def toggle_tabs_event(self, event):
1333 if self.askyesno(
1334 "Toggle tabs",
Kurt B. Kaiser6af44982005-01-19 00:22:59 +00001335 "Turn tabs " + ("on", "off")[self.usetabs] +
1336 "?\nIndent width " +
Kurt B. Kaiser53f2b5f2006-08-09 20:34:46 +00001337 ("will be", "remains at")[self.usetabs] + " 8." +
1338 "\n Note: a tab is always 8 columns",
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001339 parent=self.text):
1340 self.usetabs = not self.usetabs
Kurt B. Kaiser53f2b5f2006-08-09 20:34:46 +00001341 # Try to prevent inconsistent indentation.
1342 # User must change indent width manually after using tabs.
1343 self.indentwidth = 8
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001344 return "break"
1345
Kurt B. Kaiser6af44982005-01-19 00:22:59 +00001346 # XXX this isn't bound to anything -- see tabwidth comments
1347## def change_tabwidth_event(self, event):
1348## new = self._asktabwidth()
1349## if new != self.tabwidth:
1350## self.tabwidth = new
1351## self.set_indentation_params(0, guess=0)
1352## return "break"
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001353
1354 def change_indentwidth_event(self, event):
1355 new = self.askinteger(
1356 "Indent width",
Kurt B. Kaiser6af44982005-01-19 00:22:59 +00001357 "New indent width (2-16)\n(Always use 8 when using tabs)",
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001358 parent=self.text,
1359 initialvalue=self.indentwidth,
1360 minvalue=2,
1361 maxvalue=16)
Kurt B. Kaiser6af44982005-01-19 00:22:59 +00001362 if new and new != self.indentwidth and not self.usetabs:
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001363 self.indentwidth = new
1364 return "break"
1365
1366 def get_region(self):
1367 text = self.text
1368 first, last = self.get_selection_indices()
1369 if first and last:
1370 head = text.index(first + " linestart")
1371 tail = text.index(last + "-1c lineend +1c")
1372 else:
1373 head = text.index("insert linestart")
1374 tail = text.index("insert lineend +1c")
1375 chars = text.get(head, tail)
Kurt B. Kaiser1b3c2692002-09-15 21:31:30 +00001376 lines = chars.split("\n")
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001377 return head, tail, chars, lines
1378
1379 def set_region(self, head, tail, chars, lines):
1380 text = self.text
Kurt B. Kaiser1b3c2692002-09-15 21:31:30 +00001381 newchars = "\n".join(lines)
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001382 if newchars == chars:
1383 text.bell()
1384 return
1385 text.tag_remove("sel", "1.0", "end")
1386 text.mark_set("insert", head)
1387 text.undo_block_start()
1388 text.delete(head, tail)
1389 text.insert(head, newchars)
1390 text.undo_block_stop()
1391 text.tag_add("sel", head, "insert")
1392
1393 # Make string that displays as n leading blanks.
1394
1395 def _make_blanks(self, n):
1396 if self.usetabs:
1397 ntabs, nspaces = divmod(n, self.tabwidth)
1398 return '\t' * ntabs + ' ' * nspaces
1399 else:
1400 return ' ' * n
1401
1402 # Delete from beginning of line to insert point, then reinsert
1403 # column logical (meaning use tabs if appropriate) spaces.
1404
1405 def reindent_to(self, column):
1406 text = self.text
1407 text.undo_block_start()
1408 if text.compare("insert linestart", "!=", "insert"):
1409 text.delete("insert linestart", "insert")
1410 if column:
1411 text.insert("insert", self._make_blanks(column))
1412 text.undo_block_stop()
1413
1414 def _asktabwidth(self):
1415 return self.askinteger(
1416 "Tab width",
Kurt B. Kaiserca7329c2005-06-12 05:19:23 +00001417 "Columns per tab? (2-16)",
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001418 parent=self.text,
1419 initialvalue=self.indentwidth,
1420 minvalue=2,
1421 maxvalue=16) or self.tabwidth
1422
1423 # Guess indentwidth from text content.
1424 # Return guessed indentwidth. This should not be believed unless
1425 # it's in a reasonable range (e.g., it will be 0 if no indented
1426 # blocks are found).
1427
1428 def guess_indent(self):
1429 opener, indented = IndentSearcher(self.text, self.tabwidth).run()
1430 if opener and indented:
1431 raw, indentsmall = classifyws(opener, self.tabwidth)
1432 raw, indentlarge = classifyws(indented, self.tabwidth)
1433 else:
1434 indentsmall = indentlarge = 0
1435 return indentlarge - indentsmall
1436
1437# "line.col" -> line, as an int
1438def index2line(index):
1439 return int(float(index))
1440
1441# Look at the leading whitespace in s.
1442# Return pair (# of leading ws characters,
1443# effective # of leading blanks after expanding
1444# tabs to width tabwidth)
1445
1446def classifyws(s, tabwidth):
1447 raw = effective = 0
1448 for ch in s:
1449 if ch == ' ':
1450 raw = raw + 1
1451 effective = effective + 1
1452 elif ch == '\t':
1453 raw = raw + 1
1454 effective = (effective // tabwidth + 1) * tabwidth
1455 else:
1456 break
1457 return raw, effective
1458
1459import tokenize
1460_tokenize = tokenize
1461del tokenize
1462
Kurt B. Kaiserdcba6622004-12-21 22:10:32 +00001463class IndentSearcher(object):
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001464
1465 # .run() chews over the Text widget, looking for a block opener
1466 # and the stmt following it. Returns a pair,
1467 # (line containing block opener, line containing stmt)
1468 # Either or both may be None.
1469
1470 def __init__(self, text, tabwidth):
1471 self.text = text
1472 self.tabwidth = tabwidth
1473 self.i = self.finished = 0
1474 self.blkopenline = self.indentedline = None
1475
1476 def readline(self):
1477 if self.finished:
1478 return ""
1479 i = self.i = self.i + 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00001480 mark = repr(i) + ".0"
Kurt B. Kaisercb7a3832002-09-14 02:34:23 +00001481 if self.text.compare(mark, ">=", "end"):
1482 return ""
1483 return self.text.get(mark, mark + " lineend+1c")
1484
1485 def tokeneater(self, type, token, start, end, line,
1486 INDENT=_tokenize.INDENT,
1487 NAME=_tokenize.NAME,
1488 OPENERS=('class', 'def', 'for', 'if', 'try', 'while')):
1489 if self.finished:
1490 pass
1491 elif type == NAME and token in OPENERS:
1492 self.blkopenline = line
1493 elif type == INDENT and self.blkopenline:
1494 self.indentedline = line
1495 self.finished = 1
1496
1497 def run(self):
1498 save_tabsize = _tokenize.tabsize
1499 _tokenize.tabsize = self.tabwidth
1500 try:
1501 try:
1502 _tokenize.tokenize(self.readline, self.tokeneater)
1503 except _tokenize.TokenError:
1504 # since we cut off the tokenizer early, we can trigger
1505 # spurious errors
1506 pass
1507 finally:
1508 _tokenize.tabsize = save_tabsize
1509 return self.blkopenline, self.indentedline
1510
1511### end autoindent code ###
1512
David Scherer7aced172000-08-15 01:13:23 +00001513def prepstr(s):
1514 # Helper to extract the underscore from a string, e.g.
1515 # prepstr("Co_py") returns (2, "Copy").
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +00001516 i = s.find('_')
David Scherer7aced172000-08-15 01:13:23 +00001517 if i >= 0:
1518 s = s[:i] + s[i+1:]
1519 return i, s
1520
1521
1522keynames = {
1523 'bracketleft': '[',
1524 'bracketright': ']',
1525 'slash': '/',
1526}
1527
Kurt B. Kaiser610c7e02004-04-24 03:01:48 +00001528def get_accelerator(keydefs, eventname):
1529 keylist = keydefs.get(eventname)
David Scherer7aced172000-08-15 01:13:23 +00001530 if not keylist:
1531 return ""
1532 s = keylist[0]
Kurt B. Kaiser220ecbc2002-09-16 02:13:15 +00001533 s = re.sub(r"-[a-z]\b", lambda m: m.group().upper(), s)
David Scherer7aced172000-08-15 01:13:23 +00001534 s = re.sub(r"\b\w+\b", lambda m: keynames.get(m.group(), m.group()), s)
1535 s = re.sub("Key-", "", s)
1536 s = re.sub("Cancel","Ctrl-Break",s) # dscherer@cmu.edu
1537 s = re.sub("Control-", "Ctrl-", s)
1538 s = re.sub("-", "+", s)
1539 s = re.sub("><", " ", s)
1540 s = re.sub("<", "", s)
1541 s = re.sub(">", "", s)
1542 return s
1543
1544
1545def fixwordbreaks(root):
1546 # Make sure that Tk's double-click and next/previous word
1547 # operations use our definition of a word (i.e. an identifier)
1548 tk = root.tk
1549 tk.call('tcl_wordBreakAfter', 'a b', 0) # make sure word.tcl is loaded
1550 tk.call('set', 'tcl_wordchars', '[a-zA-Z0-9_]')
1551 tk.call('set', 'tcl_nonwordchars', '[^a-zA-Z0-9_]')
1552
1553
1554def test():
1555 root = Tk()
1556 fixwordbreaks(root)
1557 root.withdraw()
1558 if sys.argv[1:]:
1559 filename = sys.argv[1]
1560 else:
1561 filename = None
1562 edit = EditorWindow(root=root, filename=filename)
1563 edit.set_close_hook(root.quit)
Kurt B. Kaiser0b634ef2007-10-04 02:09:17 +00001564 edit.text.bind("<<close-all-windows>>", edit.close_event)
David Scherer7aced172000-08-15 01:13:23 +00001565 root.mainloop()
1566 root.destroy()
1567
1568if __name__ == '__main__':
1569 test()