ยปCore Development>Code coverage>Lib/idlelib/EditorWindow.py

Python code coverage for Lib/idlelib/EditorWindow.py

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