'''Define SearchEngine for search dialogs.'''
from Tkinter import StringVar, BooleanVar, TclError
'''Return the singleton SearchEngine instance for the process.
The single SearchEngine saves settings between dialog instances.
If there is not a SearchEngine already, make one.
if not hasattr(root, "_searchengine"):
root._searchengine = SearchEngine(root)
# This creates a cycle that persists until root is deleted.
return root._searchengine
"""Handles searching a text widget for Find, Replace, and Grep."""
def __init__(self, root):
'''Initialize Variables that save search state.
The dialogs bind these to the UI elements present in the dialogs.
self.root = root # need for report_error()
self.patvar = StringVar(root, '') # search pattern
self.revar = BooleanVar(root, False) # regular expression?
self.casevar = BooleanVar(root, False) # match case?
self.wordvar = BooleanVar(root, False) # match whole word?
self.wrapvar = BooleanVar(root, True) # wrap around buffer?
self.backvar = BooleanVar(root, False) # search backwards?
return self.casevar.get()
return self.wordvar.get()
return self.wrapvar.get()
return self.backvar.get()
# Higher level access methods
def setcookedpat(self, pat):
"Set pattern after escaping if re."
# called only in SearchDialog.py: 66
if not self.isre(): # if True, see setcookedpat
"Return compiled cooked search pattern."
self.report_error(pat, "Empty regular expression")
pat = self.getcookedpat()
flags = flags | re.IGNORECASE
prog = re.compile(pat, flags)
col = args[1] if len(args) >= 2 else -1
self.report_error(pat, msg, col)
def report_error(self, pat, msg, col=-1):
# Derived class could override this with something fancier
msg = "Error: " + str(msg)
msg = msg + "\nPattern: " + str(pat)
msg = msg + "\nOffset: " + str(col)
tkMessageBox.showerror("Regular expression error",
def search_text(self, text, prog=None, ok=0):
'''Return (lineno, matchobj) or None for forward/backward search.
This function calls the right function with the right arguments.
It directly return the result of that call.
Text is a text widget. Prog is a precompiled pattern.
The ok parameter is a bit complicated as it has two effects.
If there is a selection, the search begin at either end,
depending on the direction setting and ok, with ok meaning that
the search starts with the selection. Otherwise, search begins
To aid progress, the search functions do not return an empty
match at the starting position unless ok is True.
return None # Compilation failed -- stop
wrap = self.wrapvar.get()
first, last = get_selection(text)
line, col = get_line_col(start)
res = self.search_backward(text, prog, line, col, wrap, ok)
line, col = get_line_col(start)
res = self.search_forward(text, prog, line, col, wrap, ok)
def search_forward(self, text, prog, line, col, wrap, ok=0):
chars = text.get("%d.0" % line, "%d.0" % (line+1))
m = prog.search(chars[:-1], col)
if wrapped and line > startline:
chars = text.get("%d.0" % line, "%d.0" % (line+1))
chars = text.get("1.0", "2.0")
def search_backward(self, text, prog, line, col, wrap, ok=0):
chars = text.get("%d.0" % line, "%d.0" % (line+1))
m = search_reverse(prog, chars[:-1], col)
if ok or m.start() < col:
if wrapped and line < startline:
pos = text.index("end-1c")
line, col = map(int, pos.split("."))
chars = text.get("%d.0" % line, "%d.0" % (line+1))
def search_reverse(prog, chars, col):
'''Search backwards and return an re match object or None.
This is done by searching forwards until there is no match.
Prog: compiled re object with a search method returning a match.
Chars: line of text, without \\n.
Col: stop index for the search; the limit for match.end().
i, j = m.span() # m.start(), m.end() == match slice indexes
while i < col and j <= col:
m = prog.search(chars, j)
'''Return tuple of 'line.col' indexes from selection or insert mark.
first = text.index("sel.first")
last = text.index("sel.last")
first = text.index("insert")
'''Return (line, col) tuple of ints from 'line.col' string.'''
line, col = map(int, index.split(".")) # Fails on invalid index
if __name__ == "__main__":
unittest.main('idlelib.idle_test.test_searchengine', verbosity=2, exit=False)