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

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