annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/idlelib/editor.py @ 69:33d812a61356

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