parenmatch.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """ParenMatch -- 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 idlelib.hyperparser import HyperParser
  7. from idlelib.config import idleConf
  8. _openers = {')':'(',']':'[','}':'{'}
  9. CHECK_DELAY = 100 # milliseconds
  10. class ParenMatch:
  11. """Highlight matching openers and closers, (), [], and {}.
  12. There are three supported styles of paren matching. When a right
  13. paren (opener) is typed:
  14. opener -- highlight the matching left paren (closer);
  15. parens -- highlight the left and right parens (opener and closer);
  16. expression -- highlight the entire expression from opener to closer.
  17. (For back compatibility, 'default' is a synonym for 'opener').
  18. Flash-delay is the maximum milliseconds the highlighting remains.
  19. Any cursor movement (key press or click) before that removes the
  20. highlight. If flash-delay is 0, there is no maximum.
  21. TODO:
  22. - Augment bell() with mismatch warning in status window.
  23. - Highlight when cursor is moved to the right of a closer.
  24. This might be too expensive to check.
  25. """
  26. RESTORE_VIRTUAL_EVENT_NAME = "<<parenmatch-check-restore>>"
  27. # We want the restore event be called before the usual return and
  28. # backspace events.
  29. RESTORE_SEQUENCES = ("<KeyPress>", "<ButtonPress>",
  30. "<Key-Return>", "<Key-BackSpace>")
  31. def __init__(self, editwin):
  32. self.editwin = editwin
  33. self.text = editwin.text
  34. # Bind the check-restore event to the function restore_event,
  35. # so that we can then use activate_restore (which calls event_add)
  36. # and deactivate_restore (which calls event_delete).
  37. editwin.text.bind(self.RESTORE_VIRTUAL_EVENT_NAME,
  38. self.restore_event)
  39. self.counter = 0
  40. self.is_restore_active = 0
  41. @classmethod
  42. def reload(cls):
  43. cls.STYLE = idleConf.GetOption(
  44. 'extensions','ParenMatch','style', default='opener')
  45. cls.FLASH_DELAY = idleConf.GetOption(
  46. 'extensions','ParenMatch','flash-delay', type='int',default=500)
  47. cls.BELL = idleConf.GetOption(
  48. 'extensions','ParenMatch','bell', type='bool', default=1)
  49. cls.HILITE_CONFIG = idleConf.GetHighlight(idleConf.CurrentTheme(),
  50. 'hilite')
  51. def activate_restore(self):
  52. "Activate mechanism to restore text from highlighting."
  53. if not self.is_restore_active:
  54. for seq in self.RESTORE_SEQUENCES:
  55. self.text.event_add(self.RESTORE_VIRTUAL_EVENT_NAME, seq)
  56. self.is_restore_active = True
  57. def deactivate_restore(self):
  58. "Remove restore event bindings."
  59. if self.is_restore_active:
  60. for seq in self.RESTORE_SEQUENCES:
  61. self.text.event_delete(self.RESTORE_VIRTUAL_EVENT_NAME, seq)
  62. self.is_restore_active = False
  63. def flash_paren_event(self, event):
  64. "Handle editor 'show surrounding parens' event (menu or shortcut)."
  65. indices = (HyperParser(self.editwin, "insert")
  66. .get_surrounding_brackets())
  67. self.finish_paren_event(indices)
  68. return "break"
  69. def paren_closed_event(self, event):
  70. "Handle user input of closer."
  71. # If user bound non-closer to <<paren-closed>>, quit.
  72. closer = self.text.get("insert-1c")
  73. if closer not in _openers:
  74. return
  75. hp = HyperParser(self.editwin, "insert-1c")
  76. if not hp.is_in_code():
  77. return
  78. indices = hp.get_surrounding_brackets(_openers[closer], True)
  79. self.finish_paren_event(indices)
  80. return # Allow calltips to see ')'
  81. def finish_paren_event(self, indices):
  82. if indices is None and self.BELL:
  83. self.text.bell()
  84. return
  85. self.activate_restore()
  86. # self.create_tag(indices)
  87. self.tagfuncs.get(self.STYLE, self.create_tag_expression)(self, indices)
  88. # self.set_timeout()
  89. (self.set_timeout_last if self.FLASH_DELAY else
  90. self.set_timeout_none)()
  91. def restore_event(self, event=None):
  92. "Remove effect of doing match."
  93. self.text.tag_delete("paren")
  94. self.deactivate_restore()
  95. self.counter += 1 # disable the last timer, if there is one.
  96. def handle_restore_timer(self, timer_count):
  97. if timer_count == self.counter:
  98. self.restore_event()
  99. # any one of the create_tag_XXX methods can be used depending on
  100. # the style
  101. def create_tag_opener(self, indices):
  102. """Highlight the single paren that matches"""
  103. self.text.tag_add("paren", indices[0])
  104. self.text.tag_config("paren", self.HILITE_CONFIG)
  105. def create_tag_parens(self, indices):
  106. """Highlight the left and right parens"""
  107. if self.text.get(indices[1]) in (')', ']', '}'):
  108. rightindex = indices[1]+"+1c"
  109. else:
  110. rightindex = indices[1]
  111. self.text.tag_add("paren", indices[0], indices[0]+"+1c", rightindex+"-1c", rightindex)
  112. self.text.tag_config("paren", self.HILITE_CONFIG)
  113. def create_tag_expression(self, indices):
  114. """Highlight the entire expression"""
  115. if self.text.get(indices[1]) in (')', ']', '}'):
  116. rightindex = indices[1]+"+1c"
  117. else:
  118. rightindex = indices[1]
  119. self.text.tag_add("paren", indices[0], rightindex)
  120. self.text.tag_config("paren", self.HILITE_CONFIG)
  121. tagfuncs = {
  122. 'opener': create_tag_opener,
  123. 'default': create_tag_opener,
  124. 'parens': create_tag_parens,
  125. 'expression': create_tag_expression,
  126. }
  127. # any one of the set_timeout_XXX methods can be used depending on
  128. # the style
  129. def set_timeout_none(self):
  130. """Highlight will remain until user input turns it off
  131. or the insert has moved"""
  132. # After CHECK_DELAY, call a function which disables the "paren" tag
  133. # if the event is for the most recent timer and the insert has changed,
  134. # or schedules another call for itself.
  135. self.counter += 1
  136. def callme(callme, self=self, c=self.counter,
  137. index=self.text.index("insert")):
  138. if index != self.text.index("insert"):
  139. self.handle_restore_timer(c)
  140. else:
  141. self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
  142. self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
  143. def set_timeout_last(self):
  144. """The last highlight created will be removed after FLASH_DELAY millisecs"""
  145. # associate a counter with an event; only disable the "paren"
  146. # tag if the event is for the most recent timer.
  147. self.counter += 1
  148. self.editwin.text_frame.after(
  149. self.FLASH_DELAY,
  150. lambda self=self, c=self.counter: self.handle_restore_timer(c))
  151. ParenMatch.reload()
  152. if __name__ == '__main__':
  153. from unittest import main
  154. main('idlelib.idle_test.test_parenmatch', verbosity=2)