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