blob: 3094173bdfa773fa85a02e9d60bb3f1a50d4d77f [file] [log] [blame]
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +00001import string
2
3class History:
Guido van Rossum504b0bf1999-01-02 21:28:54 +00004
Guido van Rossum3b4ca0d1998-10-10 18:48:31 +00005 def __init__(self, text):
6 self.text = text
7 self.history = []
8 self.history_prefix = None
9 self.history_pointer = None
10 text.bind("<<history-previous>>", self.history_prev)
11 text.bind("<<history-next>>", self.history_next)
12
13 def history_next(self, event):
14 self.history_do(0)
15 return "break"
16
17 def history_prev(self, event):
18 self.history_do(1)
19 return "break"
20
21 def history_do(self, reverse):
22 nhist = len(self.history)
23 pointer = self.history_pointer
24 prefix = self.history_prefix
25 if pointer is not None and prefix is not None:
26 if self.text.compare("insert", "!=", "end-1c") or \
27 self.text.get("iomark", "end-1c") != self.history[pointer]:
28 pointer = prefix = None
29 if pointer is None or prefix is None:
30 prefix = self.text.get("iomark", "end-1c")
31 if reverse:
32 pointer = nhist
33 else:
34 pointer = -1
35 nprefix = len(prefix)
36 while 1:
37 if reverse:
38 pointer = pointer - 1
39 else:
40 pointer = pointer + 1
41 if pointer < 0 or pointer >= nhist:
42 self.text.bell()
43 if self.text.get("iomark", "end-1c") != prefix:
44 self.text.delete("iomark", "end-1c")
45 self.text.insert("iomark", prefix)
46 pointer = prefix = None
47 break
48 item = self.history[pointer]
49 if item[:nprefix] == prefix and len(item) > nprefix:
50 self.text.delete("iomark", "end-1c")
51 self.text.insert("iomark", item)
52 break
53 self.text.mark_set("insert", "end-1c")
54 self.text.see("insert")
55 self.text.tag_remove("sel", "1.0", "end")
56 self.history_pointer = pointer
57 self.history_prefix = prefix
58
59 def history_store(self, source):
60 source = string.strip(source)
61 if len(source) > 2:
62 self.history.append(source)
63 self.history_pointer = None
64 self.history_prefix = None
65
66 def recall(self, s):
67 s = string.strip(s)
68 self.text.tag_remove("sel", "1.0", "end")
69 self.text.delete("iomark", "end-1c")
70 self.text.mark_set("insert", "end-1c")
71 self.text.insert("insert", s)
72 self.text.see("insert")
73