blob: 3fd7aadb2aea84f10921a321941990cd57ebb6e9 [file] [log] [blame]
wohlganger58fc71c2017-09-10 16:19:47 -05001"""ParenMatch -- for parenthesis matching.
David Scherer7aced172000-08-15 01:13:23 +00002
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 """
David Scherer7aced172000-08-15 01:13:23 +000033
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000034 RESTORE_VIRTUAL_EVENT_NAME = "<<parenmatch-check-restore>>"
35 # We want the restore event be called before the usual return and
36 # backspace events.
37 RESTORE_SEQUENCES = ("<KeyPress>", "<ButtonPress>",
38 "<Key-Return>", "<Key-BackSpace>")
39
David Scherer7aced172000-08-15 01:13:23 +000040 def __init__(self, editwin):
41 self.editwin = editwin
42 self.text = editwin.text
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000043 # Bind the check-restore event to the function restore_event,
44 # so that we can then use activate_restore (which calls event_add)
45 # and deactivate_restore (which calls event_delete).
46 editwin.text.bind(self.RESTORE_VIRTUAL_EVENT_NAME,
47 self.restore_event)
David Scherer7aced172000-08-15 01:13:23 +000048 self.counter = 0
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000049 self.is_restore_active = 0
David Scherer7aced172000-08-15 01:13:23 +000050
wohlganger58fc71c2017-09-10 16:19:47 -050051 @classmethod
52 def reload(cls):
53 cls.STYLE = idleConf.GetOption(
54 'extensions','ParenMatch','style', default='opener')
55 cls.FLASH_DELAY = idleConf.GetOption(
56 'extensions','ParenMatch','flash-delay', type='int',default=500)
57 cls.BELL = idleConf.GetOption(
58 'extensions','ParenMatch','bell', type='bool', default=1)
59 cls.HILITE_CONFIG = idleConf.GetHighlight(idleConf.CurrentTheme(),
60 'hilite')
61
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000062 def activate_restore(self):
wohlgangerfae2c352017-06-27 21:36:23 -050063 "Activate mechanism to restore text from highlighting."
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000064 if not self.is_restore_active:
65 for seq in self.RESTORE_SEQUENCES:
66 self.text.event_add(self.RESTORE_VIRTUAL_EVENT_NAME, seq)
67 self.is_restore_active = True
68
69 def deactivate_restore(self):
wohlgangerfae2c352017-06-27 21:36:23 -050070 "Remove restore event bindings."
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000071 if self.is_restore_active:
72 for seq in self.RESTORE_SEQUENCES:
73 self.text.event_delete(self.RESTORE_VIRTUAL_EVENT_NAME, seq)
74 self.is_restore_active = False
75
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000076 def flash_paren_event(self, event):
wohlgangerfae2c352017-06-27 21:36:23 -050077 "Handle editor 'show surrounding parens' event (menu or shortcut)."
Terry Jan Reedy14fbe722014-06-17 16:35:20 -040078 indices = (HyperParser(self.editwin, "insert")
79 .get_surrounding_brackets())
Terry Jan Reedy5777ecc2017-09-16 01:42:28 -040080 self.finish_paren_event(indices)
Serhiy Storchaka213ce122017-06-27 07:02:32 +030081 return "break"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000082
83 def paren_closed_event(self, event):
wohlgangerfae2c352017-06-27 21:36:23 -050084 "Handle user input of closer."
85 # If user bound non-closer to <<paren-closed>>, quit.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000086 closer = self.text.get("insert-1c")
87 if closer not in _openers:
Terry Jan Reedy89225872017-08-07 13:37:10 -040088 return
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000089 hp = HyperParser(self.editwin, "insert-1c")
90 if not hp.is_in_code():
Terry Jan Reedy89225872017-08-07 13:37:10 -040091 return
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092 indices = hp.get_surrounding_brackets(_openers[closer], True)
Terry Jan Reedy5777ecc2017-09-16 01:42:28 -040093 self.finish_paren_event(indices)
94 return # Allow calltips to see ')'
95
96 def finish_paren_event(self, indices):
97 if indices is None and self.BELL:
98 self.text.bell()
Terry Jan Reedy89225872017-08-07 13:37:10 -040099 return
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000100 self.activate_restore()
Terry Jan Reedy5777ecc2017-09-16 01:42:28 -0400101 # self.create_tag(indices)
102 self.tagfuncs.get(self.STYLE, self.create_tag_expression)(self, indices)
103 # self.set_timeout()
104 (self.set_timeout_last if self.FLASH_DELAY else
105 self.set_timeout_none)()
David Scherer7aced172000-08-15 01:13:23 +0000106
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000107 def restore_event(self, event=None):
wohlgangerfae2c352017-06-27 21:36:23 -0500108 "Remove effect of doing match."
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000109 self.text.tag_delete("paren")
110 self.deactivate_restore()
111 self.counter += 1 # disable the last timer, if there is one.
David Scherer7aced172000-08-15 01:13:23 +0000112
113 def handle_restore_timer(self, timer_count):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000114 if timer_count == self.counter:
115 self.restore_event()
David Scherer7aced172000-08-15 01:13:23 +0000116
David Scherer7aced172000-08-15 01:13:23 +0000117 # any one of the create_tag_XXX methods can be used depending on
118 # the style
119
wohlgangerfae2c352017-06-27 21:36:23 -0500120 def create_tag_opener(self, indices):
David Scherer7aced172000-08-15 01:13:23 +0000121 """Highlight the single paren that matches"""
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000122 self.text.tag_add("paren", indices[0])
David Scherer7aced172000-08-15 01:13:23 +0000123 self.text.tag_config("paren", self.HILITE_CONFIG)
124
wohlgangerfae2c352017-06-27 21:36:23 -0500125 def create_tag_parens(self, indices):
126 """Highlight the left and right parens"""
127 if self.text.get(indices[1]) in (')', ']', '}'):
128 rightindex = indices[1]+"+1c"
129 else:
130 rightindex = indices[1]
131 self.text.tag_add("paren", indices[0], indices[0]+"+1c", rightindex+"-1c", rightindex)
132 self.text.tag_config("paren", self.HILITE_CONFIG)
133
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000134 def create_tag_expression(self, indices):
David Scherer7aced172000-08-15 01:13:23 +0000135 """Highlight the entire expression"""
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000136 if self.text.get(indices[1]) in (')', ']', '}'):
137 rightindex = indices[1]+"+1c"
138 else:
139 rightindex = indices[1]
140 self.text.tag_add("paren", indices[0], rightindex)
David Scherer7aced172000-08-15 01:13:23 +0000141 self.text.tag_config("paren", self.HILITE_CONFIG)
142
Terry Jan Reedy5777ecc2017-09-16 01:42:28 -0400143 tagfuncs = {
144 'opener': create_tag_opener,
145 'default': create_tag_opener,
146 'parens': create_tag_parens,
147 'expression': create_tag_expression,
148 }
149
David Scherer7aced172000-08-15 01:13:23 +0000150 # any one of the set_timeout_XXX methods can be used depending on
151 # the style
152
153 def set_timeout_none(self):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000154 """Highlight will remain until user input turns it off
155 or the insert has moved"""
156 # After CHECK_DELAY, call a function which disables the "paren" tag
157 # if the event is for the most recent timer and the insert has changed,
158 # or schedules another call for itself.
159 self.counter += 1
160 def callme(callme, self=self, c=self.counter,
161 index=self.text.index("insert")):
162 if index != self.text.index("insert"):
163 self.handle_restore_timer(c)
164 else:
165 self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
166 self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
David Scherer7aced172000-08-15 01:13:23 +0000167
168 def set_timeout_last(self):
wohlgangerfae2c352017-06-27 21:36:23 -0500169 """The last highlight created will be removed after FLASH_DELAY millisecs"""
David Scherer7aced172000-08-15 01:13:23 +0000170 # associate a counter with an event; only disable the "paren"
171 # tag if the event is for the most recent timer.
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000172 self.counter += 1
Terry Jan Reedy14fbe722014-06-17 16:35:20 -0400173 self.editwin.text_frame.after(
174 self.FLASH_DELAY,
175 lambda self=self, c=self.counter: self.handle_restore_timer(c))
176
177
wohlganger58fc71c2017-09-10 16:19:47 -0500178ParenMatch.reload()
179
180
Terry Jan Reedy14fbe722014-06-17 16:35:20 -0400181if __name__ == '__main__':
Terry Jan Reedyea3dc802018-06-18 04:47:59 -0400182 from unittest import main
183 main('idlelib.idle_test.test_parenmatch', verbosity=2)