'Replace all instances of patvar with replvar in text'

def replace_all(self, event=None):

    prog = self.engine.getprog()
    if (not prog):
        return
    repl = self.replvar.get()
    text = self.text
    res = self.engine.search_text(text, prog)
    if (not res):
        self.bell()
        return
    text.tag_remove('sel', '1.0', 'end')
    text.tag_remove('hit', '1.0', 'end')
    line = res[0]
    col = res[1].start()
    if self.engine.iswrap():
        line = 1
        col = 0
    ok = 1
    first = last = None
    text.undo_block_start()
    while 1:
        res = self.engine.search_forward(text, prog, line, col, 0, ok)
        if (not res):
            break
        (line, m) = res
        chars = text.get(('%d.0' % line), ('%d.0' % (line + 1)))
        orig = m.group()
        new = self._replace_expand(m, repl)
        if (new is None):
            break
        (i, j) = m.span()
        first = ('%d.%d' % (line, i))
        last = ('%d.%d' % (line, j))
        if (new == orig):
            text.mark_set('insert', last)
        else:
            text.mark_set('insert', first)
            if (first != last):
                text.delete(first, last)
            if new:
                text.insert(first, new)
        col = (i + len(new))
        ok = 0
    text.undo_block_stop()
    if (first and last):
        self.show_hit(first, last)
    self.close()
