PageRenderTime 36ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/idlelib/CodeContext.py

https://bitbucket.org/yrttyr/pypy
Python | 176 lines | 140 code | 3 blank | 33 comment | 19 complexity | 6789eb29202186dbfedf76b519290191 MD5 | raw file
  1. """CodeContext - Extension to 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 numlines
  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. """
  10. import Tkinter
  11. from Tkconstants import TOP, LEFT, X, W, SUNKEN
  12. import re
  13. from sys import maxint as INFINITY
  14. from idlelib.configHandler import idleConf
  15. BLOCKOPENERS = set(["class", "def", "elif", "else", "except", "finally", "for",
  16. "if", "try", "while", "with"])
  17. UPDATEINTERVAL = 100 # millisec
  18. FONTUPDATEINTERVAL = 1000 # millisec
  19. getspacesfirstword =\
  20. lambda s, c=re.compile(r"^(\s*)(\w*)"): c.match(s).groups()
  21. class CodeContext:
  22. menudefs = [('options', [('!Code Conte_xt', '<<toggle-code-context>>')])]
  23. context_depth = idleConf.GetOption("extensions", "CodeContext",
  24. "numlines", type="int", default=3)
  25. bgcolor = idleConf.GetOption("extensions", "CodeContext",
  26. "bgcolor", type="str", default="LightGray")
  27. fgcolor = idleConf.GetOption("extensions", "CodeContext",
  28. "fgcolor", type="str", default="Black")
  29. def __init__(self, editwin):
  30. self.editwin = editwin
  31. self.text = editwin.text
  32. self.textfont = self.text["font"]
  33. self.label = None
  34. # self.info is a list of (line number, indent level, line text, block
  35. # keyword) tuples providing the block structure associated with
  36. # self.topvisible (the linenumber of the line displayed at the top of
  37. # the edit window). self.info[0] is initialized as a 'dummy' line which
  38. # starts the toplevel 'block' of the module.
  39. self.info = [(0, -1, "", False)]
  40. self.topvisible = 1
  41. visible = idleConf.GetOption("extensions", "CodeContext",
  42. "visible", type="bool", default=False)
  43. if visible:
  44. self.toggle_code_context_event()
  45. self.editwin.setvar('<<toggle-code-context>>', True)
  46. # Start two update cycles, one for context lines, one for font changes.
  47. self.text.after(UPDATEINTERVAL, self.timer_event)
  48. self.text.after(FONTUPDATEINTERVAL, self.font_timer_event)
  49. def toggle_code_context_event(self, event=None):
  50. if not self.label:
  51. # Calculate the border width and horizontal padding required to
  52. # align the context with the text in the main Text widget.
  53. #
  54. # All values are passed through int(str(<value>)), since some
  55. # values may be pixel objects, which can't simply be added to ints.
  56. widgets = self.editwin.text, self.editwin.text_frame
  57. # Calculate the required vertical padding
  58. padx = 0
  59. for widget in widgets:
  60. padx += int(str( widget.pack_info()['padx'] ))
  61. padx += int(str( widget.cget('padx') ))
  62. # Calculate the required border width
  63. border = 0
  64. for widget in widgets:
  65. border += int(str( widget.cget('border') ))
  66. self.label = Tkinter.Label(self.editwin.top,
  67. text="\n" * (self.context_depth - 1),
  68. anchor=W, justify=LEFT,
  69. font=self.textfont,
  70. bg=self.bgcolor, fg=self.fgcolor,
  71. width=1, #don't request more than we get
  72. padx=padx, border=border,
  73. relief=SUNKEN)
  74. # Pack the label widget before and above the text_frame widget,
  75. # thus ensuring that it will appear directly above text_frame
  76. self.label.pack(side=TOP, fill=X, expand=False,
  77. before=self.editwin.text_frame)
  78. else:
  79. self.label.destroy()
  80. self.label = None
  81. idleConf.SetOption("extensions", "CodeContext", "visible",
  82. str(self.label is not None))
  83. idleConf.SaveUserCfgFiles()
  84. def get_line_info(self, linenum):
  85. """Get the line indent value, text, and any block start keyword
  86. If the line does not start a block, the keyword value is False.
  87. The indentation of empty lines (or comment lines) is INFINITY.
  88. """
  89. text = self.text.get("%d.0" % linenum, "%d.end" % linenum)
  90. spaces, firstword = getspacesfirstword(text)
  91. opener = firstword in BLOCKOPENERS and firstword
  92. if len(text) == len(spaces) or text[len(spaces)] == '#':
  93. indent = INFINITY
  94. else:
  95. indent = len(spaces)
  96. return indent, text, opener
  97. def get_context(self, new_topvisible, stopline=1, stopindent=0):
  98. """Get context lines, starting at new_topvisible and working backwards.
  99. Stop when stopline or stopindent is reached. Return a tuple of context
  100. data and the indent level at the top of the region inspected.
  101. """
  102. assert stopline > 0
  103. lines = []
  104. # The indentation level we are currently in:
  105. lastindent = INFINITY
  106. # For a line to be interesting, it must begin with a block opening
  107. # keyword, and have less indentation than lastindent.
  108. for linenum in xrange(new_topvisible, stopline-1, -1):
  109. indent, text, opener = self.get_line_info(linenum)
  110. if indent < lastindent:
  111. lastindent = indent
  112. if opener in ("else", "elif"):
  113. # We also show the if statement
  114. lastindent += 1
  115. if opener and linenum < new_topvisible and indent >= stopindent:
  116. lines.append((linenum, indent, text, opener))
  117. if lastindent <= stopindent:
  118. break
  119. lines.reverse()
  120. return lines, lastindent
  121. def update_code_context(self):
  122. """Update context information and lines visible in the context pane.
  123. """
  124. new_topvisible = int(self.text.index("@0,0").split('.')[0])
  125. if self.topvisible == new_topvisible: # haven't scrolled
  126. return
  127. if self.topvisible < new_topvisible: # scroll down
  128. lines, lastindent = self.get_context(new_topvisible,
  129. self.topvisible)
  130. # retain only context info applicable to the region
  131. # between topvisible and new_topvisible:
  132. while self.info[-1][1] >= lastindent:
  133. del self.info[-1]
  134. elif self.topvisible > new_topvisible: # scroll up
  135. stopindent = self.info[-1][1] + 1
  136. # retain only context info associated
  137. # with lines above new_topvisible:
  138. while self.info[-1][0] >= new_topvisible:
  139. stopindent = self.info[-1][1]
  140. del self.info[-1]
  141. lines, lastindent = self.get_context(new_topvisible,
  142. self.info[-1][0]+1,
  143. stopindent)
  144. self.info.extend(lines)
  145. self.topvisible = new_topvisible
  146. # empty lines in context pane:
  147. context_strings = [""] * max(0, self.context_depth - len(self.info))
  148. # followed by the context hint lines:
  149. context_strings += [x[2] for x in self.info[-self.context_depth:]]
  150. self.label["text"] = '\n'.join(context_strings)
  151. def timer_event(self):
  152. if self.label:
  153. self.update_code_context()
  154. self.text.after(UPDATEINTERVAL, self.timer_event)
  155. def font_timer_event(self):
  156. newtextfont = self.text["font"]
  157. if self.label and newtextfont != self.textfont:
  158. self.textfont = newtextfont
  159. self.label["font"] = self.textfont
  160. self.text.after(FONTUPDATEINTERVAL, self.font_timer_event)