OILS / core / comp_ui.py View on Github | oils.pub

587 lines, 296 significant
1"""comp_ui.py."""
2from __future__ import print_function
3
4from core import completion
5from display import ansi
6from display import pp_value
7import libc
8
9from mycpp import mylib
10
11from typing import Any, List, Optional, Dict, TYPE_CHECKING
12if TYPE_CHECKING:
13 from frontend.py_readline import Readline
14 from core.util import _DebugFile
15 from mycpp import iolib
16
17# ANSI escape codes affect the prompt!
18# https://superuser.com/questions/301353/escape-non-printing-characters-in-a-function-for-a-bash-prompt
19#
20# Readline understands \x01 and \x02, while bash understands \[ and \].
21
22# NOTE: There were used in demoish.py. Do we still want those styles?
23if 0:
24 PROMPT_BOLD = '\x01%s\x02' % ansi.BOLD
25 PROMPT_RESET = '\x01%s\x02' % ansi.RESET
26 PROMPT_UNDERLINE = '\x01%s\x02' % ansi.UNDERLINE
27 PROMPT_REVERSE = '\x01%s\x02' % ansi.REVERSE
28
29
30def _PromptLen(prompt_str):
31 # type: (str) -> int
32 """Ignore all characters between \x01 and \x02 and handle unicode
33 characters.
34
35 In particular, the display width of a string may be different from
36 either the number of bytes or the number of unicode characters.
37 Additionally, if there are multiple lines in the prompt, only give
38 the length of the last line.
39 """
40 escaped = False
41 display_str = ""
42 for c in prompt_str:
43 if c == '\x01':
44 escaped = True
45 elif c == '\x02':
46 escaped = False
47 elif not escaped:
48 # mycpp: rewrite of +=
49 display_str = display_str + c
50 last_line = display_str.split('\n')[-1]
51 return pp_value.TryUnicodeWidth(last_line)
52
53
54class PromptState(object):
55 """For the InteractiveLineReader to communicate with the Display
56 callback."""
57
58 def __init__(self):
59 # type: () -> None
60 self.last_prompt_str = None # type: Optional[str]
61 self.last_prompt_len = -1
62
63 def SetLastPrompt(self, prompt_str):
64 # type: (str) -> None
65 self.last_prompt_str = prompt_str
66 self.last_prompt_len = _PromptLen(prompt_str)
67
68
69class State(object):
70 """For the RootCompleter to communicate with the Display callback."""
71
72 def __init__(self):
73 # type: () -> None
74 # original line, truncated
75 self.line_until_tab = None # type: Optional[str]
76
77 # Start offset in EVERY candidate to display. We send fully-completed
78 # LINES to readline because we don't want it to do its own word splitting.
79 self.display_pos = -1
80
81 # completion candidate descriptions
82 self.descriptions = {} # type: Dict[str, str]
83
84
85class _IDisplay(object):
86 """Interface for completion displays."""
87
88 def __init__(self, comp_state, prompt_state, num_lines_cap, f, debug_f):
89 # type: (State, PromptState, int, mylib.Writer, _DebugFile) -> None
90 self.comp_state = comp_state
91 self.prompt_state = prompt_state
92 self.num_lines_cap = num_lines_cap
93 self.f = f
94 self.debug_f = debug_f
95
96 def PrintCandidates(self, unused_subst, matches, unused_match_len):
97 # type: (Optional[str], List[str], int) -> None
98 try:
99 self._PrintCandidates(unused_subst, matches, unused_match_len)
100 except Exception:
101 if 0:
102 import traceback
103 traceback.print_exc()
104
105 def _PrintCandidates(self, unused_subst, matches, unused_match_len):
106 # type: (Optional[str], List[str], int) -> None
107 """Abstract method."""
108 raise NotImplementedError()
109
110 def Reset(self):
111 # type: () -> None
112 """Call this in between commands."""
113 pass
114
115 def ExtraReadlineCommands(self):
116 # type: () -> List[str]
117 """Returns a list of commands to run when initializing readline."""
118 return []
119
120 def ShowPromptOnRight(self, rendered):
121 # type: (str) -> None
122 # Doesn't apply to MinimalDisplay
123 pass
124
125 def EraseLines(self):
126 # type: () -> None
127 # Doesn't apply to MinimalDisplay
128 pass
129
130 if mylib.PYTHON:
131
132 def PrintRequired(self, msg, *args):
133 # type: (str, *Any) -> None
134 # This gets called with "nothing to display"
135 pass
136
137 def PrintOptional(self, msg, *args):
138 # type: (str, *Any) -> None
139 pass
140
141
142class MinimalDisplay(_IDisplay):
143 """A display with minimal dependencies.
144
145 It doesn't output color or depend on the terminal width. It could be
146 useful if we ever have a browser build! We can see completion
147 without testing it.
148 """
149
150 def __init__(self, comp_state, prompt_state, debug_f):
151 # type: (State, PromptState, _DebugFile) -> None
152 _IDisplay.__init__(self, comp_state, prompt_state, 10, mylib.Stdout(),
153 debug_f)
154
155 def _RedrawPrompt(self):
156 # type: () -> None
157 # NOTE: This has to reprint the prompt and the command line!
158 # Like bash, we SAVE the prompt and print it, rather than re-evaluating it.
159 self.f.write(self.prompt_state.last_prompt_str)
160 self.f.write(self.comp_state.line_until_tab)
161
162 def _PrintCandidates(self, unused_subst, matches, unused_match_len):
163 # type: (Optional[str], List[str], int) -> None
164 #log('_PrintCandidates %s', matches)
165 self.f.write('\n') # need this
166 display_pos = self.comp_state.display_pos
167 assert display_pos != -1
168
169 too_many = False
170 i = 0
171 for m in matches:
172 self.f.write(' %s\n' % m[display_pos:])
173
174 if i == self.num_lines_cap:
175 too_many = True
176 i += 1 # Count this one
177 break
178
179 i += 1
180
181 if too_many:
182 num_left = len(matches) - i
183 if num_left:
184 self.f.write(' ... and %d more\n' % num_left)
185
186 self._RedrawPrompt()
187
188 if mylib.PYTHON:
189
190 def PrintRequired(self, msg, *args):
191 # type: (str, *Any) -> None
192 self.f.write('\n')
193 if args:
194 msg = msg % args
195 self.f.write(' %s\n' % msg) # need a newline
196 self._RedrawPrompt()
197
198
199def _PrintPacked(matches, max_match_len, term_width, max_lines, f):
200 # type: (List[str], int, int, int, mylib.Writer) -> int
201 # With of each candidate. 2 spaces between each.
202 w = max_match_len + 2
203
204 # Number of candidates per line. Don't print in first or last column.
205 num_per_line = max(1, (term_width - 2) // w)
206
207 fmt = '%-' + str(w) + 's'
208 num_lines = 0
209
210 too_many = False
211 remainder = num_per_line - 1
212 i = 0 # num matches
213 for m in matches:
214 if i % num_per_line == 0:
215 f.write(' ') # 1 space left gutter
216
217 f.write(fmt % m)
218
219 if i % num_per_line == remainder:
220 f.write('\n') # newline (leaving 1 space right gutter)
221 num_lines += 1
222
223 # Check if we've printed enough lines
224 if num_lines == max_lines:
225 too_many = True
226 i += 1 # count this one
227 break
228 i += 1
229
230 # Write last line break, unless it came out exactly.
231 if i % num_per_line != 0:
232 #log('i = %d, num_per_line = %d, i %% num_per_line = %d',
233 # i, num_per_line, i % num_per_line)
234
235 f.write('\n')
236 num_lines += 1
237
238 if too_many:
239 # TODO: Save this in the Display class
240 fmt2 = ansi.BOLD + ansi.BLUE + '%' + str(term_width -
241 2) + 's' + ansi.RESET
242 num_left = len(matches) - i
243 if num_left:
244 f.write(fmt2 % '... and %d more\n' % num_left)
245 num_lines += 1
246
247 return num_lines
248
249
250def _PrintLong(
251 matches, # type: List[str]
252 max_match_len, # type: int
253 term_width, # type: int
254 max_lines, # type: int
255 descriptions, # type: Dict[str, str]
256 f, # type: mylib.Writer
257):
258 # type: (...) -> int
259 """Print flags with descriptions, one per line.
260
261 Args:
262 descriptions: dict of { prefix-stripped match -> description }
263
264 Returns:
265 The number of lines printed.
266 """
267 #log('desc = %s', descriptions)
268
269 # Subtract 3 chars: 1 for left and right margin, and then 1 for the space in
270 # between.
271 max_desc = max(0, term_width - max_match_len - 3)
272 fmt = ' %-' + str(
273 max_match_len) + 's ' + ansi.YELLOW + '%s' + ansi.RESET + '\n'
274
275 num_lines = 0
276
277 # rl_match is a raw string, which may or may not have a trailing space
278 for rl_match in matches:
279 desc = descriptions.get(rl_match)
280 if desc is None:
281 desc = ''
282 if max_desc == 0: # the window is not wide enough for some flag
283 f.write(' %s\n' % rl_match)
284 else:
285 if len(desc) > max_desc:
286 desc = desc[:max_desc - 5] + ' ... '
287 f.write(fmt % (rl_match, desc))
288
289 num_lines += 1
290
291 if num_lines == max_lines:
292 # right justify
293 fmt2 = ansi.BOLD + ansi.BLUE + '%' + str(term_width -
294 1) + 's' + ansi.RESET
295 num_left = len(matches) - num_lines
296 if num_left:
297 f.write(fmt2 % '... and %d more\n' % num_left)
298 num_lines += 1
299 break
300
301 return num_lines
302
303
304class NiceDisplay(_IDisplay):
305 """Methods to display completion candidates and other messages.
306
307 This object has to remember how many lines we last drew, in order to erase
308 them before drawing something new.
309
310 It's also useful for:
311 - Stripping off the common prefix according to OUR rules, not readline's.
312 - displaying descriptions of flags and builtins
313 """
314
315 def __init__(
316 self,
317 term_width, # type: int
318 comp_state, # type: State
319 prompt_state, # type: PromptState
320 debug_f, # type: _DebugFile
321 readline, # type: Optional[Readline]
322 signal_safe, # type: iolib.SignalSafe
323 ):
324 # type: (...) -> None
325 """
326 Args:
327 bold_line: Should user's entry be bold?
328 """
329 _IDisplay.__init__(self, comp_state, prompt_state, 10, mylib.Stdout(),
330 debug_f)
331
332 self.term_width = term_width # initial terminal width; will be invalidated
333
334 self.readline = readline
335 self.signal_safe = signal_safe
336
337 self.bold_line = False
338
339 self.num_lines_last_displayed = 0
340
341 # For debugging only, could get rid of
342 self.c_count = 0
343 self.m_count = 0
344
345 # hash of matches -> count. Has exactly ONE entry at a time.
346 self.dupes = {} # type: Dict[int, int]
347
348 def Reset(self):
349 # type: () -> None
350 """Call this in between commands."""
351 self.num_lines_last_displayed = 0
352 self.dupes.clear()
353
354 def ExtraReadlineCommands(self):
355 # type: () -> List[str]
356 """Returns a list of commands to run when initializing readline."""
357 return ['set horizontal-scroll-mode on']
358
359 def _ReturnToPrompt(self, num_lines):
360 # type: (int) -> None
361 # NOTE: We can't use ANSI terminal codes to save and restore the prompt,
362 # because the screen may have scrolled. Instead we have to keep track of
363 # how many lines we printed and the original column of the cursor.
364
365 orig_len = len(self.comp_state.line_until_tab)
366
367 self.f.write('\x1b[%dA' % num_lines) # UP
368 last_prompt_len = self.prompt_state.last_prompt_len
369 assert last_prompt_len != -1
370
371 # Go right, but not more than the terminal width.
372 n = orig_len + last_prompt_len
373 n = n % self._GetTerminalWidth()
374 self.f.write('\x1b[%dC' % n) # RIGHT
375
376 if self.bold_line:
377 self.f.write(ansi.BOLD) # Experiment
378
379 self.f.flush()
380
381 def _PrintCandidates(self, unused_subst, matches, unused_max_match_len):
382 # type: (Optional[str], List[str], int) -> None
383 term_width = self._GetTerminalWidth()
384
385 # Variables set by the completion generator. They should always exist,
386 # because we can't get "matches" without calling that function.
387 display_pos = self.comp_state.display_pos
388 self.debug_f.write('DISPLAY POS in _PrintCandidates = %d\n' %
389 display_pos)
390
391 self.f.write('\n')
392
393 self.EraseLines() # Delete previous completions!
394 #log('_PrintCandidates %r', unused_subst, file=DEBUG_F)
395
396 # Figure out if the user hit TAB multiple times to show more matches.
397 # It's not correct to hash the line itself, because two different lines can
398 # have the same completions:
399 #
400 # ls <TAB>
401 # ls --<TAB>
402 #
403 # This is because there is a common prefix.
404 # So instead use the hash of all matches as the identity.
405
406 # This could be more accurate but I think it's good enough.
407 comp_id = hash(''.join(matches))
408 if comp_id in self.dupes:
409 # mycpp: rewrite of +=
410 self.dupes[comp_id] = self.dupes[comp_id] + 1
411 else:
412 self.dupes.clear() # delete the old ones
413 self.dupes[comp_id] = 1
414
415 max_lines = self.num_lines_cap * self.dupes[comp_id]
416
417 assert display_pos != -1
418 if display_pos == 0: # slight optimization for first word
419 to_display = matches
420 else:
421 to_display = [m[display_pos:] for m in matches]
422
423 # Calculate max length after stripping prefix.
424 lens = [len(m) for m in to_display]
425 max_match_len = max(lens)
426
427 # TODO: NiceDisplay should truncate when max_match_len > term_width?
428 # Also truncate when a single candidate is super long?
429
430 # Print and go back up. But we have to ERASE these before hitting enter!
431 if self.comp_state.descriptions is not None and len(
432 self.comp_state.descriptions) > 0: # exists and is NON EMPTY
433 num_lines = _PrintLong(to_display, max_match_len, term_width,
434 max_lines, self.comp_state.descriptions,
435 self.f)
436 else:
437 num_lines = _PrintPacked(to_display, max_match_len, term_width,
438 max_lines, self.f)
439
440 self._ReturnToPrompt(num_lines + 1)
441 self.num_lines_last_displayed = num_lines
442
443 self.c_count += 1
444
445 if mylib.PYTHON:
446
447 def PrintRequired(self, msg, *args):
448 # type: (str, *Any) -> None
449 """Print a message below the prompt, and then return to the
450 location on the prompt line."""
451 if args:
452 msg = msg % args
453
454 # This will mess up formatting
455 assert not msg.endswith('\n'), msg
456
457 self.f.write('\n')
458
459 self.EraseLines()
460 #log('PrintOptional %r', msg, file=DEBUG_F)
461
462 # Truncate to terminal width
463 max_len = self._GetTerminalWidth() - 2
464 if len(msg) > max_len:
465 msg = msg[:max_len - 5] + ' ... '
466
467 # NOTE: \n at end is REQUIRED. Otherwise we get drawing problems when on
468 # the last line.
469 fmt = ansi.BOLD + ansi.BLUE + '%' + str(
470 max_len) + 's' + ansi.RESET + '\n'
471 self.f.write(fmt % msg)
472
473 self._ReturnToPrompt(2)
474
475 self.num_lines_last_displayed = 1
476 self.m_count += 1
477
478 def PrintOptional(self, msg, *args):
479 # type: (str, *Any) -> None
480 self.PrintRequired(msg, *args)
481
482 def ShowPromptOnRight(self, rendered):
483 # type: (str) -> None
484 n = self._GetTerminalWidth() - 2 - len(rendered)
485 spaces = ' ' * n
486
487 # We avoid drawing problems if we print it on its own line:
488 # - inserting text doesn't push it to the right
489 # - you can't overwrite it
490 self.f.write(spaces + ansi.REVERSE + ' ' + rendered + ' ' +
491 ansi.RESET + '\r\n')
492
493 def EraseLines(self):
494 # type: () -> None
495 """Clear N lines one-by-one.
496
497 Assume the cursor is right below thep rompt:
498
499 ish$ echo hi
500 _ <-- HERE
501
502 That's the first line to erase out of N. After erasing them, return it
503 there.
504 """
505 if self.bold_line:
506 self.f.write(ansi.RESET) # if command is bold
507 self.f.flush()
508
509 n = self.num_lines_last_displayed
510
511 #log('EraseLines %d (c = %d, m = %d)', n, self.c_count, self.m_count,
512 # file=DEBUG_F)
513
514 if n == 0:
515 return
516
517 for i in xrange(n):
518 self.f.write('\x1b[2K') # 2K clears entire line (not 0K or 1K)
519 self.f.write('\x1b[1B') # go down one line
520
521 # Now go back up
522 self.f.write('\x1b[%dA' % n)
523 self.f.flush() # Without this, output will look messed up
524
525 def _GetTerminalWidth(self):
526 # type: () -> int
527 if self.signal_safe.PollSigWinch(): # is our value dirty?
528 try:
529 self.term_width = libc.get_terminal_width()
530 except (IOError, OSError):
531 # This shouldn't raise IOError because we did it at startup! Under
532 # rare circumstances stdin can change, e.g. if you do exec <&
533 # input.txt. So we have a fallback.
534 self.term_width = 80
535 return self.term_width
536
537
538def ExecutePrintCandidates(display, sub, matches, max_len):
539 # type: (_IDisplay, str, List[str], int) -> None
540 display.PrintCandidates(sub, matches, max_len)
541
542
543def InitReadline(
544 readline, # type: Optional[Readline]
545 hist_file, # type: Optional[str]
546 root_comp, # type: completion.RootCompleter
547 display, # type: _IDisplay
548 debug_f, # type: _DebugFile
549):
550 # type: (...) -> None
551 assert readline
552
553 if hist_file is not None:
554 try:
555 readline.read_history_file(hist_file)
556 except (IOError, OSError):
557 pass
558
559 readline.parse_and_bind('tab: complete')
560
561 for cmd in display.ExtraReadlineCommands():
562 readline.parse_and_bind(cmd)
563
564 # How does this map to C?
565 # https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#SEC45
566
567 complete_cb = completion.ReadlineCallback(readline, root_comp, debug_f)
568 readline.set_completer(complete_cb)
569
570 # http://web.mit.edu/gnu/doc/html/rlman_2.html#SEC39
571 # "The basic list of characters that signal a break between words for the
572 # completer routine. The default value of this variable is the characters
573 # which break words for completion in Bash, i.e., " \t\n\"\\'`@$><=;|&{(""
574
575 # This determines the boundaries you get back from get_begidx() and
576 # get_endidx() at completion time!
577 # We could be more conservative and set it to ' ', but then cases like
578 # 'ls|w<TAB>' would try to complete the whole thing, instead of just 'w'.
579 #
580 # Note that this should not affect the OSH completion algorithm. It only
581 # affects what we pass back to readline and what readline displays to the
582 # user!
583
584 # No delimiters because readline isn't smart enough to tokenize shell!
585 readline.set_completer_delims('')
586
587 readline.set_completion_display_matches_hook(display)