ParenMatch.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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 idlelib.HyperParser import HyperParser
  7. from idlelib.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")
  78. .get_surrounding_brackets())
  79. if indices is None:
  80. self.warn_mismatched()
  81. return
  82. self.activate_restore()
  83. self.create_tag(indices)
  84. self.set_timeout_last()
  85. def paren_closed_event(self, event):
  86. # If it was a shortcut and not really a closing paren, quit.
  87. closer = self.text.get("insert-1c")
  88. if closer not in _openers:
  89. return
  90. hp = HyperParser(self.editwin, "insert-1c")
  91. if not hp.is_in_code():
  92. return
  93. indices = hp.get_surrounding_brackets(_openers[closer], True)
  94. if indices is None:
  95. self.warn_mismatched()
  96. return
  97. self.activate_restore()
  98. self.create_tag(indices)
  99. self.set_timeout()
  100. def restore_event(self, event=None):
  101. self.text.tag_delete("paren")
  102. self.deactivate_restore()
  103. self.counter += 1 # disable the last timer, if there is one.
  104. def handle_restore_timer(self, timer_count):
  105. if timer_count == self.counter:
  106. self.restore_event()
  107. def warn_mismatched(self):
  108. if self.BELL:
  109. self.text.bell()
  110. # any one of the create_tag_XXX methods can be used depending on
  111. # the style
  112. def create_tag_default(self, indices):
  113. """Highlight the single paren that matches"""
  114. self.text.tag_add("paren", indices[0])
  115. self.text.tag_config("paren", self.HILITE_CONFIG)
  116. def create_tag_expression(self, indices):
  117. """Highlight the entire expression"""
  118. if self.text.get(indices[1]) in (')', ']', '}'):
  119. rightindex = indices[1]+"+1c"
  120. else:
  121. rightindex = indices[1]
  122. self.text.tag_add("paren", indices[0], rightindex)
  123. self.text.tag_config("paren", self.HILITE_CONFIG)
  124. # any one of the set_timeout_XXX methods can be used depending on
  125. # the style
  126. def set_timeout_none(self):
  127. """Highlight will remain until user input turns it off
  128. or the insert has moved"""
  129. # After CHECK_DELAY, call a function which disables the "paren" tag
  130. # if the event is for the most recent timer and the insert has changed,
  131. # or schedules another call for itself.
  132. self.counter += 1
  133. def callme(callme, self=self, c=self.counter,
  134. index=self.text.index("insert")):
  135. if index != self.text.index("insert"):
  136. self.handle_restore_timer(c)
  137. else:
  138. self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
  139. self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
  140. def set_timeout_last(self):
  141. """The last highlight created will be removed after .5 sec"""
  142. # associate a counter with an event; only disable the "paren"
  143. # tag if the event is for the most recent timer.
  144. self.counter += 1
  145. self.editwin.text_frame.after(
  146. self.FLASH_DELAY,
  147. lambda self=self, c=self.counter: self.handle_restore_timer(c))
  148. if __name__ == '__main__':
  149. import unittest
  150. unittest.main('idlelib.idle_test.test_parenmatch', verbosity=2)