codecontext.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. """codecontext - display the block context above the edit window
  2. Once code has scrolled off the top of a window, it can be difficult to
  3. determine which block you are in. This extension implements a pane at the top
  4. of each IDLE edit window which provides block structure hints. These hints are
  5. the lines which contain the block opening keywords, e.g. 'if', for the
  6. enclosing block. The number of hint lines is determined by the maxlines
  7. variable in the codecontext section of config-extensions.def. Lines which do
  8. not open blocks are not shown in the context hints pane.
  9. For EditorWindows, <<toggle-code-context>> is bound to CodeContext(self).
  10. toggle_code_context_event.
  11. """
  12. import re
  13. from sys import maxsize as INFINITY
  14. from tkinter import Frame, Text, TclError
  15. from tkinter.constants import NSEW, SUNKEN
  16. from idlelib.config import idleConf
  17. BLOCKOPENERS = {'class', 'def', 'if', 'elif', 'else', 'while', 'for',
  18. 'try', 'except', 'finally', 'with', 'async'}
  19. def get_spaces_firstword(codeline, c=re.compile(r"^(\s*)(\w*)")):
  20. "Extract the beginning whitespace and first word from codeline."
  21. return c.match(codeline).groups()
  22. def get_line_info(codeline):
  23. """Return tuple of (line indent value, codeline, block start keyword).
  24. The indentation of empty lines (or comment lines) is INFINITY.
  25. If the line does not start a block, the keyword value is False.
  26. """
  27. spaces, firstword = get_spaces_firstword(codeline)
  28. indent = len(spaces)
  29. if len(codeline) == indent or codeline[indent] == '#':
  30. indent = INFINITY
  31. opener = firstword in BLOCKOPENERS and firstword
  32. return indent, codeline, opener
  33. class CodeContext:
  34. "Display block context above the edit window."
  35. UPDATEINTERVAL = 100 # millisec
  36. def __init__(self, editwin):
  37. """Initialize settings for context block.
  38. editwin is the Editor window for the context block.
  39. self.text is the editor window text widget.
  40. self.context displays the code context text above the editor text.
  41. Initially None, it is toggled via <<toggle-code-context>>.
  42. self.topvisible is the number of the top text line displayed.
  43. self.info is a list of (line number, indent level, line text,
  44. block keyword) tuples for the block structure above topvisible.
  45. self.info[0] is initialized with a 'dummy' line which
  46. starts the toplevel 'block' of the module.
  47. self.t1 and self.t2 are two timer events on the editor text widget to
  48. monitor for changes to the context text or editor font.
  49. """
  50. self.editwin = editwin
  51. self.text = editwin.text
  52. self._reset()
  53. def _reset(self):
  54. self.context = None
  55. self.cell00 = None
  56. self.t1 = None
  57. self.topvisible = 1
  58. self.info = [(0, -1, "", False)]
  59. @classmethod
  60. def reload(cls):
  61. "Load class variables from config."
  62. cls.context_depth = idleConf.GetOption("extensions", "CodeContext",
  63. "maxlines", type="int",
  64. default=15)
  65. def __del__(self):
  66. "Cancel scheduled events."
  67. if self.t1 is not None:
  68. try:
  69. self.text.after_cancel(self.t1)
  70. except TclError: # pragma: no cover
  71. pass
  72. self.t1 = None
  73. def toggle_code_context_event(self, event=None):
  74. """Toggle code context display.
  75. If self.context doesn't exist, create it to match the size of the editor
  76. window text (toggle on). If it does exist, destroy it (toggle off).
  77. Return 'break' to complete the processing of the binding.
  78. """
  79. if self.context is None:
  80. # Calculate the border width and horizontal padding required to
  81. # align the context with the text in the main Text widget.
  82. #
  83. # All values are passed through getint(), since some
  84. # values may be pixel objects, which can't simply be added to ints.
  85. widgets = self.editwin.text, self.editwin.text_frame
  86. # Calculate the required horizontal padding and border width.
  87. padx = 0
  88. border = 0
  89. for widget in widgets:
  90. info = (widget.grid_info()
  91. if widget is self.editwin.text
  92. else widget.pack_info())
  93. padx += widget.tk.getint(info['padx'])
  94. padx += widget.tk.getint(widget.cget('padx'))
  95. border += widget.tk.getint(widget.cget('border'))
  96. context = self.context = Text(
  97. self.editwin.text_frame,
  98. height=1,
  99. width=1, # Don't request more than we get.
  100. highlightthickness=0,
  101. padx=padx, border=border, relief=SUNKEN, state='disabled')
  102. self.update_font()
  103. self.update_highlight_colors()
  104. context.bind('<ButtonRelease-1>', self.jumptoline)
  105. # Get the current context and initiate the recurring update event.
  106. self.timer_event()
  107. # Grid the context widget above the text widget.
  108. context.grid(row=0, column=1, sticky=NSEW)
  109. line_number_colors = idleConf.GetHighlight(idleConf.CurrentTheme(),
  110. 'linenumber')
  111. self.cell00 = Frame(self.editwin.text_frame,
  112. bg=line_number_colors['background'])
  113. self.cell00.grid(row=0, column=0, sticky=NSEW)
  114. menu_status = 'Hide'
  115. else:
  116. self.context.destroy()
  117. self.context = None
  118. self.cell00.destroy()
  119. self.cell00 = None
  120. self.text.after_cancel(self.t1)
  121. self._reset()
  122. menu_status = 'Show'
  123. self.editwin.update_menu_label(menu='options', index='*ode*ontext',
  124. label=f'{menu_status} Code Context')
  125. return "break"
  126. def get_context(self, new_topvisible, stopline=1, stopindent=0):
  127. """Return a list of block line tuples and the 'last' indent.
  128. The tuple fields are (linenum, indent, text, opener).
  129. The list represents header lines from new_topvisible back to
  130. stopline with successively shorter indents > stopindent.
  131. The list is returned ordered by line number.
  132. Last indent returned is the smallest indent observed.
  133. """
  134. assert stopline > 0
  135. lines = []
  136. # The indentation level we are currently in.
  137. lastindent = INFINITY
  138. # For a line to be interesting, it must begin with a block opening
  139. # keyword, and have less indentation than lastindent.
  140. for linenum in range(new_topvisible, stopline-1, -1):
  141. codeline = self.text.get(f'{linenum}.0', f'{linenum}.end')
  142. indent, text, opener = get_line_info(codeline)
  143. if indent < lastindent:
  144. lastindent = indent
  145. if opener in ("else", "elif"):
  146. # Also show the if statement.
  147. lastindent += 1
  148. if opener and linenum < new_topvisible and indent >= stopindent:
  149. lines.append((linenum, indent, text, opener))
  150. if lastindent <= stopindent:
  151. break
  152. lines.reverse()
  153. return lines, lastindent
  154. def update_code_context(self):
  155. """Update context information and lines visible in the context pane.
  156. No update is done if the text hasn't been scrolled. If the text
  157. was scrolled, the lines that should be shown in the context will
  158. be retrieved and the context area will be updated with the code,
  159. up to the number of maxlines.
  160. """
  161. new_topvisible = self.editwin.getlineno("@0,0")
  162. if self.topvisible == new_topvisible: # Haven't scrolled.
  163. return
  164. if self.topvisible < new_topvisible: # Scroll down.
  165. lines, lastindent = self.get_context(new_topvisible,
  166. self.topvisible)
  167. # Retain only context info applicable to the region
  168. # between topvisible and new_topvisible.
  169. while self.info[-1][1] >= lastindent:
  170. del self.info[-1]
  171. else: # self.topvisible > new_topvisible: # Scroll up.
  172. stopindent = self.info[-1][1] + 1
  173. # Retain only context info associated
  174. # with lines above new_topvisible.
  175. while self.info[-1][0] >= new_topvisible:
  176. stopindent = self.info[-1][1]
  177. del self.info[-1]
  178. lines, lastindent = self.get_context(new_topvisible,
  179. self.info[-1][0]+1,
  180. stopindent)
  181. self.info.extend(lines)
  182. self.topvisible = new_topvisible
  183. # Last context_depth context lines.
  184. context_strings = [x[2] for x in self.info[-self.context_depth:]]
  185. showfirst = 0 if context_strings[0] else 1
  186. # Update widget.
  187. self.context['height'] = len(context_strings) - showfirst
  188. self.context['state'] = 'normal'
  189. self.context.delete('1.0', 'end')
  190. self.context.insert('end', '\n'.join(context_strings[showfirst:]))
  191. self.context['state'] = 'disabled'
  192. def jumptoline(self, event=None):
  193. """ Show clicked context line at top of editor.
  194. If a selection was made, don't jump; allow copying.
  195. If no visible context, show the top line of the file.
  196. """
  197. try:
  198. self.context.index("sel.first")
  199. except TclError:
  200. lines = len(self.info)
  201. if lines == 1: # No context lines are showing.
  202. newtop = 1
  203. else:
  204. # Line number clicked.
  205. contextline = int(float(self.context.index('insert')))
  206. # Lines not displayed due to maxlines.
  207. offset = max(1, lines - self.context_depth) - 1
  208. newtop = self.info[offset + contextline][0]
  209. self.text.yview(f'{newtop}.0')
  210. self.update_code_context()
  211. def timer_event(self):
  212. "Event on editor text widget triggered every UPDATEINTERVAL ms."
  213. if self.context is not None:
  214. self.update_code_context()
  215. self.t1 = self.text.after(self.UPDATEINTERVAL, self.timer_event)
  216. def update_font(self):
  217. if self.context is not None:
  218. font = idleConf.GetFont(self.text, 'main', 'EditorWindow')
  219. self.context['font'] = font
  220. def update_highlight_colors(self):
  221. if self.context is not None:
  222. colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'context')
  223. self.context['background'] = colors['background']
  224. self.context['foreground'] = colors['foreground']
  225. if self.cell00 is not None:
  226. line_number_colors = idleConf.GetHighlight(idleConf.CurrentTheme(),
  227. 'linenumber')
  228. self.cell00.config(bg=line_number_colors['background'])
  229. CodeContext.reload()
  230. if __name__ == "__main__":
  231. from unittest import main
  232. main('idlelib.idle_test.test_codecontext', verbosity=2, exit=False)
  233. # Add htest.