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

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