Debian Codegraph @

lib_pypy/pyrepl/completing_reader.py

raw symbols SCIP
1 # Copyright 2000-2010 Michael Hudson-Doyle <[email protected]>
2 # Antonio Cuni
3 #
4 # All Rights Reserved
5 #
6 #
7 # Permission to use, copy, modify, and distribute this software and
8 # its documentation for any purpose is hereby granted without fee,
9 # provided that the above copyright notice appear in all copies and
10 # that both that copyright notice and this permission notice appear in
11 # supporting documentation.
12 #
13 # THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
14 # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15 # AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
16 # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
17 # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
18 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
19 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20
21 from __future__ import annotations
22
23 from dataclasses import dataclass, field
24
25 import re
26 from . import commands, console, reader
27 from .reader import Reader
28
29
30 # types
31 Command = commands.Command
32 if False:
33 from collections.abc import Callable
34 from .types import KeySpec, CommandName
35
36
37 def prefix(wordlist: list[str], j: int = 0) -> str:
38 d = {}
39 i = j
40 try:
41 while 1:
42 for word in wordlist:
43 d[word[i]] = 1
44 if len(d) > 1:
45 return wordlist[0][j:i]
46 i += 1
47 d = {}
48 except IndexError:
49 return wordlist[0][j:i]
50 return ""
51
52
53 STRIPCOLOR_REGEX = re.compile(r"\x1B\[([0-9]{1,3}(;[0-9]{1,2})?)?[m|K]")
54
55 def stripcolor(s: str) -> str:
56 return STRIPCOLOR_REGEX.sub('', s)
57
58
59 def real_len(s: str) -> int:
60 return len(stripcolor(s))
61
62
63 def left_align(s: str, maxlen: int) -> str:
64 stripped = stripcolor(s)
65 if len(stripped) > maxlen:
66 # too bad, we remove the color
67 return stripped[:maxlen]
68 padding = maxlen - len(stripped)
69 return s + ' '*padding
70
71
72 def build_menu(
73 cons: console.Console,
74 wordlist: list[str],
75 start: int,
76 use_brackets: bool,
77 sort_in_column: bool,
78 ) -> tuple[list[str], int]:
79 if use_brackets:
80 item = "[ %s ]"
81 padding = 4
82 else:
83 item = "%s "
84 padding = 2
85 maxlen = min(max(map(real_len, wordlist)), cons.width - padding)
86 cols = int(cons.width / (maxlen + padding))
87 rows = int((len(wordlist) - 1)/cols + 1)
88
89 if sort_in_column:
90 # sort_in_column=False (default) sort_in_column=True
91 # A B C A D G
92 # D E F B E
93 # G C F
94 #
95 # "fill" the table with empty words, so we always have the same amout
96 # of rows for each column
97 missing = cols*rows - len(wordlist)
98 wordlist = wordlist + ['']*missing
99 indexes = [(i % cols) * rows + i // cols for i in range(len(wordlist))]
100 wordlist = [wordlist[i] for i in indexes]
101 menu = []
102 i = start
103 for r in range(rows):
104 row = []
105 for col in range(cols):
106 row.append(item % left_align(wordlist[i], maxlen))
107 i += 1
108 if i >= len(wordlist):
109 break
110 menu.append(''.join(row))
111 if i >= len(wordlist):
112 i = 0
113 break
114 if r + 5 > cons.height:
115 menu.append(" %d more... " % (len(wordlist) - i))
116 break
117 return menu, i
118
119 # this gets somewhat user interface-y, and as a result the logic gets
120 # very convoluted.
121 #
122 # To summarise the summary of the summary:- people are a problem.
123 # -- The Hitch-Hikers Guide to the Galaxy, Episode 12
124
125 #### Desired behaviour of the completions commands.
126 # the considerations are:
127 # (1) how many completions are possible
128 # (2) whether the last command was a completion
129 # (3) if we can assume that the completer is going to return the same set of
130 # completions: this is controlled by the ``assume_immutable_completions``
131 # variable on the reader, which is True by default to match the historical
132 # behaviour of pyrepl, but e.g. False in the ReadlineAlikeReader to match
133 # more closely readline's semantics (this is needed e.g. by
134 # fancycompleter)
135 #
136 # if there's no possible completion, beep at the user and point this out.
137 # this is easy.
138 #
139 # if there's only one possible completion, stick it in. if the last thing
140 # user did was a completion, point out that he isn't getting anywhere, but
141 # only if the ``assume_immutable_completions`` is True.
142 #
143 # now it gets complicated.
144 #
145 # for the first press of a completion key:
146 # if there's a common prefix, stick it in.
147
148 # irrespective of whether anything got stuck in, if the word is now
149 # complete, show the "complete but not unique" message
150
151 # if there's no common prefix and if the word is not now complete,
152 # beep.
153
154 # common prefix -> yes no
155 # word complete \/
156 # yes "cbnu" "cbnu"
157 # no - beep
158
159 # for the second bang on the completion key
160 # there will necessarily be no common prefix
161 # show a menu of the choices.
162
163 # for subsequent bangs, rotate the menu around (if there are sufficient
164 # choices).
165
166
167 class complete(commands.Command):
168 def do(self) -> None:
169 r: CompletingReader
170 r = self.reader # type: ignore[assignment]
171 last_is_completer = r.last_command_is(self.__class__)
172 immutable_completions = r.assume_immutable_completions
173 completions_unchangable = last_is_completer and immutable_completions
174 stem = r.get_stem()
175 if not completions_unchangable:
176 r.cmpltn_menu_choices = r.get_completions(stem)
177
178 completions = r.cmpltn_menu_choices
179 if not completions:
180 r.error("no matches")
181 elif len(completions) == 1:
182 if completions_unchangable and len(completions[0]) == len(stem):
183 r.msg = "[ sole completion ]"
184 r.dirty = True
185 r.insert(completions[0][len(stem):])
186 else:
187 p = prefix(completions, len(stem))
188 if p:
189 r.insert(p)
190 if last_is_completer:
191 r.cmpltn_menu_visible = True
192 r.cmpltn_message_visible = False
193 hook = r.get_completion_display_matches_hook()
194 if hook is not None:
195 r.console.restore_output()
196 try:
197 hook(stem, completions, max(len(c) for c in completions))
198 finally:
199 r.console.prepare_output()
200 else:
201 r.cmpltn_menu, r.cmpltn_menu_end = build_menu(
202 r.console, completions, r.cmpltn_menu_end,
203 r.use_brackets, r.sort_in_column)
204 r.dirty = True
205 elif not r.cmpltn_menu_visible:
206 r.cmpltn_message_visible = True
207 if stem + p in completions:
208 r.msg = "[ complete but not unique ]"
209 r.dirty = True
210 else:
211 r.msg = "[ not unique ]"
212 r.dirty = True
213
214
215 class self_insert(commands.self_insert):
216 def do(self) -> None:
217 r: CompletingReader
218 r = self.reader # type: ignore[assignment]
219
220 commands.self_insert.do(self)
221 if r.cmpltn_menu_visible:
222 stem = r.get_stem()
223 if len(stem) < 1:
224 r.cmpltn_reset()
225 else:
226 completions = [w for w in r.cmpltn_menu_choices
227 if w.startswith(stem)]
228 if completions:
229 r.cmpltn_menu, r.cmpltn_menu_end = build_menu(
230 r.console, completions, 0,
231 r.use_brackets, r.sort_in_column)
232 else:
233 r.cmpltn_reset()
234
235
236 @dataclass
237 class CompletingReader(Reader):
238 """Adds completion support"""
239
240 ### Class variables
241 # see the comment for the complete command
242 assume_immutable_completions = True
243 use_brackets = True # display completions inside []
244 sort_in_column = False
245
246 ### Instance variables
247 cmpltn_menu: list[str] = field(init=False)
248 cmpltn_menu_visible: bool = field(init=False)
249 cmpltn_message_visible: bool = field(init=False)
250 cmpltn_menu_end: int = field(init=False)
251 cmpltn_menu_choices: list[str] = field(init=False)
252
253 def __post_init__(self) -> None:
254 super().__post_init__()
255 self.cmpltn_reset()
256 for c in (complete, self_insert):
257 self.commands[c.__name__] = c
258 self.commands[c.__name__.replace('_', '-')] = c
259
260 def collect_keymap(self) -> tuple[tuple[KeySpec, CommandName], ...]:
261 return super().collect_keymap() + (
262 (r'\t', 'complete'),)
263
264 def after_command(self, cmd: Command) -> None:
265 super().after_command(cmd)
266 if not isinstance(cmd, (complete, self_insert)):
267 self.cmpltn_reset()
268
269 def calc_screen(self) -> list[str]:
270 screen = super().calc_screen()
271 if self.cmpltn_menu_visible:
272 ly = self.lxy[1]
273 screen[ly:ly] = self.cmpltn_menu
274 self.screeninfo[ly:ly] = [(0, [])]*len(self.cmpltn_menu)
275 self.cxy = self.cxy[0], self.cxy[1] + len(self.cmpltn_menu)
276 return screen
277
278 def finish(self) -> None:
279 super().finish()
280 self.cmpltn_reset()
281
282 def cmpltn_reset(self) -> None:
283 self.cmpltn_menu = []
284 self.cmpltn_menu_visible = False
285 self.cmpltn_message_visible = False
286 self.cmpltn_menu_end = 0
287 self.cmpltn_menu_choices = []
288
289 def get_stem(self) -> str:
290 st = self.syntax_table
291 SW = reader.SYNTAX_WORD
292 b = self.buffer
293 p = self.pos - 1
294 while p >= 0 and st.get(b[p], SW) == SW:
295 p -= 1
296 return ''.join(b[p+1:self.pos])
297
298 def get_completions(self, stem: str) -> list[str]:
299 return []
300
301 def get_completion_display_matches_hook(self) -> Callable | None:
302 return None