0001 class History: 0002 0003 def __init__(self, text, output_sep = "\n"): 0004 self.text = text 0005 self.history = [] 0006 self.history_prefix = None 0007 self.history_pointer = None 0008 self.output_sep = output_sep 0009 text.bind("<<history-previous>>", self.history_prev) 0010 text.bind("<<history-next>>", self.history_next) 0011 0012 def history_next(self, event): 0013 self.history_do(0) 0014 return "break" 0015 0016 def history_prev(self, event): 0017 self.history_do(1) 0018 return "break" 0019 0020 def _get_source(self, start, end): 0021 # Get source code from start index to end index. Lines in the 0022 # text control may be separated by sys.ps2 . 0023 lines = self.text.get(start, end).split(self.output_sep) 0024 return "\n".join(lines) 0025 0026 def _put_source(self, where, source): 0027 output = self.output_sep.join(source.split("\n")) 0028 self.text.insert(where, output) 0029 0030 def history_do(self, reverse): 0031 nhist = len(self.history) 0032 pointer = self.history_pointer 0033 prefix = self.history_prefix 0034 if pointer is not None and prefix is not None: 0035 if self.text.compare("insert", "!=", "end-1c") or \ 0036 self._get_source("iomark", "end-1c") != self.history[pointer]: 0037 pointer = prefix = None 0038 if pointer is None or prefix is None: 0039 prefix = self._get_source("iomark", "end-1c") 0040 if reverse: 0041 pointer = nhist 0042 else: 0043 pointer = -1 0044 nprefix = len(prefix) 0045 while 1: 0046 if reverse: 0047 pointer = pointer - 1 0048 else: 0049 pointer = pointer + 1 0050 if pointer < 0 or pointer >= nhist: 0051 self.text.bell() 0052 if self._get_source("iomark", "end-1c") != prefix: 0053 self.text.delete("iomark", "end-1c") 0054 self._put_source("iomark", prefix) 0055 pointer = prefix = None 0056 break 0057 item = self.history[pointer] 0058 if item[:nprefix] == prefix and len(item) > nprefix: 0059 self.text.delete("iomark", "end-1c") 0060 self._put_source("iomark", item) 0061 break 0062 self.text.mark_set("insert", "end-1c") 0063 self.text.see("insert") 0064 self.text.tag_remove("sel", "1.0", "end") 0065 self.history_pointer = pointer 0066 self.history_prefix = prefix 0067 0068 def history_store(self, source): 0069 source = source.strip() 0070 if len(source) > 2: 0071 # avoid duplicates 0072 try: 0073 self.history.remove(source) 0074 except ValueError: 0075 pass 0076 self.history.append(source) 0077 self.history_pointer = None 0078 self.history_prefix = None 0079 0080 def recall(self, s): 0081 s = s.strip() 0082 self.text.tag_remove("sel", "1.0", "end") 0083 self.text.delete("iomark", "end-1c") 0084 self.text.mark_set("insert", "end-1c") 0085 self.text.insert("insert", s) 0086 self.text.see("insert") 0087
Generated by PyXR 0.9.4