'Fetch statememt and replace current line in text widget.
Set prefix and pointer as needed for successive fetches.
Reset them to None, None when returning to the start line.
Sound bell when return to start line or cannot leave a line
because cyclic is False.'

def fetch(self, reverse):

    nhist = len(self.history)
    pointer = self.pointer
    prefix = self.prefix
    if ((pointer is not None) and (prefix is not None)):
        if (self.text.compare('insert', '!=', 'end-1c') or (self.text.get('iomark', 'end-1c') != self.history[pointer])):
            pointer = prefix = None
            self.text.mark_set('insert', 'end-1c')
    if ((pointer is None) or (prefix is None)):
        prefix = self.text.get('iomark', 'end-1c')
        if reverse:
            pointer = nhist
        elif self.cyclic:
            pointer = (-1)
        else:
            self.text.bell()
            return
    nprefix = len(prefix)
    while 1:
        pointer += ((-1) if reverse else 1)
        if ((pointer < 0) or (pointer >= nhist)):
            self.text.bell()
            if ((not self.cyclic) and (pointer < 0)):
                return
            else:
                if (self.text.get('iomark', 'end-1c') != prefix):
                    self.text.delete('iomark', 'end-1c')
                    self.text.insert('iomark', prefix)
                pointer = prefix = None
            break
        item = self.history[pointer]
        if ((item[:nprefix] == prefix) and (len(item) > nprefix)):
            self.text.delete('iomark', 'end-1c')
            self.text.insert('iomark', item)
            break
    self.text.see('insert')
    self.text.tag_remove('sel', '1.0', 'end')
    self.pointer = pointer
    self.prefix = prefix
