replace.py 9.7 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):
  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 True:
  133. res = self.engine.search_forward(text, prog, line, col,
  134. wrap=False, ok=ok)
  135. if not res:
  136. break
  137. line, m = res
  138. chars = text.get("%d.0" % line, "%d.0" % (line+1))
  139. orig = m.group()
  140. new = self._replace_expand(m, repl)
  141. if new is None:
  142. break
  143. i, j = m.span()
  144. first = "%d.%d" % (line, i)
  145. last = "%d.%d" % (line, j)
  146. if new == orig:
  147. text.mark_set("insert", last)
  148. else:
  149. text.mark_set("insert", first)
  150. if first != last:
  151. text.delete(first, last)
  152. if new:
  153. text.insert(first, new)
  154. col = i + len(new)
  155. ok = False
  156. text.undo_block_stop()
  157. if first and last:
  158. self.show_hit(first, last)
  159. self.close()
  160. def do_find(self, ok=False):
  161. """Search for and highlight next occurrence of pattern in text.
  162. No text replacement is done with this option.
  163. """
  164. if not self.engine.getprog():
  165. return False
  166. text = self.text
  167. res = self.engine.search_text(text, None, ok)
  168. if not res:
  169. self.bell()
  170. return False
  171. line, m = res
  172. i, j = m.span()
  173. first = "%d.%d" % (line, i)
  174. last = "%d.%d" % (line, j)
  175. self.show_hit(first, last)
  176. self.ok = True
  177. return True
  178. def do_replace(self):
  179. "Replace search pattern in text with replacement value."
  180. prog = self.engine.getprog()
  181. if not prog:
  182. return False
  183. text = self.text
  184. try:
  185. first = pos = text.index("sel.first")
  186. last = text.index("sel.last")
  187. except TclError:
  188. pos = None
  189. if not pos:
  190. first = last = pos = text.index("insert")
  191. line, col = searchengine.get_line_col(pos)
  192. chars = text.get("%d.0" % line, "%d.0" % (line+1))
  193. m = prog.match(chars, col)
  194. if not prog:
  195. return False
  196. new = self._replace_expand(m, self.replvar.get())
  197. if new is None:
  198. return False
  199. text.mark_set("insert", first)
  200. text.undo_block_start()
  201. if m.group():
  202. text.delete(first, last)
  203. if new:
  204. text.insert(first, new)
  205. text.undo_block_stop()
  206. self.show_hit(first, text.index("insert"))
  207. self.ok = False
  208. return True
  209. def show_hit(self, first, last):
  210. """Highlight text between first and last indices.
  211. Text is highlighted via the 'hit' tag and the marked
  212. section is brought into view.
  213. The colors from the 'hit' tag aren't currently shown
  214. when the text is displayed. This is due to the 'sel'
  215. tag being added first, so the colors in the 'sel'
  216. config are seen instead of the colors for 'hit'.
  217. """
  218. text = self.text
  219. text.mark_set("insert", first)
  220. text.tag_remove("sel", "1.0", "end")
  221. text.tag_add("sel", first, last)
  222. text.tag_remove("hit", "1.0", "end")
  223. if first == last:
  224. text.tag_add("hit", first)
  225. else:
  226. text.tag_add("hit", first, last)
  227. text.see("insert")
  228. text.update_idletasks()
  229. def close(self, event=None):
  230. "Close the dialog and remove hit tags."
  231. SearchDialogBase.close(self, event)
  232. self.text.tag_remove("hit", "1.0", "end")
  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)