Debian Codegraph @

lib_pypy/pyrepl/historical_reader.py

raw symbols SCIP
1 # Copyright 2000-2004 Michael Hudson-Doyle <[email protected]>
2 #
3 # All Rights Reserved
4 #
5 #
6 # Permission to use, copy, modify, and distribute this software and
7 # its documentation for any purpose is hereby granted without fee,
8 # provided that the above copyright notice appear in all copies and
9 # that both that copyright notice and this permission notice appear in
10 # supporting documentation.
11 #
12 # THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
13 # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14 # AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
15 # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
16 # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
17 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
18 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
20 from __future__ import annotations
21
22 from contextlib import contextmanager
23 from dataclasses import dataclass, field
24
25 from . import commands, input
26 from .reader import Reader
27
28
29 if False:
30 from .types import SimpleContextManager, KeySpec, CommandName
31
32
33 isearch_keymap: tuple[tuple[KeySpec, CommandName], ...] = tuple(
34 [("\\%03o" % c, "isearch-end") for c in range(256) if chr(c) != "\\"]
35 + [(c, "isearch-add-character") for c in map(chr, range(32, 127)) if c != "\\"]
36 + [
37 ("\\%03o" % c, "isearch-add-character")
38 for c in range(256)
39 if chr(c).isalpha() and chr(c) != "\\"
40 ]
41 + [
42 ("\\\\", "self-insert"),
43 (r"\C-r", "isearch-backwards"),
44 (r"\C-s", "isearch-forwards"),
45 (r"\C-c", "isearch-cancel"),
46 (r"\C-g", "isearch-cancel"),
47 (r"\<backspace>", "isearch-backspace"),
48 ]
49 )
50
51 ISEARCH_DIRECTION_NONE = ""
52 ISEARCH_DIRECTION_BACKWARDS = "r"
53 ISEARCH_DIRECTION_FORWARDS = "f"
54
55
56 class next_history(commands.Command):
57 def do(self) -> None:
58 r = self.reader
59 if r.historyi == len(r.history):
60 r.error("end of history list")
61 return
62 r.select_item(r.historyi + 1)
63
64
65 class previous_history(commands.Command):
66 def do(self) -> None:
67 r = self.reader
68 if r.historyi == 0:
69 r.error("start of history list")
70 return
71 r.select_item(r.historyi - 1)
72
73
74 class restore_history(commands.Command):
75 def do(self) -> None:
76 r = self.reader
77 if r.historyi != len(r.history):
78 if r.get_unicode() != r.history[r.historyi]:
79 r.buffer = list(r.history[r.historyi])
80 r.pos = len(r.buffer)
81 r.dirty = True
82
83
84 class first_history(commands.Command):
85 def do(self) -> None:
86 self.reader.select_item(0)
87
88
89 class last_history(commands.Command):
90 def do(self) -> None:
91 self.reader.select_item(len(self.reader.history))
92
93
94 class operate_and_get_next(commands.FinishCommand):
95 def do(self) -> None:
96 self.reader.next_history = self.reader.historyi + 1
97
98
99 class yank_arg(commands.Command):
100 def do(self) -> None:
101 r = self.reader
102 if r.last_command is self.__class__:
103 r.yank_arg_i += 1
104 else:
105 r.yank_arg_i = 0
106 if r.historyi < r.yank_arg_i:
107 r.error("beginning of history list")
108 return
109 a = r.get_arg(-1)
110 # XXX how to split?
111 words = r.get_item(r.historyi - r.yank_arg_i - 1).split()
112 if a < -len(words) or a >= len(words):
113 r.error("no such arg")
114 return
115 w = words[a]
116 b = r.buffer
117 if r.yank_arg_i > 0:
118 o = len(r.yank_arg_yanked)
119 else:
120 o = 0
121 b[r.pos - o : r.pos] = list(w)
122 r.yank_arg_yanked = w
123 r.pos += len(w) - o
124 r.dirty = True
125
126
127 class forward_history_isearch(commands.Command):
128 def do(self) -> None:
129 r = self.reader
130 r.isearch_direction = ISEARCH_DIRECTION_FORWARDS
131 r.isearch_start = r.historyi, r.pos
132 r.isearch_term = ""
133 r.dirty = True
134 r.push_input_trans(r.isearch_trans)
135
136
137 class reverse_history_isearch(commands.Command):
138 def do(self) -> None:
139 r = self.reader
140 r.isearch_direction = ISEARCH_DIRECTION_BACKWARDS
141 r.dirty = True
142 r.isearch_term = ""
143 r.push_input_trans(r.isearch_trans)
144 r.isearch_start = r.historyi, r.pos
145
146
147 class isearch_cancel(commands.Command):
148 def do(self) -> None:
149 r = self.reader
150 r.isearch_direction = ISEARCH_DIRECTION_NONE
151 r.pop_input_trans()
152 r.select_item(r.isearch_start[0])
153 r.pos = r.isearch_start[1]
154 r.dirty = True
155
156
157 class isearch_add_character(commands.Command):
158 def do(self) -> None:
159 r = self.reader
160 b = r.buffer
161 r.isearch_term += self.event[-1]
162 r.dirty = True
163 p = r.pos + len(r.isearch_term) - 1
164 if b[p : p + 1] != [r.isearch_term[-1]]:
165 r.isearch_next()
166
167
168 class isearch_backspace(commands.Command):
169 def do(self) -> None:
170 r = self.reader
171 if len(r.isearch_term) > 0:
172 r.isearch_term = r.isearch_term[:-1]
173 r.dirty = True
174 else:
175 r.error("nothing to rubout")
176
177
178 class isearch_forwards(commands.Command):
179 def do(self) -> None:
180 r = self.reader
181 r.isearch_direction = ISEARCH_DIRECTION_FORWARDS
182 r.isearch_next()
183
184
185 class isearch_backwards(commands.Command):
186 def do(self) -> None:
187 r = self.reader
188 r.isearch_direction = ISEARCH_DIRECTION_BACKWARDS
189 r.isearch_next()
190
191
192 class isearch_end(commands.Command):
193 def do(self) -> None:
194 r = self.reader
195 r.isearch_direction = ISEARCH_DIRECTION_NONE
196 r.console.forgetinput()
197 r.pop_input_trans()
198 r.dirty = True
199
200
201 @dataclass
202 class HistoricalReader(Reader):
203 """Adds history support (with incremental history searching) to the
204 Reader class.
205 """
206
207 history: list[str] = field(default_factory=list)
208 historyi: int = 0
209 next_history: int | None = None
210 transient_history: dict[int, str] = field(default_factory=dict)
211 isearch_term: str = ""
212 isearch_direction: str = ISEARCH_DIRECTION_NONE
213 isearch_start: tuple[int, int] = field(init=False)
214 isearch_trans: input.KeymapTranslator = field(init=False)
215 yank_arg_i: int = 0
216 yank_arg_yanked: str = ""
217
218 def __post_init__(self) -> None:
219 super().__post_init__()
220 for c in [
221 next_history,
222 previous_history,
223 restore_history,
224 first_history,
225 last_history,
226 yank_arg,
227 forward_history_isearch,
228 reverse_history_isearch,
229 isearch_end,
230 isearch_add_character,
231 isearch_cancel,
232 isearch_add_character,
233 isearch_backspace,
234 isearch_forwards,
235 isearch_backwards,
236 operate_and_get_next,
237 ]:
238 self.commands[c.__name__] = c
239 self.commands[c.__name__.replace("_", "-")] = c
240 self.isearch_start = self.historyi, self.pos
241 self.isearch_trans = input.KeymapTranslator(
242 isearch_keymap, invalid_cls=isearch_end, character_cls=isearch_add_character
243 )
244
245 def collect_keymap(self) -> tuple[tuple[KeySpec, CommandName], ...]:
246 return super().collect_keymap() + (
247 (r"\C-n", "next-history"),
248 (r"\C-p", "previous-history"),
249 (r"\C-o", "operate-and-get-next"),
250 (r"\C-r", "reverse-history-isearch"),
251 (r"\C-s", "forward-history-isearch"),
252 (r"\M-r", "restore-history"),
253 (r"\M-.", "yank-arg"),
254 (r"\<page down>", "last-history"),
255 (r"\<page up>", "first-history"),
256 )
257
258 def select_item(self, i: int) -> None:
259 self.transient_history[self.historyi] = self.get_unicode()
260 buf = self.transient_history.get(i)
261 if buf is None:
262 buf = self.history[i].rstrip()
263 self.buffer = list(buf)
264 self.historyi = i
265 self.pos = len(self.buffer)
266 self.dirty = True
267 self.last_refresh_cache.invalidated = True
268
269 def get_item(self, i: int) -> str:
270 if i != len(self.history):
271 return self.transient_history.get(i, self.history[i])
272 else:
273 return self.transient_history.get(i, self.get_unicode())
274
275 @contextmanager
276 def suspend(self) -> SimpleContextManager:
277 with super().suspend():
278 try:
279 old_history = self.history[:]
280 del self.history[:]
281 yield
282 finally:
283 self.history[:] = old_history
284
285 def prepare(self) -> None:
286 super().prepare()
287 try:
288 self.transient_history = {}
289 if self.next_history is not None and self.next_history < len(self.history):
290 self.historyi = self.next_history
291 self.buffer[:] = list(self.history[self.next_history])
292 self.pos = len(self.buffer)
293 self.transient_history[len(self.history)] = ""
294 else:
295 self.historyi = len(self.history)
296 self.next_history = None
297 except:
298 self.restore()
299 raise
300
301 def get_prompt(self, lineno: int, cursor_on_line: bool) -> str:
302 if cursor_on_line and self.isearch_direction != ISEARCH_DIRECTION_NONE:
303 d = "rf"[self.isearch_direction == ISEARCH_DIRECTION_FORWARDS]
304 return "(%s-search `%s') " % (d, self.isearch_term)
305 else:
306 return super().get_prompt(lineno, cursor_on_line)
307
308 def isearch_next(self) -> None:
309 st = self.isearch_term
310 p = self.pos
311 i = self.historyi
312 s = self.get_unicode()
313 forwards = self.isearch_direction == ISEARCH_DIRECTION_FORWARDS
314 while 1:
315 if forwards:
316 p = s.find(st, p + 1)
317 else:
318 p = s.rfind(st, 0, p + len(st) - 1)
319 if p != -1:
320 self.select_item(i)
321 self.pos = p
322 return
323 elif (forwards and i >= len(self.history) - 1) or (not forwards and i == 0):
324 self.error("not found")
325 return
326 else:
327 if forwards:
328 i += 1
329 s = self.get_item(i)
330 p = -1
331 else:
332 i -= 1
333 s = self.get_item(i)
334 p = len(s)
335
336 def finish(self) -> None:
337 super().finish()
338 ret = self.get_unicode()
339 for i, t in self.transient_history.items():
340 if i < len(self.history) and i != self.historyi:
341 self.history[i] = t
342 if ret and should_auto_add_history:
343 self.history.append(ret)
344
345
346 should_auto_add_history = True