source: python/trunk/Lib/idlelib/EditorWindow.py

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

  • Property svn:eol-style set to native
File size: 64.5 KB
Line 
1import sys
2import os
3import re
4import imp
5from Tkinter import *
6import tkSimpleDialog
7import tkMessageBox
8import webbrowser
9
10from idlelib.MultiCall import MultiCallCreator
11from idlelib import idlever
12from idlelib import WindowList
13from idlelib import SearchDialog
14from idlelib import GrepDialog
15from idlelib import ReplaceDialog
16from idlelib import PyParse
17from idlelib.configHandler import idleConf
18from idlelib import aboutDialog, textView, configDialog
19from idlelib import macosxSupport
20
21# The default tab setting for a Text widget, in average-width characters.
22TK_TABWIDTH_DEFAULT = 8
23
24def _sphinx_version():
25 "Format sys.version_info to produce the Sphinx version string used to install the chm docs"
26 major, minor, micro, level, serial = sys.version_info
27 release = '%s%s' % (major, minor)
28 if micro:
29 release += '%s' % (micro,)
30 if level == 'candidate':
31 release += 'rc%s' % (serial,)
32 elif level != 'final':
33 release += '%s%s' % (level[0], serial)
34 return release
35
36def _find_module(fullname, path=None):
37 """Version of imp.find_module() that handles hierarchical module names"""
38
39 file = None
40 for tgt in fullname.split('.'):
41 if file is not None:
42 file.close() # close intermediate files
43 (file, filename, descr) = imp.find_module(tgt, path)
44 if descr[2] == imp.PY_SOURCE:
45 break # find but not load the source file
46 module = imp.load_module(tgt, file, filename, descr)
47 try:
48 path = module.__path__
49 except AttributeError:
50 raise ImportError, 'No source for module ' + module.__name__
51 if descr[2] != imp.PY_SOURCE:
52 # If all of the above fails and didn't raise an exception,fallback
53 # to a straight import which can find __init__.py in a package.
54 m = __import__(fullname)
55 try:
56 filename = m.__file__
57 except AttributeError:
58 pass
59 else:
60 file = None
61 base, ext = os.path.splitext(filename)
62 if ext == '.pyc':
63 ext = '.py'
64 filename = base + ext
65 descr = filename, None, imp.PY_SOURCE
66 return file, filename, descr
67
68
69class HelpDialog(object):
70
71 def __init__(self):
72 self.parent = None # parent of help window
73 self.dlg = None # the help window iteself
74
75 def display(self, parent, near=None):
76 """ Display the help dialog.
77
78 parent - parent widget for the help window
79
80 near - a Toplevel widget (e.g. EditorWindow or PyShell)
81 to use as a reference for placing the help window
82 """
83 if self.dlg is None:
84 self.show_dialog(parent)
85 if near:
86 self.nearwindow(near)
87
88 def show_dialog(self, parent):
89 self.parent = parent
90 fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt')
91 self.dlg = dlg = textView.view_file(parent,'Help',fn, modal=False)
92 dlg.bind('<Destroy>', self.destroy, '+')
93
94 def nearwindow(self, near):
95 # Place the help dialog near the window specified by parent.
96 # Note - this may not reposition the window in Metacity
97 # if "/apps/metacity/general/disable_workarounds" is enabled
98 dlg = self.dlg
99 geom = (near.winfo_rootx() + 10, near.winfo_rooty() + 10)
100 dlg.withdraw()
101 dlg.geometry("=+%d+%d" % geom)
102 dlg.deiconify()
103 dlg.lift()
104
105 def destroy(self, ev=None):
106 self.dlg = None
107 self.parent = None
108
109helpDialog = HelpDialog() # singleton instance
110
111
112class EditorWindow(object):
113 from idlelib.Percolator import Percolator
114 from idlelib.ColorDelegator import ColorDelegator
115 from idlelib.UndoDelegator import UndoDelegator
116 from idlelib.IOBinding import IOBinding, filesystemencoding, encoding
117 from idlelib import Bindings
118 from Tkinter import Toplevel
119 from idlelib.MultiStatusBar import MultiStatusBar
120
121 help_url = None
122
123 def __init__(self, flist=None, filename=None, key=None, root=None):
124 if EditorWindow.help_url is None:
125 dochome = os.path.join(sys.prefix, 'Doc', 'index.html')
126 if sys.platform.count('linux'):
127 # look for html docs in a couple of standard places
128 pyver = 'python-docs-' + '%s.%s.%s' % sys.version_info[:3]
129 if os.path.isdir('/var/www/html/python/'): # "python2" rpm
130 dochome = '/var/www/html/python/index.html'
131 else:
132 basepath = '/usr/share/doc/' # standard location
133 dochome = os.path.join(basepath, pyver,
134 'Doc', 'index.html')
135 elif sys.platform[:3] == 'win':
136 chmfile = os.path.join(sys.prefix, 'Doc',
137 'Python%s.chm' % _sphinx_version())
138 if os.path.isfile(chmfile):
139 dochome = chmfile
140 elif macosxSupport.runningAsOSXApp():
141 # documentation is stored inside the python framework
142 dochome = os.path.join(sys.prefix,
143 'Resources/English.lproj/Documentation/index.html')
144 dochome = os.path.normpath(dochome)
145 if os.path.isfile(dochome):
146 EditorWindow.help_url = dochome
147 if sys.platform == 'darwin':
148 # Safari requires real file:-URLs
149 EditorWindow.help_url = 'file://' + EditorWindow.help_url
150 else:
151 EditorWindow.help_url = "http://docs.python.org/%d.%d" % sys.version_info[:2]
152 currentTheme=idleConf.CurrentTheme()
153 self.flist = flist
154 root = root or flist.root
155 self.root = root
156 try:
157 sys.ps1
158 except AttributeError:
159 sys.ps1 = '>>> '
160 self.menubar = Menu(root)
161 self.top = top = WindowList.ListedToplevel(root, menu=self.menubar)
162 if flist:
163 self.tkinter_vars = flist.vars
164 #self.top.instance_dict makes flist.inversedict available to
165 #configDialog.py so it can access all EditorWindow instances
166 self.top.instance_dict = flist.inversedict
167 else:
168 self.tkinter_vars = {} # keys: Tkinter event names
169 # values: Tkinter variable instances
170 self.top.instance_dict = {}
171 self.recent_files_path = os.path.join(idleConf.GetUserCfgDir(),
172 'recent-files.lst')
173 self.text_frame = text_frame = Frame(top)
174 self.vbar = vbar = Scrollbar(text_frame, name='vbar')
175 self.width = idleConf.GetOption('main','EditorWindow','width', type='int')
176 text_options = {
177 'name': 'text',
178 'padx': 5,
179 'wrap': 'none',
180 'width': self.width,
181 'height': idleConf.GetOption('main', 'EditorWindow', 'height', type='int')}
182 if TkVersion >= 8.5:
183 # Starting with tk 8.5 we have to set the new tabstyle option
184 # to 'wordprocessor' to achieve the same display of tabs as in
185 # older tk versions.
186 text_options['tabstyle'] = 'wordprocessor'
187 self.text = text = MultiCallCreator(Text)(text_frame, **text_options)
188 self.top.focused_widget = self.text
189
190 self.createmenubar()
191 self.apply_bindings()
192
193 self.top.protocol("WM_DELETE_WINDOW", self.close)
194 self.top.bind("<<close-window>>", self.close_event)
195 if macosxSupport.runningAsOSXApp():
196 # Command-W on editorwindows doesn't work without this.
197 text.bind('<<close-window>>', self.close_event)
198 # Some OS X systems have only one mouse button,
199 # so use control-click for pulldown menus there.
200 # (Note, AquaTk defines <2> as the right button if
201 # present and the Tk Text widget already binds <2>.)
202 text.bind("<Control-Button-1>",self.right_menu_event)
203 else:
204 # Elsewhere, use right-click for pulldown menus.
205 text.bind("<3>",self.right_menu_event)
206 text.bind("<<cut>>", self.cut)
207 text.bind("<<copy>>", self.copy)
208 text.bind("<<paste>>", self.paste)
209 text.bind("<<center-insert>>", self.center_insert_event)
210 text.bind("<<help>>", self.help_dialog)
211 text.bind("<<python-docs>>", self.python_docs)
212 text.bind("<<about-idle>>", self.about_dialog)
213 text.bind("<<open-config-dialog>>", self.config_dialog)
214 text.bind("<<open-module>>", self.open_module)
215 text.bind("<<do-nothing>>", lambda event: "break")
216 text.bind("<<select-all>>", self.select_all)
217 text.bind("<<remove-selection>>", self.remove_selection)
218 text.bind("<<find>>", self.find_event)
219 text.bind("<<find-again>>", self.find_again_event)
220 text.bind("<<find-in-files>>", self.find_in_files_event)
221 text.bind("<<find-selection>>", self.find_selection_event)
222 text.bind("<<replace>>", self.replace_event)
223 text.bind("<<goto-line>>", self.goto_line_event)
224 text.bind("<<smart-backspace>>",self.smart_backspace_event)
225 text.bind("<<newline-and-indent>>",self.newline_and_indent_event)
226 text.bind("<<smart-indent>>",self.smart_indent_event)
227 text.bind("<<indent-region>>",self.indent_region_event)
228 text.bind("<<dedent-region>>",self.dedent_region_event)
229 text.bind("<<comment-region>>",self.comment_region_event)
230 text.bind("<<uncomment-region>>",self.uncomment_region_event)
231 text.bind("<<tabify-region>>",self.tabify_region_event)
232 text.bind("<<untabify-region>>",self.untabify_region_event)
233 text.bind("<<toggle-tabs>>",self.toggle_tabs_event)
234 text.bind("<<change-indentwidth>>",self.change_indentwidth_event)
235 text.bind("<Left>", self.move_at_edge_if_selection(0))
236 text.bind("<Right>", self.move_at_edge_if_selection(1))
237 text.bind("<<del-word-left>>", self.del_word_left)
238 text.bind("<<del-word-right>>", self.del_word_right)
239 text.bind("<<beginning-of-line>>", self.home_callback)
240
241 if flist:
242 flist.inversedict[self] = key
243 if key:
244 flist.dict[key] = self
245 text.bind("<<open-new-window>>", self.new_callback)
246 text.bind("<<close-all-windows>>", self.flist.close_all_callback)
247 text.bind("<<open-class-browser>>", self.open_class_browser)
248 text.bind("<<open-path-browser>>", self.open_path_browser)
249
250 self.set_status_bar()
251 vbar['command'] = text.yview
252 vbar.pack(side=RIGHT, fill=Y)
253 text['yscrollcommand'] = vbar.set
254 fontWeight = 'normal'
255 if idleConf.GetOption('main', 'EditorWindow', 'font-bold', type='bool'):
256 fontWeight='bold'
257 text.config(font=(idleConf.GetOption('main', 'EditorWindow', 'font'),
258 idleConf.GetOption('main', 'EditorWindow',
259 'font-size', type='int'),
260 fontWeight))
261 text_frame.pack(side=LEFT, fill=BOTH, expand=1)
262 text.pack(side=TOP, fill=BOTH, expand=1)
263 text.focus_set()
264
265 # usetabs true -> literal tab characters are used by indent and
266 # dedent cmds, possibly mixed with spaces if
267 # indentwidth is not a multiple of tabwidth,
268 # which will cause Tabnanny to nag!
269 # false -> tab characters are converted to spaces by indent
270 # and dedent cmds, and ditto TAB keystrokes
271 # Although use-spaces=0 can be configured manually in config-main.def,
272 # configuration of tabs v. spaces is not supported in the configuration
273 # dialog. IDLE promotes the preferred Python indentation: use spaces!
274 usespaces = idleConf.GetOption('main', 'Indent', 'use-spaces', type='bool')
275 self.usetabs = not usespaces
276
277 # tabwidth is the display width of a literal tab character.
278 # CAUTION: telling Tk to use anything other than its default
279 # tab setting causes it to use an entirely different tabbing algorithm,
280 # treating tab stops as fixed distances from the left margin.
281 # Nobody expects this, so for now tabwidth should never be changed.
282 self.tabwidth = 8 # must remain 8 until Tk is fixed.
283
284 # indentwidth is the number of screen characters per indent level.
285 # The recommended Python indentation is four spaces.
286 self.indentwidth = self.tabwidth
287 self.set_notabs_indentwidth()
288
289 # If context_use_ps1 is true, parsing searches back for a ps1 line;
290 # else searches for a popular (if, def, ...) Python stmt.
291 self.context_use_ps1 = False
292
293 # When searching backwards for a reliable place to begin parsing,
294 # first start num_context_lines[0] lines back, then
295 # num_context_lines[1] lines back if that didn't work, and so on.
296 # The last value should be huge (larger than the # of lines in a
297 # conceivable file).
298 # Making the initial values larger slows things down more often.
299 self.num_context_lines = 50, 500, 5000000
300
301 self.per = per = self.Percolator(text)
302
303 self.undo = undo = self.UndoDelegator()
304 per.insertfilter(undo)
305 text.undo_block_start = undo.undo_block_start
306 text.undo_block_stop = undo.undo_block_stop
307 undo.set_saved_change_hook(self.saved_change_hook)
308
309 # IOBinding implements file I/O and printing functionality
310 self.io = io = self.IOBinding(self)
311 io.set_filename_change_hook(self.filename_change_hook)
312
313 # Create the recent files submenu
314 self.recent_files_menu = Menu(self.menubar)
315 self.menudict['file'].insert_cascade(3, label='Recent Files',
316 underline=0,
317 menu=self.recent_files_menu)
318 self.update_recent_files_list()
319
320 self.color = None # initialized below in self.ResetColorizer
321 if filename:
322 if os.path.exists(filename) and not os.path.isdir(filename):
323 io.loadfile(filename)
324 else:
325 io.set_filename(filename)
326 self.ResetColorizer()
327 self.saved_change_hook()
328
329 self.set_indentation_params(self.ispythonsource(filename))
330
331 self.load_extensions()
332
333 menu = self.menudict.get('windows')
334 if menu:
335 end = menu.index("end")
336 if end is None:
337 end = -1
338 if end >= 0:
339 menu.add_separator()
340 end = end + 1
341 self.wmenu_end = end
342 WindowList.register_callback(self.postwindowsmenu)
343
344 # Some abstractions so IDLE extensions are cross-IDE
345 self.askyesno = tkMessageBox.askyesno
346 self.askinteger = tkSimpleDialog.askinteger
347 self.showerror = tkMessageBox.showerror
348
349 self._highlight_workaround() # Fix selection tags on Windows
350
351 def _highlight_workaround(self):
352 # On Windows, Tk removes painting of the selection
353 # tags which is different behavior than on Linux and Mac.
354 # See issue14146 for more information.
355 if not sys.platform.startswith('win'):
356 return
357
358 text = self.text
359 text.event_add("<<Highlight-FocusOut>>", "<FocusOut>")
360 text.event_add("<<Highlight-FocusIn>>", "<FocusIn>")
361 def highlight_fix(focus):
362 sel_range = text.tag_ranges("sel")
363 if sel_range:
364 if focus == 'out':
365 HILITE_CONFIG = idleConf.GetHighlight(
366 idleConf.CurrentTheme(), 'hilite')
367 text.tag_config("sel_fix", HILITE_CONFIG)
368 text.tag_raise("sel_fix")
369 text.tag_add("sel_fix", *sel_range)
370 elif focus == 'in':
371 text.tag_remove("sel_fix", "1.0", "end")
372
373 text.bind("<<Highlight-FocusOut>>",
374 lambda ev: highlight_fix("out"))
375 text.bind("<<Highlight-FocusIn>>",
376 lambda ev: highlight_fix("in"))
377
378
379 def _filename_to_unicode(self, filename):
380 """convert filename to unicode in order to display it in Tk"""
381 if isinstance(filename, unicode) or not filename:
382 return filename
383 else:
384 try:
385 return filename.decode(self.filesystemencoding)
386 except UnicodeDecodeError:
387 # XXX
388 try:
389 return filename.decode(self.encoding)
390 except UnicodeDecodeError:
391 # byte-to-byte conversion
392 return filename.decode('iso8859-1')
393
394 def new_callback(self, event):
395 dirname, basename = self.io.defaultfilename()
396 self.flist.new(dirname)
397 return "break"
398
399 def home_callback(self, event):
400 if (event.state & 4) != 0 and event.keysym == "Home":
401 # state&4==Control. If <Control-Home>, use the Tk binding.
402 return
403 if self.text.index("iomark") and \
404 self.text.compare("iomark", "<=", "insert lineend") and \
405 self.text.compare("insert linestart", "<=", "iomark"):
406 # In Shell on input line, go to just after prompt
407 insertpt = int(self.text.index("iomark").split(".")[1])
408 else:
409 line = self.text.get("insert linestart", "insert lineend")
410 for insertpt in xrange(len(line)):
411 if line[insertpt] not in (' ','\t'):
412 break
413 else:
414 insertpt=len(line)
415 lineat = int(self.text.index("insert").split('.')[1])
416 if insertpt == lineat:
417 insertpt = 0
418 dest = "insert linestart+"+str(insertpt)+"c"
419 if (event.state&1) == 0:
420 # shift was not pressed
421 self.text.tag_remove("sel", "1.0", "end")
422 else:
423 if not self.text.index("sel.first"):
424 self.text.mark_set("my_anchor", "insert") # there was no previous selection
425 else:
426 if self.text.compare(self.text.index("sel.first"), "<", self.text.index("insert")):
427 self.text.mark_set("my_anchor", "sel.first") # extend back
428 else:
429 self.text.mark_set("my_anchor", "sel.last") # extend forward
430 first = self.text.index(dest)
431 last = self.text.index("my_anchor")
432 if self.text.compare(first,">",last):
433 first,last = last,first
434 self.text.tag_remove("sel", "1.0", "end")
435 self.text.tag_add("sel", first, last)
436 self.text.mark_set("insert", dest)
437 self.text.see("insert")
438 return "break"
439
440 def set_status_bar(self):
441 self.status_bar = self.MultiStatusBar(self.top)
442 if macosxSupport.runningAsOSXApp():
443 # Insert some padding to avoid obscuring some of the statusbar
444 # by the resize widget.
445 self.status_bar.set_label('_padding1', ' ', side=RIGHT)
446 self.status_bar.set_label('column', 'Col: ?', side=RIGHT)
447 self.status_bar.set_label('line', 'Ln: ?', side=RIGHT)
448 self.status_bar.pack(side=BOTTOM, fill=X)
449 self.text.bind("<<set-line-and-column>>", self.set_line_and_column)
450 self.text.event_add("<<set-line-and-column>>",
451 "<KeyRelease>", "<ButtonRelease>")
452 self.text.after_idle(self.set_line_and_column)
453
454 def set_line_and_column(self, event=None):
455 line, column = self.text.index(INSERT).split('.')
456 self.status_bar.set_label('column', 'Col: %s' % column)
457 self.status_bar.set_label('line', 'Ln: %s' % line)
458
459 menu_specs = [
460 ("file", "_File"),
461 ("edit", "_Edit"),
462 ("format", "F_ormat"),
463 ("run", "_Run"),
464 ("options", "_Options"),
465 ("windows", "_Windows"),
466 ("help", "_Help"),
467 ]
468
469 if macosxSupport.runningAsOSXApp():
470 menu_specs[-2] = ("windows", "_Window")
471
472
473 def createmenubar(self):
474 mbar = self.menubar
475 self.menudict = menudict = {}
476 for name, label in self.menu_specs:
477 underline, label = prepstr(label)
478 menudict[name] = menu = Menu(mbar, name=name)
479 mbar.add_cascade(label=label, menu=menu, underline=underline)
480
481 if macosxSupport.isCarbonAquaTk(self.root):
482 # Insert the application menu
483 menudict['application'] = menu = Menu(mbar, name='apple')
484 mbar.add_cascade(label='IDLE', menu=menu)
485
486 self.fill_menus()
487 self.base_helpmenu_length = self.menudict['help'].index(END)
488 self.reset_help_menu_entries()
489
490 def postwindowsmenu(self):
491 # Only called when Windows menu exists
492 menu = self.menudict['windows']
493 end = menu.index("end")
494 if end is None:
495 end = -1
496 if end > self.wmenu_end:
497 menu.delete(self.wmenu_end+1, end)
498 WindowList.add_windows_to_menu(menu)
499
500 rmenu = None
501
502 def right_menu_event(self, event):
503 self.text.mark_set("insert", "@%d,%d" % (event.x, event.y))
504 if not self.rmenu:
505 self.make_rmenu()
506 rmenu = self.rmenu
507 self.event = event
508 iswin = sys.platform[:3] == 'win'
509 if iswin:
510 self.text.config(cursor="arrow")
511
512 for item in self.rmenu_specs:
513 try:
514 label, eventname, verify_state = item
515 except ValueError: # see issue1207589
516 continue
517
518 if verify_state is None:
519 continue
520 state = getattr(self, verify_state)()
521 rmenu.entryconfigure(label, state=state)
522
523 rmenu.tk_popup(event.x_root, event.y_root)
524 if iswin:
525 self.text.config(cursor="ibeam")
526
527 rmenu_specs = [
528 # ("Label", "<<virtual-event>>", "statefuncname"), ...
529 ("Close", "<<close-window>>", None), # Example
530 ]
531
532 def make_rmenu(self):
533 rmenu = Menu(self.text, tearoff=0)
534 for item in self.rmenu_specs:
535 label, eventname = item[0], item[1]
536 if label is not None:
537 def command(text=self.text, eventname=eventname):
538 text.event_generate(eventname)
539 rmenu.add_command(label=label, command=command)
540 else:
541 rmenu.add_separator()
542 self.rmenu = rmenu
543
544 def rmenu_check_cut(self):
545 return self.rmenu_check_copy()
546
547 def rmenu_check_copy(self):
548 try:
549 indx = self.text.index('sel.first')
550 except TclError:
551 return 'disabled'
552 else:
553 return 'normal' if indx else 'disabled'
554
555 def rmenu_check_paste(self):
556 try:
557 self.text.tk.call('tk::GetSelection', self.text, 'CLIPBOARD')
558 except TclError:
559 return 'disabled'
560 else:
561 return 'normal'
562
563 def about_dialog(self, event=None):
564 aboutDialog.AboutDialog(self.top,'About IDLE')
565
566 def config_dialog(self, event=None):
567 configDialog.ConfigDialog(self.top,'Settings')
568
569 def help_dialog(self, event=None):
570 if self.root:
571 parent = self.root
572 else:
573 parent = self.top
574 helpDialog.display(parent, near=self.top)
575
576 def python_docs(self, event=None):
577 if sys.platform[:3] == 'win':
578 try:
579 os.startfile(self.help_url)
580 except WindowsError as why:
581 tkMessageBox.showerror(title='Document Start Failure',
582 message=str(why), parent=self.text)
583 else:
584 webbrowser.open(self.help_url)
585 return "break"
586
587 def cut(self,event):
588 self.text.event_generate("<<Cut>>")
589 return "break"
590
591 def copy(self,event):
592 if not self.text.tag_ranges("sel"):
593 # There is no selection, so do nothing and maybe interrupt.
594 return
595 self.text.event_generate("<<Copy>>")
596 return "break"
597
598 def paste(self,event):
599 self.text.event_generate("<<Paste>>")
600 self.text.see("insert")
601 return "break"
602
603 def select_all(self, event=None):
604 self.text.tag_add("sel", "1.0", "end-1c")
605 self.text.mark_set("insert", "1.0")
606 self.text.see("insert")
607 return "break"
608
609 def remove_selection(self, event=None):
610 self.text.tag_remove("sel", "1.0", "end")
611 self.text.see("insert")
612
613 def move_at_edge_if_selection(self, edge_index):
614 """Cursor move begins at start or end of selection
615
616 When a left/right cursor key is pressed create and return to Tkinter a
617 function which causes a cursor move from the associated edge of the
618 selection.
619
620 """
621 self_text_index = self.text.index
622 self_text_mark_set = self.text.mark_set
623 edges_table = ("sel.first+1c", "sel.last-1c")
624 def move_at_edge(event):
625 if (event.state & 5) == 0: # no shift(==1) or control(==4) pressed
626 try:
627 self_text_index("sel.first")
628 self_text_mark_set("insert", edges_table[edge_index])
629 except TclError:
630 pass
631 return move_at_edge
632
633 def del_word_left(self, event):
634 self.text.event_generate('<Meta-Delete>')
635 return "break"
636
637 def del_word_right(self, event):
638 self.text.event_generate('<Meta-d>')
639 return "break"
640
641 def find_event(self, event):
642 SearchDialog.find(self.text)
643 return "break"
644
645 def find_again_event(self, event):
646 SearchDialog.find_again(self.text)
647 return "break"
648
649 def find_selection_event(self, event):
650 SearchDialog.find_selection(self.text)
651 return "break"
652
653 def find_in_files_event(self, event):
654 GrepDialog.grep(self.text, self.io, self.flist)
655 return "break"
656
657 def replace_event(self, event):
658 ReplaceDialog.replace(self.text)
659 return "break"
660
661 def goto_line_event(self, event):
662 text = self.text
663 lineno = tkSimpleDialog.askinteger("Goto",
664 "Go to line number:",parent=text)
665 if lineno is None:
666 return "break"
667 if lineno <= 0:
668 text.bell()
669 return "break"
670 text.mark_set("insert", "%d.0" % lineno)
671 text.see("insert")
672
673 def open_module(self, event=None):
674 # XXX Shouldn't this be in IOBinding or in FileList?
675 try:
676 name = self.text.get("sel.first", "sel.last")
677 except TclError:
678 name = ""
679 else:
680 name = name.strip()
681 name = tkSimpleDialog.askstring("Module",
682 "Enter the name of a Python module\n"
683 "to search on sys.path and open:",
684 parent=self.text, initialvalue=name)
685 if name:
686 name = name.strip()
687 if not name:
688 return
689 # XXX Ought to insert current file's directory in front of path
690 try:
691 (f, file, (suffix, mode, type)) = _find_module(name)
692 except (NameError, ImportError) as msg:
693 tkMessageBox.showerror("Import error", str(msg), parent=self.text)
694 return
695 if type != imp.PY_SOURCE:
696 tkMessageBox.showerror("Unsupported type",
697 "%s is not a source module" % name, parent=self.text)
698 return
699 if f:
700 f.close()
701 if self.flist:
702 self.flist.open(file)
703 else:
704 self.io.loadfile(file)
705
706 def open_class_browser(self, event=None):
707 filename = self.io.filename
708 if not filename:
709 tkMessageBox.showerror(
710 "No filename",
711 "This buffer has no associated filename",
712 master=self.text)
713 self.text.focus_set()
714 return None
715 head, tail = os.path.split(filename)
716 base, ext = os.path.splitext(tail)
717 from idlelib import ClassBrowser
718 ClassBrowser.ClassBrowser(self.flist, base, [head])
719
720 def open_path_browser(self, event=None):
721 from idlelib import PathBrowser
722 PathBrowser.PathBrowser(self.flist)
723
724 def gotoline(self, lineno):
725 if lineno is not None and lineno > 0:
726 self.text.mark_set("insert", "%d.0" % lineno)
727 self.text.tag_remove("sel", "1.0", "end")
728 self.text.tag_add("sel", "insert", "insert +1l")
729 self.center()
730
731 def ispythonsource(self, filename):
732 if not filename or os.path.isdir(filename):
733 return True
734 base, ext = os.path.splitext(os.path.basename(filename))
735 if os.path.normcase(ext) in (".py", ".pyw"):
736 return True
737 try:
738 f = open(filename)
739 line = f.readline()
740 f.close()
741 except IOError:
742 return False
743 return line.startswith('#!') and line.find('python') >= 0
744
745 def close_hook(self):
746 if self.flist:
747 self.flist.unregister_maybe_terminate(self)
748 self.flist = None
749
750 def set_close_hook(self, close_hook):
751 self.close_hook = close_hook
752
753 def filename_change_hook(self):
754 if self.flist:
755 self.flist.filename_changed_edit(self)
756 self.saved_change_hook()
757 self.top.update_windowlist_registry(self)
758 self.ResetColorizer()
759
760 def _addcolorizer(self):
761 if self.color:
762 return
763 if self.ispythonsource(self.io.filename):
764 self.color = self.ColorDelegator()
765 # can add more colorizers here...
766 if self.color:
767 self.per.removefilter(self.undo)
768 self.per.insertfilter(self.color)
769 self.per.insertfilter(self.undo)
770
771 def _rmcolorizer(self):
772 if not self.color:
773 return
774 self.color.removecolors()
775 self.per.removefilter(self.color)
776 self.color = None
777
778 def ResetColorizer(self):
779 "Update the colour theme"
780 # Called from self.filename_change_hook and from configDialog.py
781 self._rmcolorizer()
782 self._addcolorizer()
783 theme = idleConf.GetOption('main','Theme','name')
784 normal_colors = idleConf.GetHighlight(theme, 'normal')
785 cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg')
786 select_colors = idleConf.GetHighlight(theme, 'hilite')
787 self.text.config(
788 foreground=normal_colors['foreground'],
789 background=normal_colors['background'],
790 insertbackground=cursor_color,
791 selectforeground=select_colors['foreground'],
792 selectbackground=select_colors['background'],
793 )
794
795 def ResetFont(self):
796 "Update the text widgets' font if it is changed"
797 # Called from configDialog.py
798 fontWeight='normal'
799 if idleConf.GetOption('main','EditorWindow','font-bold',type='bool'):
800 fontWeight='bold'
801 self.text.config(font=(idleConf.GetOption('main','EditorWindow','font'),
802 idleConf.GetOption('main','EditorWindow','font-size',
803 type='int'),
804 fontWeight))
805
806 def RemoveKeybindings(self):
807 "Remove the keybindings before they are changed."
808 # Called from configDialog.py
809 self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
810 for event, keylist in keydefs.items():
811 self.text.event_delete(event, *keylist)
812 for extensionName in self.get_standard_extension_names():
813 xkeydefs = idleConf.GetExtensionBindings(extensionName)
814 if xkeydefs:
815 for event, keylist in xkeydefs.items():
816 self.text.event_delete(event, *keylist)
817
818 def ApplyKeybindings(self):
819 "Update the keybindings after they are changed"
820 # Called from configDialog.py
821 self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
822 self.apply_bindings()
823 for extensionName in self.get_standard_extension_names():
824 xkeydefs = idleConf.GetExtensionBindings(extensionName)
825 if xkeydefs:
826 self.apply_bindings(xkeydefs)
827 #update menu accelerators
828 menuEventDict = {}
829 for menu in self.Bindings.menudefs:
830 menuEventDict[menu[0]] = {}
831 for item in menu[1]:
832 if item:
833 menuEventDict[menu[0]][prepstr(item[0])[1]] = item[1]
834 for menubarItem in self.menudict.keys():
835 menu = self.menudict[menubarItem]
836 end = menu.index(END)
837 if end is None:
838 # Skip empty menus
839 continue
840 end += 1
841 for index in range(0, end):
842 if menu.type(index) == 'command':
843 accel = menu.entrycget(index, 'accelerator')
844 if accel:
845 itemName = menu.entrycget(index, 'label')
846 event = ''
847 if menubarItem in menuEventDict:
848 if itemName in menuEventDict[menubarItem]:
849 event = menuEventDict[menubarItem][itemName]
850 if event:
851 accel = get_accelerator(keydefs, event)
852 menu.entryconfig(index, accelerator=accel)
853
854 def set_notabs_indentwidth(self):
855 "Update the indentwidth if changed and not using tabs in this window"
856 # Called from configDialog.py
857 if not self.usetabs:
858 self.indentwidth = idleConf.GetOption('main', 'Indent','num-spaces',
859 type='int')
860
861 def reset_help_menu_entries(self):
862 "Update the additional help entries on the Help menu"
863 help_list = idleConf.GetAllExtraHelpSourcesList()
864 helpmenu = self.menudict['help']
865 # first delete the extra help entries, if any
866 helpmenu_length = helpmenu.index(END)
867 if helpmenu_length > self.base_helpmenu_length:
868 helpmenu.delete((self.base_helpmenu_length + 1), helpmenu_length)
869 # then rebuild them
870 if help_list:
871 helpmenu.add_separator()
872 for entry in help_list:
873 cmd = self.__extra_help_callback(entry[1])
874 helpmenu.add_command(label=entry[0], command=cmd)
875 # and update the menu dictionary
876 self.menudict['help'] = helpmenu
877
878 def __extra_help_callback(self, helpfile):
879 "Create a callback with the helpfile value frozen at definition time"
880 def display_extra_help(helpfile=helpfile):
881 if not helpfile.startswith(('www', 'http')):
882 helpfile = os.path.normpath(helpfile)
883 if sys.platform[:3] == 'win':
884 try:
885 os.startfile(helpfile)
886 except WindowsError as why:
887 tkMessageBox.showerror(title='Document Start Failure',
888 message=str(why), parent=self.text)
889 else:
890 webbrowser.open(helpfile)
891 return display_extra_help
892
893 def update_recent_files_list(self, new_file=None):
894 "Load and update the recent files list and menus"
895 rf_list = []
896 if os.path.exists(self.recent_files_path):
897 with open(self.recent_files_path, 'r') as rf_list_file:
898 rf_list = rf_list_file.readlines()
899 if new_file:
900 new_file = os.path.abspath(new_file) + '\n'
901 if new_file in rf_list:
902 rf_list.remove(new_file) # move to top
903 rf_list.insert(0, new_file)
904 # clean and save the recent files list
905 bad_paths = []
906 for path in rf_list:
907 if '\0' in path or not os.path.exists(path[0:-1]):
908 bad_paths.append(path)
909 rf_list = [path for path in rf_list if path not in bad_paths]
910 ulchars = "1234567890ABCDEFGHIJK"
911 rf_list = rf_list[0:len(ulchars)]
912 try:
913 with open(self.recent_files_path, 'w') as rf_file:
914 rf_file.writelines(rf_list)
915 except IOError as err:
916 if not getattr(self.root, "recentfilelist_error_displayed", False):
917 self.root.recentfilelist_error_displayed = True
918 tkMessageBox.showerror(title='IDLE Error',
919 message='Unable to update Recent Files list:\n%s'
920 % str(err),
921 parent=self.text)
922 # for each edit window instance, construct the recent files menu
923 for instance in self.top.instance_dict.keys():
924 menu = instance.recent_files_menu
925 menu.delete(0, END) # clear, and rebuild:
926 for i, file_name in enumerate(rf_list):
927 file_name = file_name.rstrip() # zap \n
928 # make unicode string to display non-ASCII chars correctly
929 ufile_name = self._filename_to_unicode(file_name)
930 callback = instance.__recent_file_callback(file_name)
931 menu.add_command(label=ulchars[i] + " " + ufile_name,
932 command=callback,
933 underline=0)
934
935 def __recent_file_callback(self, file_name):
936 def open_recent_file(fn_closure=file_name):
937 self.io.open(editFile=fn_closure)
938 return open_recent_file
939
940 def saved_change_hook(self):
941 short = self.short_title()
942 long = self.long_title()
943 if short and long:
944 title = short + " - " + long
945 elif short:
946 title = short
947 elif long:
948 title = long
949 else:
950 title = "Untitled"
951 icon = short or long or title
952 if not self.get_saved():
953 title = "*%s*" % title
954 icon = "*%s" % icon
955 self.top.wm_title(title)
956 self.top.wm_iconname(icon)
957
958 def get_saved(self):
959 return self.undo.get_saved()
960
961 def set_saved(self, flag):
962 self.undo.set_saved(flag)
963
964 def reset_undo(self):
965 self.undo.reset_undo()
966
967 def short_title(self):
968 filename = self.io.filename
969 if filename:
970 filename = os.path.basename(filename)
971 # return unicode string to display non-ASCII chars correctly
972 return self._filename_to_unicode(filename)
973
974 def long_title(self):
975 # return unicode string to display non-ASCII chars correctly
976 return self._filename_to_unicode(self.io.filename or "")
977
978 def center_insert_event(self, event):
979 self.center()
980
981 def center(self, mark="insert"):
982 text = self.text
983 top, bot = self.getwindowlines()
984 lineno = self.getlineno(mark)
985 height = bot - top
986 newtop = max(1, lineno - height//2)
987 text.yview(float(newtop))
988
989 def getwindowlines(self):
990 text = self.text
991 top = self.getlineno("@0,0")
992 bot = self.getlineno("@0,65535")
993 if top == bot and text.winfo_height() == 1:
994 # Geometry manager hasn't run yet
995 height = int(text['height'])
996 bot = top + height - 1
997 return top, bot
998
999 def getlineno(self, mark="insert"):
1000 text = self.text
1001 return int(float(text.index(mark)))
1002
1003 def get_geometry(self):
1004 "Return (width, height, x, y)"
1005 geom = self.top.wm_geometry()
1006 m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
1007 tuple = (map(int, m.groups()))
1008 return tuple
1009
1010 def close_event(self, event):
1011 self.close()
1012
1013 def maybesave(self):
1014 if self.io:
1015 if not self.get_saved():
1016 if self.top.state()!='normal':
1017 self.top.deiconify()
1018 self.top.lower()
1019 self.top.lift()
1020 return self.io.maybesave()
1021
1022 def close(self):
1023 reply = self.maybesave()
1024 if str(reply) != "cancel":
1025 self._close()
1026 return reply
1027
1028 def _close(self):
1029 if self.io.filename:
1030 self.update_recent_files_list(new_file=self.io.filename)
1031 WindowList.unregister_callback(self.postwindowsmenu)
1032 self.unload_extensions()
1033 self.io.close()
1034 self.io = None
1035 self.undo = None
1036 if self.color:
1037 self.color.close(False)
1038 self.color = None
1039 self.text = None
1040 self.tkinter_vars = None
1041 self.per.close()
1042 self.per = None
1043 self.top.destroy()
1044 if self.close_hook:
1045 # unless override: unregister from flist, terminate if last window
1046 self.close_hook()
1047
1048 def load_extensions(self):
1049 self.extensions = {}
1050 self.load_standard_extensions()
1051
1052 def unload_extensions(self):
1053 for ins in self.extensions.values():
1054 if hasattr(ins, "close"):
1055 ins.close()
1056 self.extensions = {}
1057
1058 def load_standard_extensions(self):
1059 for name in self.get_standard_extension_names():
1060 try:
1061 self.load_extension(name)
1062 except:
1063 print "Failed to load extension", repr(name)
1064 import traceback
1065 traceback.print_exc()
1066
1067 def get_standard_extension_names(self):
1068 return idleConf.GetExtensions(editor_only=True)
1069
1070 def load_extension(self, name):
1071 try:
1072 mod = __import__(name, globals(), locals(), [])
1073 except ImportError:
1074 print "\nFailed to import extension: ", name
1075 return
1076 cls = getattr(mod, name)
1077 keydefs = idleConf.GetExtensionBindings(name)
1078 if hasattr(cls, "menudefs"):
1079 self.fill_menus(cls.menudefs, keydefs)
1080 ins = cls(self)
1081 self.extensions[name] = ins
1082 if keydefs:
1083 self.apply_bindings(keydefs)
1084 for vevent in keydefs.keys():
1085 methodname = vevent.replace("-", "_")
1086 while methodname[:1] == '<':
1087 methodname = methodname[1:]
1088 while methodname[-1:] == '>':
1089 methodname = methodname[:-1]
1090 methodname = methodname + "_event"
1091 if hasattr(ins, methodname):
1092 self.text.bind(vevent, getattr(ins, methodname))
1093
1094 def apply_bindings(self, keydefs=None):
1095 if keydefs is None:
1096 keydefs = self.Bindings.default_keydefs
1097 text = self.text
1098 text.keydefs = keydefs
1099 for event, keylist in keydefs.items():
1100 if keylist:
1101 text.event_add(event, *keylist)
1102
1103 def fill_menus(self, menudefs=None, keydefs=None):
1104 """Add appropriate entries to the menus and submenus
1105
1106 Menus that are absent or None in self.menudict are ignored.
1107 """
1108 if menudefs is None:
1109 menudefs = self.Bindings.menudefs
1110 if keydefs is None:
1111 keydefs = self.Bindings.default_keydefs
1112 menudict = self.menudict
1113 text = self.text
1114 for mname, entrylist in menudefs:
1115 menu = menudict.get(mname)
1116 if not menu:
1117 continue
1118 for entry in entrylist:
1119 if not entry:
1120 menu.add_separator()
1121 else:
1122 label, eventname = entry
1123 checkbutton = (label[:1] == '!')
1124 if checkbutton:
1125 label = label[1:]
1126 underline, label = prepstr(label)
1127 accelerator = get_accelerator(keydefs, eventname)
1128 def command(text=text, eventname=eventname):
1129 text.event_generate(eventname)
1130 if checkbutton:
1131 var = self.get_var_obj(eventname, BooleanVar)
1132 menu.add_checkbutton(label=label, underline=underline,
1133 command=command, accelerator=accelerator,
1134 variable=var)
1135 else:
1136 menu.add_command(label=label, underline=underline,
1137 command=command,
1138 accelerator=accelerator)
1139
1140 def getvar(self, name):
1141 var = self.get_var_obj(name)
1142 if var:
1143 value = var.get()
1144 return value
1145 else:
1146 raise NameError, name
1147
1148 def setvar(self, name, value, vartype=None):
1149 var = self.get_var_obj(name, vartype)
1150 if var:
1151 var.set(value)
1152 else:
1153 raise NameError, name
1154
1155 def get_var_obj(self, name, vartype=None):
1156 var = self.tkinter_vars.get(name)
1157 if not var and vartype:
1158 # create a Tkinter variable object with self.text as master:
1159 self.tkinter_vars[name] = var = vartype(self.text)
1160 return var
1161
1162 # Tk implementations of "virtual text methods" -- each platform
1163 # reusing IDLE's support code needs to define these for its GUI's
1164 # flavor of widget.
1165
1166 # Is character at text_index in a Python string? Return 0 for
1167 # "guaranteed no", true for anything else. This info is expensive
1168 # to compute ab initio, but is probably already known by the
1169 # platform's colorizer.
1170
1171 def is_char_in_string(self, text_index):
1172 if self.color:
1173 # Return true iff colorizer hasn't (re)gotten this far
1174 # yet, or the character is tagged as being in a string
1175 return self.text.tag_prevrange("TODO", text_index) or \
1176 "STRING" in self.text.tag_names(text_index)
1177 else:
1178 # The colorizer is missing: assume the worst
1179 return 1
1180
1181 # If a selection is defined in the text widget, return (start,
1182 # end) as Tkinter text indices, otherwise return (None, None)
1183 def get_selection_indices(self):
1184 try:
1185 first = self.text.index("sel.first")
1186 last = self.text.index("sel.last")
1187 return first, last
1188 except TclError:
1189 return None, None
1190
1191 # Return the text widget's current view of what a tab stop means
1192 # (equivalent width in spaces).
1193
1194 def get_tabwidth(self):
1195 current = self.text['tabs'] or TK_TABWIDTH_DEFAULT
1196 return int(current)
1197
1198 # Set the text widget's current view of what a tab stop means.
1199
1200 def set_tabwidth(self, newtabwidth):
1201 text = self.text
1202 if self.get_tabwidth() != newtabwidth:
1203 pixels = text.tk.call("font", "measure", text["font"],
1204 "-displayof", text.master,
1205 "n" * newtabwidth)
1206 text.configure(tabs=pixels)
1207
1208 # If ispythonsource and guess are true, guess a good value for
1209 # indentwidth based on file content (if possible), and if
1210 # indentwidth != tabwidth set usetabs false.
1211 # In any case, adjust the Text widget's view of what a tab
1212 # character means.
1213
1214 def set_indentation_params(self, ispythonsource, guess=True):
1215 if guess and ispythonsource:
1216 i = self.guess_indent()
1217 if 2 <= i <= 8:
1218 self.indentwidth = i
1219 if self.indentwidth != self.tabwidth:
1220 self.usetabs = False
1221 self.set_tabwidth(self.tabwidth)
1222
1223 def smart_backspace_event(self, event):
1224 text = self.text
1225 first, last = self.get_selection_indices()
1226 if first and last:
1227 text.delete(first, last)
1228 text.mark_set("insert", first)
1229 return "break"
1230 # Delete whitespace left, until hitting a real char or closest
1231 # preceding virtual tab stop.
1232 chars = text.get("insert linestart", "insert")
1233 if chars == '':
1234 if text.compare("insert", ">", "1.0"):
1235 # easy: delete preceding newline
1236 text.delete("insert-1c")
1237 else:
1238 text.bell() # at start of buffer
1239 return "break"
1240 if chars[-1] not in " \t":
1241 # easy: delete preceding real char
1242 text.delete("insert-1c")
1243 return "break"
1244 # Ick. It may require *inserting* spaces if we back up over a
1245 # tab character! This is written to be clear, not fast.
1246 tabwidth = self.tabwidth
1247 have = len(chars.expandtabs(tabwidth))
1248 assert have > 0
1249 want = ((have - 1) // self.indentwidth) * self.indentwidth
1250 # Debug prompt is multilined....
1251 if self.context_use_ps1:
1252 last_line_of_prompt = sys.ps1.split('\n')[-1]
1253 else:
1254 last_line_of_prompt = ''
1255 ncharsdeleted = 0
1256 while 1:
1257 if chars == last_line_of_prompt:
1258 break
1259 chars = chars[:-1]
1260 ncharsdeleted = ncharsdeleted + 1
1261 have = len(chars.expandtabs(tabwidth))
1262 if have <= want or chars[-1] not in " \t":
1263 break
1264 text.undo_block_start()
1265 text.delete("insert-%dc" % ncharsdeleted, "insert")
1266 if have < want:
1267 text.insert("insert", ' ' * (want - have))
1268 text.undo_block_stop()
1269 return "break"
1270
1271 def smart_indent_event(self, event):
1272 # if intraline selection:
1273 # delete it
1274 # elif multiline selection:
1275 # do indent-region
1276 # else:
1277 # indent one level
1278 text = self.text
1279 first, last = self.get_selection_indices()
1280 text.undo_block_start()
1281 try:
1282 if first and last:
1283 if index2line(first) != index2line(last):
1284 return self.indent_region_event(event)
1285 text.delete(first, last)
1286 text.mark_set("insert", first)
1287 prefix = text.get("insert linestart", "insert")
1288 raw, effective = classifyws(prefix, self.tabwidth)
1289 if raw == len(prefix):
1290 # only whitespace to the left
1291 self.reindent_to(effective + self.indentwidth)
1292 else:
1293 # tab to the next 'stop' within or to right of line's text:
1294 if self.usetabs:
1295 pad = '\t'
1296 else:
1297 effective = len(prefix.expandtabs(self.tabwidth))
1298 n = self.indentwidth
1299 pad = ' ' * (n - effective % n)
1300 text.insert("insert", pad)
1301 text.see("insert")
1302 return "break"
1303 finally:
1304 text.undo_block_stop()
1305
1306 def newline_and_indent_event(self, event):
1307 text = self.text
1308 first, last = self.get_selection_indices()
1309 text.undo_block_start()
1310 try:
1311 if first and last:
1312 text.delete(first, last)
1313 text.mark_set("insert", first)
1314 line = text.get("insert linestart", "insert")
1315 i, n = 0, len(line)
1316 while i < n and line[i] in " \t":
1317 i = i+1
1318 if i == n:
1319 # the cursor is in or at leading indentation in a continuation
1320 # line; just inject an empty line at the start
1321 text.insert("insert linestart", '\n')
1322 return "break"
1323 indent = line[:i]
1324 # strip whitespace before insert point unless it's in the prompt
1325 i = 0
1326 last_line_of_prompt = sys.ps1.split('\n')[-1]
1327 while line and line[-1] in " \t" and line != last_line_of_prompt:
1328 line = line[:-1]
1329 i = i+1
1330 if i:
1331 text.delete("insert - %d chars" % i, "insert")
1332 # strip whitespace after insert point
1333 while text.get("insert") in " \t":
1334 text.delete("insert")
1335 # start new line
1336 text.insert("insert", '\n')
1337
1338 # adjust indentation for continuations and block
1339 # open/close first need to find the last stmt
1340 lno = index2line(text.index('insert'))
1341 y = PyParse.Parser(self.indentwidth, self.tabwidth)
1342 if not self.context_use_ps1:
1343 for context in self.num_context_lines:
1344 startat = max(lno - context, 1)
1345 startatindex = repr(startat) + ".0"
1346 rawtext = text.get(startatindex, "insert")
1347 y.set_str(rawtext)
1348 bod = y.find_good_parse_start(
1349 self.context_use_ps1,
1350 self._build_char_in_string_func(startatindex))
1351 if bod is not None or startat == 1:
1352 break
1353 y.set_lo(bod or 0)
1354 else:
1355 r = text.tag_prevrange("console", "insert")
1356 if r:
1357 startatindex = r[1]
1358 else:
1359 startatindex = "1.0"
1360 rawtext = text.get(startatindex, "insert")
1361 y.set_str(rawtext)
1362 y.set_lo(0)
1363
1364 c = y.get_continuation_type()
1365 if c != PyParse.C_NONE:
1366 # The current stmt hasn't ended yet.
1367 if c == PyParse.C_STRING_FIRST_LINE:
1368 # after the first line of a string; do not indent at all
1369 pass
1370 elif c == PyParse.C_STRING_NEXT_LINES:
1371 # inside a string which started before this line;
1372 # just mimic the current indent
1373 text.insert("insert", indent)
1374 elif c == PyParse.C_BRACKET:
1375 # line up with the first (if any) element of the
1376 # last open bracket structure; else indent one
1377 # level beyond the indent of the line with the
1378 # last open bracket
1379 self.reindent_to(y.compute_bracket_indent())
1380 elif c == PyParse.C_BACKSLASH:
1381 # if more than one line in this stmt already, just
1382 # mimic the current indent; else if initial line
1383 # has a start on an assignment stmt, indent to
1384 # beyond leftmost =; else to beyond first chunk of
1385 # non-whitespace on initial line
1386 if y.get_num_lines_in_stmt() > 1:
1387 text.insert("insert", indent)
1388 else:
1389 self.reindent_to(y.compute_backslash_indent())
1390 else:
1391 assert 0, "bogus continuation type %r" % (c,)
1392 return "break"
1393
1394 # This line starts a brand new stmt; indent relative to
1395 # indentation of initial line of closest preceding
1396 # interesting stmt.
1397 indent = y.get_base_indent_string()
1398 text.insert("insert", indent)
1399 if y.is_block_opener():
1400 self.smart_indent_event(event)
1401 elif indent and y.is_block_closer():
1402 self.smart_backspace_event(event)
1403 return "break"
1404 finally:
1405 text.see("insert")
1406 text.undo_block_stop()
1407
1408 # Our editwin provides a is_char_in_string function that works
1409 # with a Tk text index, but PyParse only knows about offsets into
1410 # a string. This builds a function for PyParse that accepts an
1411 # offset.
1412
1413 def _build_char_in_string_func(self, startindex):
1414 def inner(offset, _startindex=startindex,
1415 _icis=self.is_char_in_string):
1416 return _icis(_startindex + "+%dc" % offset)
1417 return inner
1418
1419 def indent_region_event(self, event):
1420 head, tail, chars, lines = self.get_region()
1421 for pos in range(len(lines)):
1422 line = lines[pos]
1423 if line:
1424 raw, effective = classifyws(line, self.tabwidth)
1425 effective = effective + self.indentwidth
1426 lines[pos] = self._make_blanks(effective) + line[raw:]
1427 self.set_region(head, tail, chars, lines)
1428 return "break"
1429
1430 def dedent_region_event(self, event):
1431 head, tail, chars, lines = self.get_region()
1432 for pos in range(len(lines)):
1433 line = lines[pos]
1434 if line:
1435 raw, effective = classifyws(line, self.tabwidth)
1436 effective = max(effective - self.indentwidth, 0)
1437 lines[pos] = self._make_blanks(effective) + line[raw:]
1438 self.set_region(head, tail, chars, lines)
1439 return "break"
1440
1441 def comment_region_event(self, event):
1442 head, tail, chars, lines = self.get_region()
1443 for pos in range(len(lines) - 1):
1444 line = lines[pos]
1445 lines[pos] = '##' + line
1446 self.set_region(head, tail, chars, lines)
1447
1448 def uncomment_region_event(self, event):
1449 head, tail, chars, lines = self.get_region()
1450 for pos in range(len(lines)):
1451 line = lines[pos]
1452 if not line:
1453 continue
1454 if line[:2] == '##':
1455 line = line[2:]
1456 elif line[:1] == '#':
1457 line = line[1:]
1458 lines[pos] = line
1459 self.set_region(head, tail, chars, lines)
1460
1461 def tabify_region_event(self, event):
1462 head, tail, chars, lines = self.get_region()
1463 tabwidth = self._asktabwidth()
1464 if tabwidth is None: return
1465 for pos in range(len(lines)):
1466 line = lines[pos]
1467 if line:
1468 raw, effective = classifyws(line, tabwidth)
1469 ntabs, nspaces = divmod(effective, tabwidth)
1470 lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:]
1471 self.set_region(head, tail, chars, lines)
1472
1473 def untabify_region_event(self, event):
1474 head, tail, chars, lines = self.get_region()
1475 tabwidth = self._asktabwidth()
1476 if tabwidth is None: return
1477 for pos in range(len(lines)):
1478 lines[pos] = lines[pos].expandtabs(tabwidth)
1479 self.set_region(head, tail, chars, lines)
1480
1481 def toggle_tabs_event(self, event):
1482 if self.askyesno(
1483 "Toggle tabs",
1484 "Turn tabs " + ("on", "off")[self.usetabs] +
1485 "?\nIndent width " +
1486 ("will be", "remains at")[self.usetabs] + " 8." +
1487 "\n Note: a tab is always 8 columns",
1488 parent=self.text):
1489 self.usetabs = not self.usetabs
1490 # Try to prevent inconsistent indentation.
1491 # User must change indent width manually after using tabs.
1492 self.indentwidth = 8
1493 return "break"
1494
1495 # XXX this isn't bound to anything -- see tabwidth comments
1496## def change_tabwidth_event(self, event):
1497## new = self._asktabwidth()
1498## if new != self.tabwidth:
1499## self.tabwidth = new
1500## self.set_indentation_params(0, guess=0)
1501## return "break"
1502
1503 def change_indentwidth_event(self, event):
1504 new = self.askinteger(
1505 "Indent width",
1506 "New indent width (2-16)\n(Always use 8 when using tabs)",
1507 parent=self.text,
1508 initialvalue=self.indentwidth,
1509 minvalue=2,
1510 maxvalue=16)
1511 if new and new != self.indentwidth and not self.usetabs:
1512 self.indentwidth = new
1513 return "break"
1514
1515 def get_region(self):
1516 text = self.text
1517 first, last = self.get_selection_indices()
1518 if first and last:
1519 head = text.index(first + " linestart")
1520 tail = text.index(last + "-1c lineend +1c")
1521 else:
1522 head = text.index("insert linestart")
1523 tail = text.index("insert lineend +1c")
1524 chars = text.get(head, tail)
1525 lines = chars.split("\n")
1526 return head, tail, chars, lines
1527
1528 def set_region(self, head, tail, chars, lines):
1529 text = self.text
1530 newchars = "\n".join(lines)
1531 if newchars == chars:
1532 text.bell()
1533 return
1534 text.tag_remove("sel", "1.0", "end")
1535 text.mark_set("insert", head)
1536 text.undo_block_start()
1537 text.delete(head, tail)
1538 text.insert(head, newchars)
1539 text.undo_block_stop()
1540 text.tag_add("sel", head, "insert")
1541
1542 # Make string that displays as n leading blanks.
1543
1544 def _make_blanks(self, n):
1545 if self.usetabs:
1546 ntabs, nspaces = divmod(n, self.tabwidth)
1547 return '\t' * ntabs + ' ' * nspaces
1548 else:
1549 return ' ' * n
1550
1551 # Delete from beginning of line to insert point, then reinsert
1552 # column logical (meaning use tabs if appropriate) spaces.
1553
1554 def reindent_to(self, column):
1555 text = self.text
1556 text.undo_block_start()
1557 if text.compare("insert linestart", "!=", "insert"):
1558 text.delete("insert linestart", "insert")
1559 if column:
1560 text.insert("insert", self._make_blanks(column))
1561 text.undo_block_stop()
1562
1563 def _asktabwidth(self):
1564 return self.askinteger(
1565 "Tab width",
1566 "Columns per tab? (2-16)",
1567 parent=self.text,
1568 initialvalue=self.indentwidth,
1569 minvalue=2,
1570 maxvalue=16)
1571
1572 # Guess indentwidth from text content.
1573 # Return guessed indentwidth. This should not be believed unless
1574 # it's in a reasonable range (e.g., it will be 0 if no indented
1575 # blocks are found).
1576
1577 def guess_indent(self):
1578 opener, indented = IndentSearcher(self.text, self.tabwidth).run()
1579 if opener and indented:
1580 raw, indentsmall = classifyws(opener, self.tabwidth)
1581 raw, indentlarge = classifyws(indented, self.tabwidth)
1582 else:
1583 indentsmall = indentlarge = 0
1584 return indentlarge - indentsmall
1585
1586# "line.col" -> line, as an int
1587def index2line(index):
1588 return int(float(index))
1589
1590# Look at the leading whitespace in s.
1591# Return pair (# of leading ws characters,
1592# effective # of leading blanks after expanding
1593# tabs to width tabwidth)
1594
1595def classifyws(s, tabwidth):
1596 raw = effective = 0
1597 for ch in s:
1598 if ch == ' ':
1599 raw = raw + 1
1600 effective = effective + 1
1601 elif ch == '\t':
1602 raw = raw + 1
1603 effective = (effective // tabwidth + 1) * tabwidth
1604 else:
1605 break
1606 return raw, effective
1607
1608import tokenize
1609_tokenize = tokenize
1610del tokenize
1611
1612class IndentSearcher(object):
1613
1614 # .run() chews over the Text widget, looking for a block opener
1615 # and the stmt following it. Returns a pair,
1616 # (line containing block opener, line containing stmt)
1617 # Either or both may be None.
1618
1619 def __init__(self, text, tabwidth):
1620 self.text = text
1621 self.tabwidth = tabwidth
1622 self.i = self.finished = 0
1623 self.blkopenline = self.indentedline = None
1624
1625 def readline(self):
1626 if self.finished:
1627 return ""
1628 i = self.i = self.i + 1
1629 mark = repr(i) + ".0"
1630 if self.text.compare(mark, ">=", "end"):
1631 return ""
1632 return self.text.get(mark, mark + " lineend+1c")
1633
1634 def tokeneater(self, type, token, start, end, line,
1635 INDENT=_tokenize.INDENT,
1636 NAME=_tokenize.NAME,
1637 OPENERS=('class', 'def', 'for', 'if', 'try', 'while')):
1638 if self.finished:
1639 pass
1640 elif type == NAME and token in OPENERS:
1641 self.blkopenline = line
1642 elif type == INDENT and self.blkopenline:
1643 self.indentedline = line
1644 self.finished = 1
1645
1646 def run(self):
1647 save_tabsize = _tokenize.tabsize
1648 _tokenize.tabsize = self.tabwidth
1649 try:
1650 try:
1651 _tokenize.tokenize(self.readline, self.tokeneater)
1652 except (_tokenize.TokenError, SyntaxError):
1653 # since we cut off the tokenizer early, we can trigger
1654 # spurious errors
1655 pass
1656 finally:
1657 _tokenize.tabsize = save_tabsize
1658 return self.blkopenline, self.indentedline
1659
1660### end autoindent code ###
1661
1662def prepstr(s):
1663 # Helper to extract the underscore from a string, e.g.
1664 # prepstr("Co_py") returns (2, "Copy").
1665 i = s.find('_')
1666 if i >= 0:
1667 s = s[:i] + s[i+1:]
1668 return i, s
1669
1670
1671keynames = {
1672 'bracketleft': '[',
1673 'bracketright': ']',
1674 'slash': '/',
1675}
1676
1677def get_accelerator(keydefs, eventname):
1678 keylist = keydefs.get(eventname)
1679 # issue10940: temporary workaround to prevent hang with OS X Cocoa Tk 8.5
1680 # if not keylist:
1681 if (not keylist) or (macosxSupport.runningAsOSXApp() and eventname in {
1682 "<<open-module>>",
1683 "<<goto-line>>",
1684 "<<change-indentwidth>>"}):
1685 return ""
1686 s = keylist[0]
1687 s = re.sub(r"-[a-z]\b", lambda m: m.group().upper(), s)
1688 s = re.sub(r"\b\w+\b", lambda m: keynames.get(m.group(), m.group()), s)
1689 s = re.sub("Key-", "", s)
1690 s = re.sub("Cancel","Ctrl-Break",s) # dscherer@cmu.edu
1691 s = re.sub("Control-", "Ctrl-", s)
1692 s = re.sub("-", "+", s)
1693 s = re.sub("><", " ", s)
1694 s = re.sub("<", "", s)
1695 s = re.sub(">", "", s)
1696 return s
1697
1698
1699def fixwordbreaks(root):
1700 # Make sure that Tk's double-click and next/previous word
1701 # operations use our definition of a word (i.e. an identifier)
1702 tk = root.tk
1703 tk.call('tcl_wordBreakAfter', 'a b', 0) # make sure word.tcl is loaded
1704 tk.call('set', 'tcl_wordchars', '[a-zA-Z0-9_]')
1705 tk.call('set', 'tcl_nonwordchars', '[^a-zA-Z0-9_]')
1706
1707
1708def test():
1709 root = Tk()
1710 fixwordbreaks(root)
1711 root.withdraw()
1712 if sys.argv[1:]:
1713 filename = sys.argv[1]
1714 else:
1715 filename = None
1716 edit = EditorWindow(root=root, filename=filename)
1717 edit.set_close_hook(root.quit)
1718 edit.text.bind("<<close-all-windows>>", edit.close_event)
1719 root.mainloop()
1720 root.destroy()
1721
1722if __name__ == '__main__':
1723 test()
Note: See TracBrowser for help on using the repository browser.