"""Replace dialog for IDLE. Inherits SearchDialogBase for GUI.
Uses idlelib.SearchEngine for search capability.
Defines various replace related functions like replace, replace all,
replace+find.
"""
import re

from tkinter import StringVar, TclError

from idlelib.searchbase import SearchDialogBase
from idlelib import searchengine

def replace(text):
    """Returns a singleton ReplaceDialog instance.The single dialog
     saves user entries and preferences across instances."""
    root = text._root()
    engine = searchengine.get(root)
    if not hasattr(engine, "_replacedialog"):
        engine._replacedialog = ReplaceDialog(root, engine)
    dialog = engine._replacedialog
    dialog.open(text)


class ReplaceDialog(SearchDialogBase):

    title = "Replace Dialog"
    icon = "Replace"

    def __init__(self, root, engine):
        SearchDialogBase.__init__(self, root, engine)
        self.replvar = StringVar(root)

    def open(self, text):
        """Display the replace dialog"""
        SearchDialogBase.open(self, text)
        try:
            first = text.index("sel.first")
        except TclError:
            first = None
        try: