replace.py 9.6 KB

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