blob: c15cb818cd8fbd0d4cea0007e96526bba5fbc6b5 [file] [log] [blame]
David Scherer7aced172000-08-15 01:13:23 +00001"""ParenMatch -- An IDLE extension for parenthesis matching.
2
3When you hit a right paren, the cursor should move briefly to the left
4paren. Paren here is used generically; the matching applies to
5parentheses, square brackets, and curly braces.
David Scherer7aced172000-08-15 01:13:23 +00006"""
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -04007from idlelib.hyperparser import HyperParser
8from idlelib.config import idleConf
David Scherer7aced172000-08-15 01:13:23 +00009
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010_openers = {')':'(',']':'[','}':'{'}
Martin Pantereb995702016-07-28 01:11:04 +000011CHECK_DELAY = 100 # milliseconds
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000012
David Scherer7aced172000-08-15 01:13:23 +000013class ParenMatch:
wohlgangerfae2c352017-06-27 21:36:23 -050014 """Highlight matching openers and closers, (), [], and {}.
David Scherer7aced172000-08-15 01:13:23 +000015
wohlgangerfae2c352017-06-27 21:36:23 -050016 There are three supported styles of paren matching. When a right
17 paren (opener) is typed:
David Scherer7aced172000-08-15 01:13:23 +000018
wohlgangerfae2c352017-06-27 21:36:23 -050019 opener -- highlight the matching left paren (closer);
20 parens -- highlight the left and right parens (opener and closer);
21 expression -- highlight the entire expression from opener to closer.
22 (For back compatibility, 'default' is a synonym for 'opener').
David Scherer7aced172000-08-15 01:13:23 +000023
wohlgangerfae2c352017-06-27 21:36:23 -050024 Flash-delay is the maximum milliseconds the highlighting remains.
25 Any cursor movement (key press or click) before that removes the
26 highlight. If flash-delay is 0, there is no maximum.
David Scherer7aced172000-08-15 01:13:23 +000027
28 TODO:
wohlgangerfae2c352017-06-27 21:36:23 -050029 - Augment bell() with mismatch warning in status window.
30 - Highlight when cursor is moved to the right of a closer.
31 This might be too expensive to check.
David Scherer7aced172000-08-15 01:13:23 +000032 """
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000033 menudefs = [
34 ('edit', [
35 ("Show surrounding parens", "<<flash-paren>>"),
36 ])
37 ]
wohlgangerfae2c352017-06-27 21:36:23 -050038 STYLE = idleConf.GetOption(
39 'extensions','ParenMatch','style', default='expression')
40 FLASH_DELAY = idleConf.GetOption(
41 'extensions','ParenMatch','flash-delay', type='int',default=500)
42 BELL = idleConf.GetOption(
43 'extensions','ParenMatch','bell', type='bool',default=1)
Kurt B. Kaiser8c11f7e2002-09-14 02:46:19 +000044 HILITE_CONFIG = idleConf.GetHighlight(idleConf.CurrentTheme(),'hilite')
David Scherer7aced172000-08-15 01:13:23 +000045
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000046 RESTORE_VIRTUAL_EVENT_NAME = "<<parenmatch-check-restore>>"
47 # We want the restore event be called before the usual return and
48 # backspace events.
49 RESTORE_SEQUENCES = ("<KeyPress>", "<ButtonPress>",
50 "<Key-Return>", "<Key-BackSpace>")
51
David Scherer7aced172000-08-15 01:13:23 +000052 def __init__(self, editwin):
53 self.editwin = editwin
54 self.text = editwin.text
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000055 # Bind the check-restore event to the function restore_event,
56 # so that we can then use activate_restore (which calls event_add)
57 # and deactivate_restore (which calls event_delete).
58 editwin.text.bind(self.RESTORE_VIRTUAL_EVENT_NAME,
59 self.restore_event)
Terry Jan Reedy3ff55a82016-08-10 23:44:54 -040060 self.bell = self.text.bell if self.BELL else lambda: None
David Scherer7aced172000-08-15 01:13:23 +000061 self.counter = 0
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000062 self.is_restore_active = 0
David Scherer7aced172000-08-15 01:13:23 +000063 self.set_style(self.STYLE)
64
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000065 def activate_restore(self):
wohlgangerfae2c352017-06-27 21:36:23 -050066 "Activate mechanism to restore text from highlighting."
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000067 if not self.is_restore_active:
68 for seq in self.RESTORE_SEQUENCES:
69 self.text.event_add(self.RESTORE_VIRTUAL_EVENT_NAME, seq)
70 self.is_restore_active = True
71
72 def deactivate_restore(self):
wohlgangerfae2c352017-06-27 21:36:23 -050073 "Remove restore event bindings."
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000074 if self.is_restore_active:
75 for seq in self.RESTORE_SEQUENCES:
76 self.text.event_delete(self.RESTORE_VIRTUAL_EVENT_NAME, seq)
77 self.is_restore_active = False
78
David Scherer7aced172000-08-15 01:13:23 +000079 def set_style(self, style):
wohlgangerfae2c352017-06-27 21:36:23 -050080 "Set tag and timeout functions."
David Scherer7aced172000-08-15 01:13:23 +000081 self.STYLE = style
wohlgangerfae2c352017-06-27 21:36:23 -050082 self.create_tag = (
83 self.create_tag_opener if style in {"opener", "default"} else
84 self.create_tag_parens if style == "parens" else
85 self.create_tag_expression) # "expression" or unknown
86
87 self.set_timeout = (self.set_timeout_last if self.FLASH_DELAY else
88 self.set_timeout_none)
David Scherer7aced172000-08-15 01:13:23 +000089
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000090 def flash_paren_event(self, event):
wohlgangerfae2c352017-06-27 21:36:23 -050091 "Handle editor 'show surrounding parens' event (menu or shortcut)."
Terry Jan Reedy14fbe722014-06-17 16:35:20 -040092 indices = (HyperParser(self.editwin, "insert")
93 .get_surrounding_brackets())
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000094 if indices is None:
Terry Jan Reedy3ff55a82016-08-10 23:44:54 -040095 self.bell()
Serhiy Storchaka213ce122017-06-27 07:02:32 +030096 return "break"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000097 self.activate_restore()
98 self.create_tag(indices)
wohlgangerfae2c352017-06-27 21:36:23 -050099 self.set_timeout()
Serhiy Storchaka213ce122017-06-27 07:02:32 +0300100 return "break"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000101
102 def paren_closed_event(self, event):
wohlgangerfae2c352017-06-27 21:36:23 -0500103 "Handle user input of closer."
104 # If user bound non-closer to <<paren-closed>>, quit.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000105 closer = self.text.get("insert-1c")
106 if closer not in _openers:
Serhiy Storchaka213ce122017-06-27 07:02:32 +0300107 return "break"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000108 hp = HyperParser(self.editwin, "insert-1c")
109 if not hp.is_in_code():
Serhiy Storchaka213ce122017-06-27 07:02:32 +0300110 return "break"
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000111 indices = hp.get_surrounding_brackets(_openers[closer], True)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000112 if indices is None:
Terry Jan Reedy3ff55a82016-08-10 23:44:54 -0400113 self.bell()
Serhiy Storchaka213ce122017-06-27 07:02:32 +0300114 return "break"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000115 self.activate_restore()
116 self.create_tag(indices)
David Scherer7aced172000-08-15 01:13:23 +0000117 self.set_timeout()
Serhiy Storchaka213ce122017-06-27 07:02:32 +0300118 return "break"
David Scherer7aced172000-08-15 01:13:23 +0000119
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000120 def restore_event(self, event=None):
wohlgangerfae2c352017-06-27 21:36:23 -0500121 "Remove effect of doing match."
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000122 self.text.tag_delete("paren")
123 self.deactivate_restore()
124 self.counter += 1 # disable the last timer, if there is one.
David Scherer7aced172000-08-15 01:13:23 +0000125
126 def handle_restore_timer(self, timer_count):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000127 if timer_count == self.counter:
128 self.restore_event()
David Scherer7aced172000-08-15 01:13:23 +0000129
David Scherer7aced172000-08-15 01:13:23 +0000130 # any one of the create_tag_XXX methods can be used depending on
131 # the style
132
wohlgangerfae2c352017-06-27 21:36:23 -0500133 def create_tag_opener(self, indices):
David Scherer7aced172000-08-15 01:13:23 +0000134 """Highlight the single paren that matches"""
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000135 self.text.tag_add("paren", indices[0])
David Scherer7aced172000-08-15 01:13:23 +0000136 self.text.tag_config("paren", self.HILITE_CONFIG)
137
wohlgangerfae2c352017-06-27 21:36:23 -0500138 def create_tag_parens(self, indices):
139 """Highlight the left and right parens"""
140 if self.text.get(indices[1]) in (')', ']', '}'):
141 rightindex = indices[1]+"+1c"
142 else:
143 rightindex = indices[1]
144 self.text.tag_add("paren", indices[0], indices[0]+"+1c", rightindex+"-1c", rightindex)
145 self.text.tag_config("paren", self.HILITE_CONFIG)
146
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000147 def create_tag_expression(self, indices):
David Scherer7aced172000-08-15 01:13:23 +0000148 """Highlight the entire expression"""
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000149 if self.text.get(indices[1]) in (')', ']', '}'):
150 rightindex = indices[1]+"+1c"
151 else:
152 rightindex = indices[1]
153 self.text.tag_add("paren", indices[0], rightindex)
David Scherer7aced172000-08-15 01:13:23 +0000154 self.text.tag_config("paren", self.HILITE_CONFIG)
155
156 # any one of the set_timeout_XXX methods can be used depending on
157 # the style
158
159 def set_timeout_none(self):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000160 """Highlight will remain until user input turns it off
161 or the insert has moved"""
162 # After CHECK_DELAY, call a function which disables the "paren" tag
163 # if the event is for the most recent timer and the insert has changed,
164 # or schedules another call for itself.
165 self.counter += 1
166 def callme(callme, self=self, c=self.counter,
167 index=self.text.index("insert")):
168 if index != self.text.index("insert"):
169 self.handle_restore_timer(c)
170 else:
171 self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
172 self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
David Scherer7aced172000-08-15 01:13:23 +0000173
174 def set_timeout_last(self):
wohlgangerfae2c352017-06-27 21:36:23 -0500175 """The last highlight created will be removed after FLASH_DELAY millisecs"""
David Scherer7aced172000-08-15 01:13:23 +0000176 # associate a counter with an event; only disable the "paren"
177 # tag if the event is for the most recent timer.
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000178 self.counter += 1
Terry Jan Reedy14fbe722014-06-17 16:35:20 -0400179 self.editwin.text_frame.after(
180 self.FLASH_DELAY,
181 lambda self=self, c=self.counter: self.handle_restore_timer(c))
182
183
184if __name__ == '__main__':
185 import unittest
186 unittest.main('idlelib.idle_test.test_parenmatch', verbosity=2)