annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/idlelib/editor.py @ 68:5028fdace37b

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