menus.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. from __future__ import annotations
  2. import math
  3. from itertools import zip_longest
  4. from typing import TYPE_CHECKING, Callable, Iterable, Sequence, TypeVar, cast
  5. from weakref import WeakKeyDictionary
  6. from prompt_toolkit.application.current import get_app
  7. from prompt_toolkit.buffer import CompletionState
  8. from prompt_toolkit.completion import Completion
  9. from prompt_toolkit.data_structures import Point
  10. from prompt_toolkit.filters import (
  11. Condition,
  12. FilterOrBool,
  13. has_completions,
  14. is_done,
  15. to_filter,
  16. )
  17. from prompt_toolkit.formatted_text import (
  18. StyleAndTextTuples,
  19. fragment_list_width,
  20. to_formatted_text,
  21. )
  22. from prompt_toolkit.key_binding.key_processor import KeyPressEvent
  23. from prompt_toolkit.layout.utils import explode_text_fragments
  24. from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
  25. from prompt_toolkit.utils import get_cwidth
  26. from .containers import ConditionalContainer, HSplit, ScrollOffsets, Window
  27. from .controls import GetLinePrefixCallable, UIContent, UIControl
  28. from .dimension import Dimension
  29. from .margins import ScrollbarMargin
  30. if TYPE_CHECKING:
  31. from prompt_toolkit.key_binding.key_bindings import (
  32. KeyBindings,
  33. NotImplementedOrNone,
  34. )
  35. __all__ = [
  36. "CompletionsMenu",
  37. "MultiColumnCompletionsMenu",
  38. ]
  39. E = KeyPressEvent
  40. class CompletionsMenuControl(UIControl):
  41. """
  42. Helper for drawing the complete menu to the screen.
  43. :param scroll_offset: Number (integer) representing the preferred amount of
  44. completions to be displayed before and after the current one. When this
  45. is a very high number, the current completion will be shown in the
  46. middle most of the time.
  47. """
  48. # Preferred minimum size of the menu control.
  49. # The CompletionsMenu class defines a width of 8, and there is a scrollbar
  50. # of 1.)
  51. MIN_WIDTH = 7
  52. def has_focus(self) -> bool:
  53. return False
  54. def preferred_width(self, max_available_width: int) -> int | None:
  55. complete_state = get_app().current_buffer.complete_state
  56. if complete_state:
  57. menu_width = self._get_menu_width(500, complete_state)
  58. menu_meta_width = self._get_menu_meta_width(500, complete_state)
  59. return menu_width + menu_meta_width
  60. else:
  61. return 0
  62. def preferred_height(
  63. self,
  64. width: int,
  65. max_available_height: int,
  66. wrap_lines: bool,
  67. get_line_prefix: GetLinePrefixCallable | None,
  68. ) -> int | None:
  69. complete_state = get_app().current_buffer.complete_state
  70. if complete_state:
  71. return len(complete_state.completions)
  72. else:
  73. return 0
  74. def create_content(self, width: int, height: int) -> UIContent:
  75. """
  76. Create a UIContent object for this control.
  77. """
  78. complete_state = get_app().current_buffer.complete_state
  79. if complete_state:
  80. completions = complete_state.completions
  81. index = complete_state.complete_index # Can be None!
  82. # Calculate width of completions menu.
  83. menu_width = self._get_menu_width(width, complete_state)
  84. menu_meta_width = self._get_menu_meta_width(
  85. width - menu_width, complete_state
  86. )
  87. show_meta = self._show_meta(complete_state)
  88. def get_line(i: int) -> StyleAndTextTuples:
  89. c = completions[i]
  90. is_current_completion = i == index
  91. result = _get_menu_item_fragments(
  92. c, is_current_completion, menu_width, space_after=True
  93. )
  94. if show_meta:
  95. result += self._get_menu_item_meta_fragments(
  96. c, is_current_completion, menu_meta_width
  97. )
  98. return result
  99. return UIContent(
  100. get_line=get_line,
  101. cursor_position=Point(x=0, y=index or 0),
  102. line_count=len(completions),
  103. )
  104. return UIContent()
  105. def _show_meta(self, complete_state: CompletionState) -> bool:
  106. """
  107. Return ``True`` if we need to show a column with meta information.
  108. """
  109. return any(c.display_meta_text for c in complete_state.completions)
  110. def _get_menu_width(self, max_width: int, complete_state: CompletionState) -> int:
  111. """
  112. Return the width of the main column.
  113. """
  114. return min(
  115. max_width,
  116. max(
  117. self.MIN_WIDTH,
  118. max(get_cwidth(c.display_text) for c in complete_state.completions) + 2,
  119. ),
  120. )
  121. def _get_menu_meta_width(
  122. self, max_width: int, complete_state: CompletionState
  123. ) -> int:
  124. """
  125. Return the width of the meta column.
  126. """
  127. def meta_width(completion: Completion) -> int:
  128. return get_cwidth(completion.display_meta_text)
  129. if self._show_meta(complete_state):
  130. # If the amount of completions is over 200, compute the width based
  131. # on the first 200 completions, otherwise this can be very slow.
  132. completions = complete_state.completions
  133. if len(completions) > 200:
  134. completions = completions[:200]
  135. return min(max_width, max(meta_width(c) for c in completions) + 2)
  136. else:
  137. return 0
  138. def _get_menu_item_meta_fragments(
  139. self, completion: Completion, is_current_completion: bool, width: int
  140. ) -> StyleAndTextTuples:
  141. if is_current_completion:
  142. style_str = "class:completion-menu.meta.completion.current"
  143. else:
  144. style_str = "class:completion-menu.meta.completion"
  145. text, tw = _trim_formatted_text(completion.display_meta, width - 2)
  146. padding = " " * (width - 1 - tw)
  147. return to_formatted_text(
  148. cast(StyleAndTextTuples, []) + [("", " ")] + text + [("", padding)],
  149. style=style_str,
  150. )
  151. def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
  152. """
  153. Handle mouse events: clicking and scrolling.
  154. """
  155. b = get_app().current_buffer
  156. if mouse_event.event_type == MouseEventType.MOUSE_UP:
  157. # Select completion.
  158. b.go_to_completion(mouse_event.position.y)
  159. b.complete_state = None
  160. elif mouse_event.event_type == MouseEventType.SCROLL_DOWN:
  161. # Scroll up.
  162. b.complete_next(count=3, disable_wrap_around=True)
  163. elif mouse_event.event_type == MouseEventType.SCROLL_UP:
  164. # Scroll down.
  165. b.complete_previous(count=3, disable_wrap_around=True)
  166. return None
  167. def _get_menu_item_fragments(
  168. completion: Completion,
  169. is_current_completion: bool,
  170. width: int,
  171. space_after: bool = False,
  172. ) -> StyleAndTextTuples:
  173. """
  174. Get the style/text tuples for a menu item, styled and trimmed to the given
  175. width.
  176. """
  177. if is_current_completion:
  178. style_str = "class:completion-menu.completion.current {} {}".format(
  179. completion.style,
  180. completion.selected_style,
  181. )
  182. else:
  183. style_str = "class:completion-menu.completion " + completion.style
  184. text, tw = _trim_formatted_text(
  185. completion.display, (width - 2 if space_after else width - 1)
  186. )
  187. padding = " " * (width - 1 - tw)
  188. return to_formatted_text(
  189. cast(StyleAndTextTuples, []) + [("", " ")] + text + [("", padding)],
  190. style=style_str,
  191. )
  192. def _trim_formatted_text(
  193. formatted_text: StyleAndTextTuples, max_width: int
  194. ) -> tuple[StyleAndTextTuples, int]:
  195. """
  196. Trim the text to `max_width`, append dots when the text is too long.
  197. Returns (text, width) tuple.
  198. """
  199. width = fragment_list_width(formatted_text)
  200. # When the text is too wide, trim it.
  201. if width > max_width:
  202. result = [] # Text fragments.
  203. remaining_width = max_width - 3
  204. for style_and_ch in explode_text_fragments(formatted_text):
  205. ch_width = get_cwidth(style_and_ch[1])
  206. if ch_width <= remaining_width:
  207. result.append(style_and_ch)
  208. remaining_width -= ch_width
  209. else:
  210. break
  211. result.append(("", "..."))
  212. return result, max_width - remaining_width
  213. else:
  214. return formatted_text, width
  215. class CompletionsMenu(ConditionalContainer):
  216. # NOTE: We use a pretty big z_index by default. Menus are supposed to be
  217. # above anything else. We also want to make sure that the content is
  218. # visible at the point where we draw this menu.
  219. def __init__(
  220. self,
  221. max_height: int | None = None,
  222. scroll_offset: int | Callable[[], int] = 0,
  223. extra_filter: FilterOrBool = True,
  224. display_arrows: FilterOrBool = False,
  225. z_index: int = 10**8,
  226. ) -> None:
  227. extra_filter = to_filter(extra_filter)
  228. display_arrows = to_filter(display_arrows)
  229. super().__init__(
  230. content=Window(
  231. content=CompletionsMenuControl(),
  232. width=Dimension(min=8),
  233. height=Dimension(min=1, max=max_height),
  234. scroll_offsets=ScrollOffsets(top=scroll_offset, bottom=scroll_offset),
  235. right_margins=[ScrollbarMargin(display_arrows=display_arrows)],
  236. dont_extend_width=True,
  237. style="class:completion-menu",
  238. z_index=z_index,
  239. ),
  240. # Show when there are completions but not at the point we are
  241. # returning the input.
  242. filter=extra_filter & has_completions & ~is_done,
  243. )
  244. class MultiColumnCompletionMenuControl(UIControl):
  245. """
  246. Completion menu that displays all the completions in several columns.
  247. When there are more completions than space for them to be displayed, an
  248. arrow is shown on the left or right side.
  249. `min_rows` indicates how many rows will be available in any possible case.
  250. When this is larger than one, it will try to use less columns and more
  251. rows until this value is reached.
  252. Be careful passing in a too big value, if less than the given amount of
  253. rows are available, more columns would have been required, but
  254. `preferred_width` doesn't know about that and reports a too small value.
  255. This results in less completions displayed and additional scrolling.
  256. (It's a limitation of how the layout engine currently works: first the
  257. widths are calculated, then the heights.)
  258. :param suggested_max_column_width: The suggested max width of a column.
  259. The column can still be bigger than this, but if there is place for two
  260. columns of this width, we will display two columns. This to avoid that
  261. if there is one very wide completion, that it doesn't significantly
  262. reduce the amount of columns.
  263. """
  264. _required_margin = 3 # One extra padding on the right + space for arrows.
  265. def __init__(self, min_rows: int = 3, suggested_max_column_width: int = 30) -> None:
  266. assert min_rows >= 1
  267. self.min_rows = min_rows
  268. self.suggested_max_column_width = suggested_max_column_width
  269. self.scroll = 0
  270. # Cache for column width computations. This computation is not cheap,
  271. # so we don't want to do it over and over again while the user
  272. # navigates through the completions.
  273. # (map `completion_state` to `(completion_count, width)`. We remember
  274. # the count, because a completer can add new completions to the
  275. # `CompletionState` while loading.)
  276. self._column_width_for_completion_state: WeakKeyDictionary[
  277. CompletionState, tuple[int, int]
  278. ] = WeakKeyDictionary()
  279. # Info of last rendering.
  280. self._rendered_rows = 0
  281. self._rendered_columns = 0
  282. self._total_columns = 0
  283. self._render_pos_to_completion: dict[tuple[int, int], Completion] = {}
  284. self._render_left_arrow = False
  285. self._render_right_arrow = False
  286. self._render_width = 0
  287. def reset(self) -> None:
  288. self.scroll = 0
  289. def has_focus(self) -> bool:
  290. return False
  291. def preferred_width(self, max_available_width: int) -> int | None:
  292. """
  293. Preferred width: prefer to use at least min_rows, but otherwise as much
  294. as possible horizontally.
  295. """
  296. complete_state = get_app().current_buffer.complete_state
  297. if complete_state is None:
  298. return 0
  299. column_width = self._get_column_width(complete_state)
  300. result = int(
  301. column_width
  302. * math.ceil(len(complete_state.completions) / float(self.min_rows))
  303. )
  304. # When the desired width is still more than the maximum available,
  305. # reduce by removing columns until we are less than the available
  306. # width.
  307. while (
  308. result > column_width
  309. and result > max_available_width - self._required_margin
  310. ):
  311. result -= column_width
  312. return result + self._required_margin
  313. def preferred_height(
  314. self,
  315. width: int,
  316. max_available_height: int,
  317. wrap_lines: bool,
  318. get_line_prefix: GetLinePrefixCallable | None,
  319. ) -> int | None:
  320. """
  321. Preferred height: as much as needed in order to display all the completions.
  322. """
  323. complete_state = get_app().current_buffer.complete_state
  324. if complete_state is None:
  325. return 0
  326. column_width = self._get_column_width(complete_state)
  327. column_count = max(1, (width - self._required_margin) // column_width)
  328. return int(math.ceil(len(complete_state.completions) / float(column_count)))
  329. def create_content(self, width: int, height: int) -> UIContent:
  330. """
  331. Create a UIContent object for this menu.
  332. """
  333. complete_state = get_app().current_buffer.complete_state
  334. if complete_state is None:
  335. return UIContent()
  336. column_width = self._get_column_width(complete_state)
  337. self._render_pos_to_completion = {}
  338. _T = TypeVar("_T")
  339. def grouper(
  340. n: int, iterable: Iterable[_T], fillvalue: _T | None = None
  341. ) -> Iterable[Sequence[_T | None]]:
  342. "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
  343. args = [iter(iterable)] * n
  344. return zip_longest(fillvalue=fillvalue, *args)
  345. def is_current_completion(completion: Completion) -> bool:
  346. "Returns True when this completion is the currently selected one."
  347. return (
  348. complete_state is not None
  349. and complete_state.complete_index is not None
  350. and c == complete_state.current_completion
  351. )
  352. # Space required outside of the regular columns, for displaying the
  353. # left and right arrow.
  354. HORIZONTAL_MARGIN_REQUIRED = 3
  355. # There should be at least one column, but it cannot be wider than
  356. # the available width.
  357. column_width = min(width - HORIZONTAL_MARGIN_REQUIRED, column_width)
  358. # However, when the columns tend to be very wide, because there are
  359. # some very wide entries, shrink it anyway.
  360. if column_width > self.suggested_max_column_width:
  361. # `column_width` can still be bigger that `suggested_max_column_width`,
  362. # but if there is place for two columns, we divide by two.
  363. column_width //= column_width // self.suggested_max_column_width
  364. visible_columns = max(1, (width - self._required_margin) // column_width)
  365. columns_ = list(grouper(height, complete_state.completions))
  366. rows_ = list(zip(*columns_))
  367. # Make sure the current completion is always visible: update scroll offset.
  368. selected_column = (complete_state.complete_index or 0) // height
  369. self.scroll = min(
  370. selected_column, max(self.scroll, selected_column - visible_columns + 1)
  371. )
  372. render_left_arrow = self.scroll > 0
  373. render_right_arrow = self.scroll < len(rows_[0]) - visible_columns
  374. # Write completions to screen.
  375. fragments_for_line = []
  376. for row_index, row in enumerate(rows_):
  377. fragments: StyleAndTextTuples = []
  378. middle_row = row_index == len(rows_) // 2
  379. # Draw left arrow if we have hidden completions on the left.
  380. if render_left_arrow:
  381. fragments.append(("class:scrollbar", "<" if middle_row else " "))
  382. elif render_right_arrow:
  383. # Reserve one column empty space. (If there is a right
  384. # arrow right now, there can be a left arrow as well.)
  385. fragments.append(("", " "))
  386. # Draw row content.
  387. for column_index, c in enumerate(row[self.scroll :][:visible_columns]):
  388. if c is not None:
  389. fragments += _get_menu_item_fragments(
  390. c, is_current_completion(c), column_width, space_after=False
  391. )
  392. # Remember render position for mouse click handler.
  393. for x in range(column_width):
  394. self._render_pos_to_completion[
  395. (column_index * column_width + x, row_index)
  396. ] = c
  397. else:
  398. fragments.append(("class:completion", " " * column_width))
  399. # Draw trailing padding for this row.
  400. # (_get_menu_item_fragments only returns padding on the left.)
  401. if render_left_arrow or render_right_arrow:
  402. fragments.append(("class:completion", " "))
  403. # Draw right arrow if we have hidden completions on the right.
  404. if render_right_arrow:
  405. fragments.append(("class:scrollbar", ">" if middle_row else " "))
  406. elif render_left_arrow:
  407. fragments.append(("class:completion", " "))
  408. # Add line.
  409. fragments_for_line.append(
  410. to_formatted_text(fragments, style="class:completion-menu")
  411. )
  412. self._rendered_rows = height
  413. self._rendered_columns = visible_columns
  414. self._total_columns = len(columns_)
  415. self._render_left_arrow = render_left_arrow
  416. self._render_right_arrow = render_right_arrow
  417. self._render_width = (
  418. column_width * visible_columns + render_left_arrow + render_right_arrow + 1
  419. )
  420. def get_line(i: int) -> StyleAndTextTuples:
  421. return fragments_for_line[i]
  422. return UIContent(get_line=get_line, line_count=len(rows_))
  423. def _get_column_width(self, completion_state: CompletionState) -> int:
  424. """
  425. Return the width of each column.
  426. """
  427. try:
  428. count, width = self._column_width_for_completion_state[completion_state]
  429. if count != len(completion_state.completions):
  430. # Number of completions changed, recompute.
  431. raise KeyError
  432. return width
  433. except KeyError:
  434. result = (
  435. max(get_cwidth(c.display_text) for c in completion_state.completions)
  436. + 1
  437. )
  438. self._column_width_for_completion_state[completion_state] = (
  439. len(completion_state.completions),
  440. result,
  441. )
  442. return result
  443. def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
  444. """
  445. Handle scroll and click events.
  446. """
  447. b = get_app().current_buffer
  448. def scroll_left() -> None:
  449. b.complete_previous(count=self._rendered_rows, disable_wrap_around=True)
  450. self.scroll = max(0, self.scroll - 1)
  451. def scroll_right() -> None:
  452. b.complete_next(count=self._rendered_rows, disable_wrap_around=True)
  453. self.scroll = min(
  454. self._total_columns - self._rendered_columns, self.scroll + 1
  455. )
  456. if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
  457. scroll_right()
  458. elif mouse_event.event_type == MouseEventType.SCROLL_UP:
  459. scroll_left()
  460. elif mouse_event.event_type == MouseEventType.MOUSE_UP:
  461. x = mouse_event.position.x
  462. y = mouse_event.position.y
  463. # Mouse click on left arrow.
  464. if x == 0:
  465. if self._render_left_arrow:
  466. scroll_left()
  467. # Mouse click on right arrow.
  468. elif x == self._render_width - 1:
  469. if self._render_right_arrow:
  470. scroll_right()
  471. # Mouse click on completion.
  472. else:
  473. completion = self._render_pos_to_completion.get((x, y))
  474. if completion:
  475. b.apply_completion(completion)
  476. return None
  477. def get_key_bindings(self) -> KeyBindings:
  478. """
  479. Expose key bindings that handle the left/right arrow keys when the menu
  480. is displayed.
  481. """
  482. from prompt_toolkit.key_binding.key_bindings import KeyBindings
  483. kb = KeyBindings()
  484. @Condition
  485. def filter() -> bool:
  486. "Only handle key bindings if this menu is visible."
  487. app = get_app()
  488. complete_state = app.current_buffer.complete_state
  489. # There need to be completions, and one needs to be selected.
  490. if complete_state is None or complete_state.complete_index is None:
  491. return False
  492. # This menu needs to be visible.
  493. return any(window.content == self for window in app.layout.visible_windows)
  494. def move(right: bool = False) -> None:
  495. buff = get_app().current_buffer
  496. complete_state = buff.complete_state
  497. if complete_state is not None and complete_state.complete_index is not None:
  498. # Calculate new complete index.
  499. new_index = complete_state.complete_index
  500. if right:
  501. new_index += self._rendered_rows
  502. else:
  503. new_index -= self._rendered_rows
  504. if 0 <= new_index < len(complete_state.completions):
  505. buff.go_to_completion(new_index)
  506. # NOTE: the is_global is required because the completion menu will
  507. # never be focussed.
  508. @kb.add("left", is_global=True, filter=filter)
  509. def _left(event: E) -> None:
  510. move()
  511. @kb.add("right", is_global=True, filter=filter)
  512. def _right(event: E) -> None:
  513. move(True)
  514. return kb
  515. class MultiColumnCompletionsMenu(HSplit):
  516. """
  517. Container that displays the completions in several columns.
  518. When `show_meta` (a :class:`~prompt_toolkit.filters.Filter`) evaluates
  519. to True, it shows the meta information at the bottom.
  520. """
  521. def __init__(
  522. self,
  523. min_rows: int = 3,
  524. suggested_max_column_width: int = 30,
  525. show_meta: FilterOrBool = True,
  526. extra_filter: FilterOrBool = True,
  527. z_index: int = 10**8,
  528. ) -> None:
  529. show_meta = to_filter(show_meta)
  530. extra_filter = to_filter(extra_filter)
  531. # Display filter: show when there are completions but not at the point
  532. # we are returning the input.
  533. full_filter = extra_filter & has_completions & ~is_done
  534. @Condition
  535. def any_completion_has_meta() -> bool:
  536. complete_state = get_app().current_buffer.complete_state
  537. return complete_state is not None and any(
  538. c.display_meta for c in complete_state.completions
  539. )
  540. # Create child windows.
  541. # NOTE: We don't set style='class:completion-menu' to the
  542. # `MultiColumnCompletionMenuControl`, because this is used in a
  543. # Float that is made transparent, and the size of the control
  544. # doesn't always correspond exactly with the size of the
  545. # generated content.
  546. completions_window = ConditionalContainer(
  547. content=Window(
  548. content=MultiColumnCompletionMenuControl(
  549. min_rows=min_rows,
  550. suggested_max_column_width=suggested_max_column_width,
  551. ),
  552. width=Dimension(min=8),
  553. height=Dimension(min=1),
  554. ),
  555. filter=full_filter,
  556. )
  557. meta_window = ConditionalContainer(
  558. content=Window(content=_SelectedCompletionMetaControl()),
  559. filter=full_filter & show_meta & any_completion_has_meta,
  560. )
  561. # Initialize split.
  562. super().__init__([completions_window, meta_window], z_index=z_index)
  563. class _SelectedCompletionMetaControl(UIControl):
  564. """
  565. Control that shows the meta information of the selected completion.
  566. """
  567. def preferred_width(self, max_available_width: int) -> int | None:
  568. """
  569. Report the width of the longest meta text as the preferred width of this control.
  570. It could be that we use less width, but this way, we're sure that the
  571. layout doesn't change when we select another completion (E.g. that
  572. completions are suddenly shown in more or fewer columns.)
  573. """
  574. app = get_app()
  575. if app.current_buffer.complete_state:
  576. state = app.current_buffer.complete_state
  577. if len(state.completions) >= 30:
  578. # When there are many completions, calling `get_cwidth` for
  579. # every `display_meta_text` is too expensive. In this case,
  580. # just return the max available width. There will be enough
  581. # columns anyway so that the whole screen is filled with
  582. # completions and `create_content` will then take up as much
  583. # space as needed.
  584. return max_available_width
  585. return 2 + max(
  586. get_cwidth(c.display_meta_text) for c in state.completions[:100]
  587. )
  588. else:
  589. return 0
  590. def preferred_height(
  591. self,
  592. width: int,
  593. max_available_height: int,
  594. wrap_lines: bool,
  595. get_line_prefix: GetLinePrefixCallable | None,
  596. ) -> int | None:
  597. return 1
  598. def create_content(self, width: int, height: int) -> UIContent:
  599. fragments = self._get_text_fragments()
  600. def get_line(i: int) -> StyleAndTextTuples:
  601. return fragments
  602. return UIContent(get_line=get_line, line_count=1 if fragments else 0)
  603. def _get_text_fragments(self) -> StyleAndTextTuples:
  604. style = "class:completion-menu.multi-column-meta"
  605. state = get_app().current_buffer.complete_state
  606. if (
  607. state
  608. and state.current_completion
  609. and state.current_completion.display_meta_text
  610. ):
  611. return to_formatted_text(
  612. cast(StyleAndTextTuples, [("", " ")])
  613. + state.current_completion.display_meta
  614. + [("", " ")],
  615. style=style,
  616. )
  617. return []