replace.py 9.8 KB

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