Debian Codegraph @

lib-python/3/idlelib/replace.py

raw symbols SCIP
1 """Replace dialog for IDLE. Inherits SearchDialogBase for GUI.
2 Uses idlelib.searchengine.SearchEngine for search capability.
3 Defines various replace related functions like replace, replace all,
4 and replace+find.
5 """
6 import re
7 re.PatternError = re.error # New in 3.13.
8
9 from tkinter import StringVar, TclError
10
11 from idlelib.searchbase import SearchDialogBase
12 from idlelib import searchengine
13
14
15 def replace(text, insert_tags=None):
16 """Create or reuse a singleton ReplaceDialog instance.
17
18 The singleton dialog saves user entries and preferences
19 across instances.
20
21 Args:
22 text: Text widget containing the text to be searched.
23 """
24 root = text._root()
25 engine = searchengine.get(root)
26 if not hasattr(engine, "_replacedialog"):
27 engine._replacedialog = ReplaceDialog(root, engine)
28 dialog = engine._replacedialog
29 searchphrase = text.get("sel.first", "sel.last")
30 dialog.open(text, searchphrase, insert_tags=insert_tags)
31
32
33 class ReplaceDialog(SearchDialogBase):
34 "Dialog for finding and replacing a pattern in text."
35
36 title = "Replace Dialog"
37 icon = "Replace"
38
39 def __init__(self, root, engine):
40 """Create search dialog for finding and replacing text.
41
42 Uses SearchDialogBase as the basis for the GUI and a
43 searchengine instance to prepare the search.
44
45 Attributes:
46 replvar: StringVar containing 'Replace with:' value.
47 replent: Entry widget for replvar. Created in
48 create_entries().
49 ok: Boolean used in searchengine.search_text to indicate
50 whether the search includes the selection.
51 """
52 super().__init__(root, engine)
53 self.replvar = StringVar(root)
54 self.insert_tags = None
55
56 def open(self, text, searchphrase=None, *, insert_tags=None):
57 """Make dialog visible on top of others and ready to use.
58
59 Also, set the search to include the current selection
60 (self.ok).
61
62 Args:
63 text: Text widget being searched.
64 searchphrase: String phrase to search.
65 """
66 SearchDialogBase.open(self, text, searchphrase)
67 self.ok = True
68 self.insert_tags = insert_tags
69
70 def create_entries(self):
71 "Create base and additional label and text entry widgets."
72 SearchDialogBase.create_entries(self)
73 self.replent = self.make_entry("Replace with:", self.replvar)[0]
74
75 def create_command_buttons(self):
76 """Create base and additional command buttons.
77
78 The additional buttons are for Find, Replace,
79 Replace+Find, and Replace All.
80 """
81 SearchDialogBase.create_command_buttons(self)
82 self.make_button("Find", self.find_it)
83 self.make_button("Replace", self.replace_it)
84 self.make_button("Replace+Find", self.default_command, isdef=True)
85 self.make_button("Replace All", self.replace_all)
86
87 def find_it(self, event=None):
88 "Handle the Find button."
89 self.do_find(False)
90
91 def replace_it(self, event=None):
92 """Handle the Replace button.
93
94 If the find is successful, then perform replace.
95 """
96 if self.do_find(self.ok):
97 self.do_replace()
98
99 def default_command(self, event=None):
100 """Handle the Replace+Find button as the default command.
101
102 First performs a replace and then, if the replace was
103 successful, a find next.
104 """
105 if self.do_find(self.ok):
106 if self.do_replace(): # Only find next match if replace succeeded.
107 # A bad re can cause it to fail.
108 self.do_find(False)
109
110 def _replace_expand(self, m, repl):
111 "Expand replacement text if regular expression."
112 if self.engine.isre():
113 try:
114 new = m.expand(repl)
115 except re.PatternError:
116 self.engine.report_error(repl, 'Invalid Replace Expression')
117 new = None
118 else:
119 new = repl
120
121 return new
122
123 def replace_all(self, event=None):
124 """Handle the Replace All button.
125
126 Search text for occurrences of the Find value and replace
127 each of them. The 'wrap around' value controls the start
128 point for searching. If wrap isn't set, then the searching
129 starts at the first occurrence after the current selection;
130 if wrap is set, the replacement starts at the first line.
131 The replacement is always done top-to-bottom in the text.
132 """
133 prog = self.engine.getprog()
134 if not prog:
135 return
136 repl = self.replvar.get()
137 text = self.text
138 res = self.engine.search_text(text, prog)
139 if not res:
140 self.bell()
141 return
142 text.tag_remove("sel", "1.0", "end")
143 text.tag_remove("hit", "1.0", "end")
144 line = res[0]
145 col = res[1].start()
146 if self.engine.iswrap():
147 line = 1
148 col = 0
149 ok = True
150 first = last = None
151 # XXX ought to replace circular instead of top-to-bottom when wrapping
152 text.undo_block_start()
153 while res := self.engine.search_forward(
154 text, prog, line, col, wrap=False, ok=ok):
155 line, m = res
156 chars = text.get("%d.0" % line, "%d.0" % (line+1))
157 orig = m.group()
158 new = self._replace_expand(m, repl)
159 if new is None:
160 break
161 i, j = m.span()
162 first = "%d.%d" % (line, i)
163 last = "%d.%d" % (line, j)
164 if new == orig:
165 text.mark_set("insert", last)
166 else:
167 text.mark_set("insert", first)
168 if first != last:
169 text.delete(first, last)
170 if new:
171 text.insert(first, new, self.insert_tags)
172 col = i + len(new)
173 ok = False
174 text.undo_block_stop()
175 if first and last:
176 self.show_hit(first, last)
177 self.close()
178
179 def do_find(self, ok=False):
180 """Search for and highlight next occurrence of pattern in text.
181
182 No text replacement is done with this option.
183 """
184 if not self.engine.getprog():
185 return False
186 text = self.text
187 res = self.engine.search_text(text, None, ok)
188 if not res:
189 self.bell()
190 return False
191 line, m = res
192 i, j = m.span()
193 first = "%d.%d" % (line, i)
194 last = "%d.%d" % (line, j)
195 self.show_hit(first, last)
196 self.ok = True
197 return True
198
199 def do_replace(self):
200 "Replace search pattern in text with replacement value."
201 prog = self.engine.getprog()
202 if not prog:
203 return False
204 text = self.text
205 try:
206 first = pos = text.index("sel.first")
207 last = text.index("sel.last")
208 except TclError:
209 pos = None
210 if not pos:
211 first = last = pos = text.index("insert")
212 line, col = searchengine.get_line_col(pos)
213 chars = text.get("%d.0" % line, "%d.0" % (line+1))
214 m = prog.match(chars, col)
215 if not prog:
216 return False
217 new = self._replace_expand(m, self.replvar.get())
218 if new is None:
219 return False
220 text.mark_set("insert", first)
221 text.undo_block_start()
222 if m.group():
223 text.delete(first, last)
224 if new:
225 text.insert(first, new, self.insert_tags)
226 text.undo_block_stop()
227 self.show_hit(first, text.index("insert"))
228 self.ok = False
229 return True
230
231 def show_hit(self, first, last):
232 """Highlight text between first and last indices.
233
234 Text is highlighted via the 'hit' tag and the marked
235 section is brought into view.
236
237 The colors from the 'hit' tag aren't currently shown
238 when the text is displayed. This is due to the 'sel'
239 tag being added first, so the colors in the 'sel'
240 config are seen instead of the colors for 'hit'.
241 """
242 text = self.text
243 text.mark_set("insert", first)
244 text.tag_remove("sel", "1.0", "end")
245 text.tag_add("sel", first, last)
246 text.tag_remove("hit", "1.0", "end")
247 if first == last:
248 text.tag_add("hit", first)
249 else:
250 text.tag_add("hit", first, last)
251 text.see("insert")
252 text.update_idletasks()
253
254 def close(self, event=None):
255 "Close the dialog and remove hit tags."
256 SearchDialogBase.close(self, event)
257 self.text.tag_remove("hit", "1.0", "end")
258 self.insert_tags = None
259
260
261 def _replace_dialog(parent): # htest #
262 from tkinter import Toplevel, Text, END, SEL
263 from tkinter.ttk import Frame, Button
264
265 top = Toplevel(parent)
266 top.title("Test ReplaceDialog")
267 x, y = map(int, parent.geometry().split('+')[1:])
268 top.geometry("+%d+%d" % (x, y + 175))
269
270 # mock undo delegator methods
271 def undo_block_start():
272 pass
273
274 def undo_block_stop():
275 pass
276
277 frame = Frame(top)
278 frame.pack()
279 text = Text(frame, inactiveselectbackground='gray')
280 text.undo_block_start = undo_block_start
281 text.undo_block_stop = undo_block_stop
282 text.pack()
283 text.insert("insert","This is a sample sTring\nPlus MORE.")
284 text.focus_set()
285
286 def show_replace():
287 text.tag_add(SEL, "1.0", END)
288 replace(text)
289 text.tag_remove(SEL, "1.0", END)
290
291 button = Button(frame, text="Replace", command=show_replace)
292 button.pack()
293
294
295 if __name__ == '__main__':
296 from unittest import main
297 main('idlelib.idle_test.test_replace', verbosity=2, exit=False)
298
299 from idlelib.idle_test.htest import run
300 run(_replace_dialog)