/Lib/idlelib/ParenMatch.py

http://unladen-swallow.googlecode.com/ · Python · 172 lines · 141 code · 3 blank · 28 comment · 0 complexity · 4456c7cf8d8baa5bd9545bfd5b47a893 MD5 · raw file

  1. """ParenMatch -- An IDLE extension for parenthesis matching.
  2. When you hit a right paren, the cursor should move briefly to the left
  3. paren. Paren here is used generically; the matching applies to
  4. parentheses, square brackets, and curly braces.
  5. """
  6. from HyperParser import HyperParser
  7. from configHandler import idleConf
  8. _openers = {')':'(',']':'[','}':'{'}
  9. CHECK_DELAY = 100 # miliseconds
  10. class ParenMatch:
  11. """Highlight matching parentheses
  12. There are three supported style of paren matching, based loosely
  13. on the Emacs options. The style is select based on the
  14. HILITE_STYLE attribute; it can be changed used the set_style
  15. method.
  16. The supported styles are:
  17. default -- When a right paren is typed, highlight the matching
  18. left paren for 1/2 sec.
  19. expression -- When a right paren is typed, highlight the entire
  20. expression from the left paren to the right paren.
  21. TODO:
  22. - extend IDLE with configuration dialog to change options
  23. - implement rest of Emacs highlight styles (see below)
  24. - print mismatch warning in IDLE status window
  25. Note: In Emacs, there are several styles of highlight where the
  26. matching paren is highlighted whenever the cursor is immediately
  27. to the right of a right paren. I don't know how to do that in Tk,
  28. so I haven't bothered.
  29. """
  30. menudefs = [
  31. ('edit', [
  32. ("Show surrounding parens", "<<flash-paren>>"),
  33. ])
  34. ]
  35. STYLE = idleConf.GetOption('extensions','ParenMatch','style',
  36. default='expression')
  37. FLASH_DELAY = idleConf.GetOption('extensions','ParenMatch','flash-delay',
  38. type='int',default=500)
  39. HILITE_CONFIG = idleConf.GetHighlight(idleConf.CurrentTheme(),'hilite')
  40. BELL = idleConf.GetOption('extensions','ParenMatch','bell',
  41. type='bool',default=1)
  42. RESTORE_VIRTUAL_EVENT_NAME = "<<parenmatch-check-restore>>"
  43. # We want the restore event be called before the usual return and
  44. # backspace events.
  45. RESTORE_SEQUENCES = ("<KeyPress>", "<ButtonPress>",
  46. "<Key-Return>", "<Key-BackSpace>")
  47. def __init__(self, editwin):
  48. self.editwin = editwin
  49. self.text = editwin.text
  50. # Bind the check-restore event to the function restore_event,
  51. # so that we can then use activate_restore (which calls event_add)
  52. # and deactivate_restore (which calls event_delete).
  53. editwin.text.bind(self.RESTORE_VIRTUAL_EVENT_NAME,
  54. self.restore_event)
  55. self.counter = 0
  56. self.is_restore_active = 0
  57. self.set_style(self.STYLE)
  58. def activate_restore(self):
  59. if not self.is_restore_active:
  60. for seq in self.RESTORE_SEQUENCES:
  61. self.text.event_add(self.RESTORE_VIRTUAL_EVENT_NAME, seq)
  62. self.is_restore_active = True
  63. def deactivate_restore(self):
  64. if self.is_restore_active:
  65. for seq in self.RESTORE_SEQUENCES:
  66. self.text.event_delete(self.RESTORE_VIRTUAL_EVENT_NAME, seq)
  67. self.is_restore_active = False
  68. def set_style(self, style):
  69. self.STYLE = style
  70. if style == "default":
  71. self.create_tag = self.create_tag_default
  72. self.set_timeout = self.set_timeout_last
  73. elif style == "expression":
  74. self.create_tag = self.create_tag_expression
  75. self.set_timeout = self.set_timeout_none
  76. def flash_paren_event(self, event):
  77. indices = HyperParser(self.editwin, "insert").get_surrounding_brackets()
  78. if indices is None:
  79. self.warn_mismatched()
  80. return
  81. self.activate_restore()
  82. self.create_tag(indices)
  83. self.set_timeout_last()
  84. def paren_closed_event(self, event):
  85. # If it was a shortcut and not really a closing paren, quit.
  86. closer = self.text.get("insert-1c")
  87. if closer not in _openers:
  88. return
  89. hp = HyperParser(self.editwin, "insert-1c")
  90. if not hp.is_in_code():
  91. return
  92. indices = hp.get_surrounding_brackets(_openers[closer], True)
  93. if indices is None:
  94. self.warn_mismatched()
  95. return
  96. self.activate_restore()
  97. self.create_tag(indices)
  98. self.set_timeout()
  99. def restore_event(self, event=None):
  100. self.text.tag_delete("paren")
  101. self.deactivate_restore()
  102. self.counter += 1 # disable the last timer, if there is one.
  103. def handle_restore_timer(self, timer_count):
  104. if timer_count == self.counter:
  105. self.restore_event()
  106. def warn_mismatched(self):
  107. if self.BELL:
  108. self.text.bell()
  109. # any one of the create_tag_XXX methods can be used depending on
  110. # the style
  111. def create_tag_default(self, indices):
  112. """Highlight the single paren that matches"""
  113. self.text.tag_add("paren", indices[0])
  114. self.text.tag_config("paren", self.HILITE_CONFIG)
  115. def create_tag_expression(self, indices):
  116. """Highlight the entire expression"""
  117. if self.text.get(indices[1]) in (')', ']', '}'):
  118. rightindex = indices[1]+"+1c"
  119. else:
  120. rightindex = indices[1]
  121. self.text.tag_add("paren", indices[0], rightindex)
  122. self.text.tag_config("paren", self.HILITE_CONFIG)
  123. # any one of the set_timeout_XXX methods can be used depending on
  124. # the style
  125. def set_timeout_none(self):
  126. """Highlight will remain until user input turns it off
  127. or the insert has moved"""
  128. # After CHECK_DELAY, call a function which disables the "paren" tag
  129. # if the event is for the most recent timer and the insert has changed,
  130. # or schedules another call for itself.
  131. self.counter += 1
  132. def callme(callme, self=self, c=self.counter,
  133. index=self.text.index("insert")):
  134. if index != self.text.index("insert"):
  135. self.handle_restore_timer(c)
  136. else:
  137. self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
  138. self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
  139. def set_timeout_last(self):
  140. """The last highlight created will be removed after .5 sec"""
  141. # associate a counter with an event; only disable the "paren"
  142. # tag if the event is for the most recent timer.
  143. self.counter += 1
  144. self.editwin.text_frame.after(self.FLASH_DELAY,
  145. lambda self=self, c=self.counter: \
  146. self.handle_restore_timer(c))