jpayne@68: """codecontext - display the block context above the edit window jpayne@68: jpayne@68: Once code has scrolled off the top of a window, it can be difficult to jpayne@68: determine which block you are in. This extension implements a pane at the top jpayne@68: of each IDLE edit window which provides block structure hints. These hints are jpayne@68: the lines which contain the block opening keywords, e.g. 'if', for the jpayne@68: enclosing block. The number of hint lines is determined by the maxlines jpayne@68: variable in the codecontext section of config-extensions.def. Lines which do jpayne@68: not open blocks are not shown in the context hints pane. jpayne@68: jpayne@68: """ jpayne@68: import re jpayne@68: from sys import maxsize as INFINITY jpayne@68: jpayne@68: import tkinter jpayne@68: from tkinter.constants import NSEW, SUNKEN jpayne@68: jpayne@68: from idlelib.config import idleConf jpayne@68: jpayne@68: BLOCKOPENERS = {"class", "def", "elif", "else", "except", "finally", "for", jpayne@68: "if", "try", "while", "with", "async"} jpayne@68: jpayne@68: jpayne@68: def get_spaces_firstword(codeline, c=re.compile(r"^(\s*)(\w*)")): jpayne@68: "Extract the beginning whitespace and first word from codeline." jpayne@68: return c.match(codeline).groups() jpayne@68: jpayne@68: jpayne@68: def get_line_info(codeline): jpayne@68: """Return tuple of (line indent value, codeline, block start keyword). jpayne@68: jpayne@68: The indentation of empty lines (or comment lines) is INFINITY. jpayne@68: If the line does not start a block, the keyword value is False. jpayne@68: """ jpayne@68: spaces, firstword = get_spaces_firstword(codeline) jpayne@68: indent = len(spaces) jpayne@68: if len(codeline) == indent or codeline[indent] == '#': jpayne@68: indent = INFINITY jpayne@68: opener = firstword in BLOCKOPENERS and firstword jpayne@68: return indent, codeline, opener jpayne@68: jpayne@68: jpayne@68: class CodeContext: jpayne@68: "Display block context above the edit window." jpayne@68: UPDATEINTERVAL = 100 # millisec jpayne@68: jpayne@68: def __init__(self, editwin): jpayne@68: """Initialize settings for context block. jpayne@68: jpayne@68: editwin is the Editor window for the context block. jpayne@68: self.text is the editor window text widget. jpayne@68: jpayne@68: self.context displays the code context text above the editor text. jpayne@68: Initially None, it is toggled via <>. jpayne@68: self.topvisible is the number of the top text line displayed. jpayne@68: self.info is a list of (line number, indent level, line text, jpayne@68: block keyword) tuples for the block structure above topvisible. jpayne@68: self.info[0] is initialized with a 'dummy' line which jpayne@68: starts the toplevel 'block' of the module. jpayne@68: jpayne@68: self.t1 and self.t2 are two timer events on the editor text widget to jpayne@68: monitor for changes to the context text or editor font. jpayne@68: """ jpayne@68: self.editwin = editwin jpayne@68: self.text = editwin.text jpayne@68: self._reset() jpayne@68: jpayne@68: def _reset(self): jpayne@68: self.context = None jpayne@68: self.cell00 = None jpayne@68: self.t1 = None jpayne@68: self.topvisible = 1 jpayne@68: self.info = [(0, -1, "", False)] jpayne@68: jpayne@68: @classmethod jpayne@68: def reload(cls): jpayne@68: "Load class variables from config." jpayne@68: cls.context_depth = idleConf.GetOption("extensions", "CodeContext", jpayne@68: "maxlines", type="int", jpayne@68: default=15) jpayne@68: jpayne@68: def __del__(self): jpayne@68: "Cancel scheduled events." jpayne@68: if self.t1 is not None: jpayne@68: try: jpayne@68: self.text.after_cancel(self.t1) jpayne@68: except tkinter.TclError: jpayne@68: pass jpayne@68: self.t1 = None jpayne@68: jpayne@68: def toggle_code_context_event(self, event=None): jpayne@68: """Toggle code context display. jpayne@68: jpayne@68: If self.context doesn't exist, create it to match the size of the editor jpayne@68: window text (toggle on). If it does exist, destroy it (toggle off). jpayne@68: Return 'break' to complete the processing of the binding. jpayne@68: """ jpayne@68: if self.context is None: jpayne@68: # Calculate the border width and horizontal padding required to jpayne@68: # align the context with the text in the main Text widget. jpayne@68: # jpayne@68: # All values are passed through getint(), since some jpayne@68: # values may be pixel objects, which can't simply be added to ints. jpayne@68: widgets = self.editwin.text, self.editwin.text_frame jpayne@68: # Calculate the required horizontal padding and border width. jpayne@68: padx = 0 jpayne@68: border = 0 jpayne@68: for widget in widgets: jpayne@68: info = (widget.grid_info() jpayne@68: if widget is self.editwin.text jpayne@68: else widget.pack_info()) jpayne@68: padx += widget.tk.getint(info['padx']) jpayne@68: padx += widget.tk.getint(widget.cget('padx')) jpayne@68: border += widget.tk.getint(widget.cget('border')) jpayne@68: self.context = tkinter.Text( jpayne@68: self.editwin.text_frame, jpayne@68: height=1, jpayne@68: width=1, # Don't request more than we get. jpayne@68: highlightthickness=0, jpayne@68: padx=padx, border=border, relief=SUNKEN, state='disabled') jpayne@68: self.update_font() jpayne@68: self.update_highlight_colors() jpayne@68: self.context.bind('', self.jumptoline) jpayne@68: # Get the current context and initiate the recurring update event. jpayne@68: self.timer_event() jpayne@68: # Grid the context widget above the text widget. jpayne@68: self.context.grid(row=0, column=1, sticky=NSEW) jpayne@68: jpayne@68: line_number_colors = idleConf.GetHighlight(idleConf.CurrentTheme(), jpayne@68: 'linenumber') jpayne@68: self.cell00 = tkinter.Frame(self.editwin.text_frame, jpayne@68: bg=line_number_colors['background']) jpayne@68: self.cell00.grid(row=0, column=0, sticky=NSEW) jpayne@68: menu_status = 'Hide' jpayne@68: else: jpayne@68: self.context.destroy() jpayne@68: self.context = None jpayne@68: self.cell00.destroy() jpayne@68: self.cell00 = None jpayne@68: self.text.after_cancel(self.t1) jpayne@68: self._reset() jpayne@68: menu_status = 'Show' jpayne@68: self.editwin.update_menu_label(menu='options', index='* Code Context', jpayne@68: label=f'{menu_status} Code Context') jpayne@68: return "break" jpayne@68: jpayne@68: def get_context(self, new_topvisible, stopline=1, stopindent=0): jpayne@68: """Return a list of block line tuples and the 'last' indent. jpayne@68: jpayne@68: The tuple fields are (linenum, indent, text, opener). jpayne@68: The list represents header lines from new_topvisible back to jpayne@68: stopline with successively shorter indents > stopindent. jpayne@68: The list is returned ordered by line number. jpayne@68: Last indent returned is the smallest indent observed. jpayne@68: """ jpayne@68: assert stopline > 0 jpayne@68: lines = [] jpayne@68: # The indentation level we are currently in. jpayne@68: lastindent = INFINITY jpayne@68: # For a line to be interesting, it must begin with a block opening jpayne@68: # keyword, and have less indentation than lastindent. jpayne@68: for linenum in range(new_topvisible, stopline-1, -1): jpayne@68: codeline = self.text.get(f'{linenum}.0', f'{linenum}.end') jpayne@68: indent, text, opener = get_line_info(codeline) jpayne@68: if indent < lastindent: jpayne@68: lastindent = indent jpayne@68: if opener in ("else", "elif"): jpayne@68: # Also show the if statement. jpayne@68: lastindent += 1 jpayne@68: if opener and linenum < new_topvisible and indent >= stopindent: jpayne@68: lines.append((linenum, indent, text, opener)) jpayne@68: if lastindent <= stopindent: jpayne@68: break jpayne@68: lines.reverse() jpayne@68: return lines, lastindent jpayne@68: jpayne@68: def update_code_context(self): jpayne@68: """Update context information and lines visible in the context pane. jpayne@68: jpayne@68: No update is done if the text hasn't been scrolled. If the text jpayne@68: was scrolled, the lines that should be shown in the context will jpayne@68: be retrieved and the context area will be updated with the code, jpayne@68: up to the number of maxlines. jpayne@68: """ jpayne@68: new_topvisible = self.editwin.getlineno("@0,0") jpayne@68: if self.topvisible == new_topvisible: # Haven't scrolled. jpayne@68: return jpayne@68: if self.topvisible < new_topvisible: # Scroll down. jpayne@68: lines, lastindent = self.get_context(new_topvisible, jpayne@68: self.topvisible) jpayne@68: # Retain only context info applicable to the region jpayne@68: # between topvisible and new_topvisible. jpayne@68: while self.info[-1][1] >= lastindent: jpayne@68: del self.info[-1] jpayne@68: else: # self.topvisible > new_topvisible: # Scroll up. jpayne@68: stopindent = self.info[-1][1] + 1 jpayne@68: # Retain only context info associated jpayne@68: # with lines above new_topvisible. jpayne@68: while self.info[-1][0] >= new_topvisible: jpayne@68: stopindent = self.info[-1][1] jpayne@68: del self.info[-1] jpayne@68: lines, lastindent = self.get_context(new_topvisible, jpayne@68: self.info[-1][0]+1, jpayne@68: stopindent) jpayne@68: self.info.extend(lines) jpayne@68: self.topvisible = new_topvisible jpayne@68: # Last context_depth context lines. jpayne@68: context_strings = [x[2] for x in self.info[-self.context_depth:]] jpayne@68: showfirst = 0 if context_strings[0] else 1 jpayne@68: # Update widget. jpayne@68: self.context['height'] = len(context_strings) - showfirst jpayne@68: self.context['state'] = 'normal' jpayne@68: self.context.delete('1.0', 'end') jpayne@68: self.context.insert('end', '\n'.join(context_strings[showfirst:])) jpayne@68: self.context['state'] = 'disabled' jpayne@68: jpayne@68: def jumptoline(self, event=None): jpayne@68: "Show clicked context line at top of editor." jpayne@68: lines = len(self.info) jpayne@68: if lines == 1: # No context lines are showing. jpayne@68: newtop = 1 jpayne@68: else: jpayne@68: # Line number clicked. jpayne@68: contextline = int(float(self.context.index('insert'))) jpayne@68: # Lines not displayed due to maxlines. jpayne@68: offset = max(1, lines - self.context_depth) - 1 jpayne@68: newtop = self.info[offset + contextline][0] jpayne@68: self.text.yview(f'{newtop}.0') jpayne@68: self.update_code_context() jpayne@68: jpayne@68: def timer_event(self): jpayne@68: "Event on editor text widget triggered every UPDATEINTERVAL ms." jpayne@68: if self.context is not None: jpayne@68: self.update_code_context() jpayne@68: self.t1 = self.text.after(self.UPDATEINTERVAL, self.timer_event) jpayne@68: jpayne@68: def update_font(self): jpayne@68: if self.context is not None: jpayne@68: font = idleConf.GetFont(self.text, 'main', 'EditorWindow') jpayne@68: self.context['font'] = font jpayne@68: jpayne@68: def update_highlight_colors(self): jpayne@68: if self.context is not None: jpayne@68: colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'context') jpayne@68: self.context['background'] = colors['background'] jpayne@68: self.context['foreground'] = colors['foreground'] jpayne@68: jpayne@68: if self.cell00 is not None: jpayne@68: line_number_colors = idleConf.GetHighlight(idleConf.CurrentTheme(), jpayne@68: 'linenumber') jpayne@68: self.cell00.config(bg=line_number_colors['background']) jpayne@68: jpayne@68: jpayne@68: CodeContext.reload() jpayne@68: jpayne@68: jpayne@68: if __name__ == "__main__": jpayne@68: from unittest import main jpayne@68: main('idlelib.idle_test.test_codecontext', verbosity=2, exit=False) jpayne@68: jpayne@68: # Add htest.