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

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