controls.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. """
  2. User interface Controls for the layout.
  3. """
  4. from __future__ import annotations
  5. import time
  6. from abc import ABCMeta, abstractmethod
  7. from typing import TYPE_CHECKING, Callable, Hashable, Iterable, NamedTuple
  8. from prompt_toolkit.application.current import get_app
  9. from prompt_toolkit.buffer import Buffer
  10. from prompt_toolkit.cache import SimpleCache
  11. from prompt_toolkit.data_structures import Point
  12. from prompt_toolkit.document import Document
  13. from prompt_toolkit.filters import FilterOrBool, to_filter
  14. from prompt_toolkit.formatted_text import (
  15. AnyFormattedText,
  16. StyleAndTextTuples,
  17. to_formatted_text,
  18. )
  19. from prompt_toolkit.formatted_text.utils import (
  20. fragment_list_to_text,
  21. fragment_list_width,
  22. split_lines,
  23. )
  24. from prompt_toolkit.lexers import Lexer, SimpleLexer
  25. from prompt_toolkit.mouse_events import MouseButton, MouseEvent, MouseEventType
  26. from prompt_toolkit.search import SearchState
  27. from prompt_toolkit.selection import SelectionType
  28. from prompt_toolkit.utils import get_cwidth
  29. from .processors import (
  30. DisplayMultipleCursors,
  31. HighlightIncrementalSearchProcessor,
  32. HighlightSearchProcessor,
  33. HighlightSelectionProcessor,
  34. Processor,
  35. TransformationInput,
  36. merge_processors,
  37. )
  38. if TYPE_CHECKING:
  39. from prompt_toolkit.key_binding.key_bindings import (
  40. KeyBindingsBase,
  41. NotImplementedOrNone,
  42. )
  43. from prompt_toolkit.utils import Event
  44. __all__ = [
  45. "BufferControl",
  46. "SearchBufferControl",
  47. "DummyControl",
  48. "FormattedTextControl",
  49. "UIControl",
  50. "UIContent",
  51. ]
  52. GetLinePrefixCallable = Callable[[int, int], AnyFormattedText]
  53. class UIControl(metaclass=ABCMeta):
  54. """
  55. Base class for all user interface controls.
  56. """
  57. def reset(self) -> None:
  58. # Default reset. (Doesn't have to be implemented.)
  59. pass
  60. def preferred_width(self, max_available_width: int) -> int | None:
  61. return None
  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. return None
  70. def is_focusable(self) -> bool:
  71. """
  72. Tell whether this user control is focusable.
  73. """
  74. return False
  75. @abstractmethod
  76. def create_content(self, width: int, height: int) -> UIContent:
  77. """
  78. Generate the content for this user control.
  79. Returns a :class:`.UIContent` instance.
  80. """
  81. def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
  82. """
  83. Handle mouse events.
  84. When `NotImplemented` is returned, it means that the given event is not
  85. handled by the `UIControl` itself. The `Window` or key bindings can
  86. decide to handle this event as scrolling or changing focus.
  87. :param mouse_event: `MouseEvent` instance.
  88. """
  89. return NotImplemented
  90. def move_cursor_down(self) -> None:
  91. """
  92. Request to move the cursor down.
  93. This happens when scrolling down and the cursor is completely at the
  94. top.
  95. """
  96. def move_cursor_up(self) -> None:
  97. """
  98. Request to move the cursor up.
  99. """
  100. def get_key_bindings(self) -> KeyBindingsBase | None:
  101. """
  102. The key bindings that are specific for this user control.
  103. Return a :class:`.KeyBindings` object if some key bindings are
  104. specified, or `None` otherwise.
  105. """
  106. def get_invalidate_events(self) -> Iterable[Event[object]]:
  107. """
  108. Return a list of `Event` objects. This can be a generator.
  109. (The application collects all these events, in order to bind redraw
  110. handlers to these events.)
  111. """
  112. return []
  113. class UIContent:
  114. """
  115. Content generated by a user control. This content consists of a list of
  116. lines.
  117. :param get_line: Callable that takes a line number and returns the current
  118. line. This is a list of (style_str, text) tuples.
  119. :param line_count: The number of lines.
  120. :param cursor_position: a :class:`.Point` for the cursor position.
  121. :param menu_position: a :class:`.Point` for the menu position.
  122. :param show_cursor: Make the cursor visible.
  123. """
  124. def __init__(
  125. self,
  126. get_line: Callable[[int], StyleAndTextTuples] = (lambda i: []),
  127. line_count: int = 0,
  128. cursor_position: Point | None = None,
  129. menu_position: Point | None = None,
  130. show_cursor: bool = True,
  131. ):
  132. self.get_line = get_line
  133. self.line_count = line_count
  134. self.cursor_position = cursor_position or Point(x=0, y=0)
  135. self.menu_position = menu_position
  136. self.show_cursor = show_cursor
  137. # Cache for line heights. Maps cache key -> height
  138. self._line_heights_cache: dict[Hashable, int] = {}
  139. def __getitem__(self, lineno: int) -> StyleAndTextTuples:
  140. "Make it iterable (iterate line by line)."
  141. if lineno < self.line_count:
  142. return self.get_line(lineno)
  143. else:
  144. raise IndexError
  145. def get_height_for_line(
  146. self,
  147. lineno: int,
  148. width: int,
  149. get_line_prefix: GetLinePrefixCallable | None,
  150. slice_stop: int | None = None,
  151. ) -> int:
  152. """
  153. Return the height that a given line would need if it is rendered in a
  154. space with the given width (using line wrapping).
  155. :param get_line_prefix: None or a `Window.get_line_prefix` callable
  156. that returns the prefix to be inserted before this line.
  157. :param slice_stop: Wrap only "line[:slice_stop]" and return that
  158. partial result. This is needed for scrolling the window correctly
  159. when line wrapping.
  160. :returns: The computed height.
  161. """
  162. # Instead of using `get_line_prefix` as key, we use render_counter
  163. # instead. This is more reliable, because this function could still be
  164. # the same, while the content would change over time.
  165. key = get_app().render_counter, lineno, width, slice_stop
  166. try:
  167. return self._line_heights_cache[key]
  168. except KeyError:
  169. if width == 0:
  170. height = 10**8
  171. else:
  172. # Calculate line width first.
  173. line = fragment_list_to_text(self.get_line(lineno))[:slice_stop]
  174. text_width = get_cwidth(line)
  175. if get_line_prefix:
  176. # Add prefix width.
  177. text_width += fragment_list_width(
  178. to_formatted_text(get_line_prefix(lineno, 0))
  179. )
  180. # Slower path: compute path when there's a line prefix.
  181. height = 1
  182. # Keep wrapping as long as the line doesn't fit.
  183. # Keep adding new prefixes for every wrapped line.
  184. while text_width > width:
  185. height += 1
  186. text_width -= width
  187. fragments2 = to_formatted_text(
  188. get_line_prefix(lineno, height - 1)
  189. )
  190. prefix_width = get_cwidth(fragment_list_to_text(fragments2))
  191. if prefix_width >= width: # Prefix doesn't fit.
  192. height = 10**8
  193. break
  194. text_width += prefix_width
  195. else:
  196. # Fast path: compute height when there's no line prefix.
  197. try:
  198. quotient, remainder = divmod(text_width, width)
  199. except ZeroDivisionError:
  200. height = 10**8
  201. else:
  202. if remainder:
  203. quotient += 1 # Like math.ceil.
  204. height = max(1, quotient)
  205. # Cache and return
  206. self._line_heights_cache[key] = height
  207. return height
  208. class FormattedTextControl(UIControl):
  209. """
  210. Control that displays formatted text. This can be either plain text, an
  211. :class:`~prompt_toolkit.formatted_text.HTML` object an
  212. :class:`~prompt_toolkit.formatted_text.ANSI` object, a list of ``(style_str,
  213. text)`` tuples or a callable that takes no argument and returns one of
  214. those, depending on how you prefer to do the formatting. See
  215. ``prompt_toolkit.layout.formatted_text`` for more information.
  216. (It's mostly optimized for rather small widgets, like toolbars, menus, etc...)
  217. When this UI control has the focus, the cursor will be shown in the upper
  218. left corner of this control by default. There are two ways for specifying
  219. the cursor position:
  220. - Pass a `get_cursor_position` function which returns a `Point` instance
  221. with the current cursor position.
  222. - If the (formatted) text is passed as a list of ``(style, text)`` tuples
  223. and there is one that looks like ``('[SetCursorPosition]', '')``, then
  224. this will specify the cursor position.
  225. Mouse support:
  226. The list of fragments can also contain tuples of three items, looking like:
  227. (style_str, text, handler). When mouse support is enabled and the user
  228. clicks on this fragment, then the given handler is called. That handler
  229. should accept two inputs: (Application, MouseEvent) and it should
  230. either handle the event or return `NotImplemented` in case we want the
  231. containing Window to handle this event.
  232. :param focusable: `bool` or :class:`.Filter`: Tell whether this control is
  233. focusable.
  234. :param text: Text or formatted text to be displayed.
  235. :param style: Style string applied to the content. (If you want to style
  236. the whole :class:`~prompt_toolkit.layout.Window`, pass the style to the
  237. :class:`~prompt_toolkit.layout.Window` instead.)
  238. :param key_bindings: a :class:`.KeyBindings` object.
  239. :param get_cursor_position: A callable that returns the cursor position as
  240. a `Point` instance.
  241. """
  242. def __init__(
  243. self,
  244. text: AnyFormattedText = "",
  245. style: str = "",
  246. focusable: FilterOrBool = False,
  247. key_bindings: KeyBindingsBase | None = None,
  248. show_cursor: bool = True,
  249. modal: bool = False,
  250. get_cursor_position: Callable[[], Point | None] | None = None,
  251. ) -> None:
  252. self.text = text # No type check on 'text'. This is done dynamically.
  253. self.style = style
  254. self.focusable = to_filter(focusable)
  255. # Key bindings.
  256. self.key_bindings = key_bindings
  257. self.show_cursor = show_cursor
  258. self.modal = modal
  259. self.get_cursor_position = get_cursor_position
  260. #: Cache for the content.
  261. self._content_cache: SimpleCache[Hashable, UIContent] = SimpleCache(maxsize=18)
  262. self._fragment_cache: SimpleCache[int, StyleAndTextTuples] = SimpleCache(
  263. maxsize=1
  264. )
  265. # Only cache one fragment list. We don't need the previous item.
  266. # Render info for the mouse support.
  267. self._fragments: StyleAndTextTuples | None = None
  268. def reset(self) -> None:
  269. self._fragments = None
  270. def is_focusable(self) -> bool:
  271. return self.focusable()
  272. def __repr__(self) -> str:
  273. return f"{self.__class__.__name__}({self.text!r})"
  274. def _get_formatted_text_cached(self) -> StyleAndTextTuples:
  275. """
  276. Get fragments, but only retrieve fragments once during one render run.
  277. (This function is called several times during one rendering, because
  278. we also need those for calculating the dimensions.)
  279. """
  280. return self._fragment_cache.get(
  281. get_app().render_counter, lambda: to_formatted_text(self.text, self.style)
  282. )
  283. def preferred_width(self, max_available_width: int) -> int:
  284. """
  285. Return the preferred width for this control.
  286. That is the width of the longest line.
  287. """
  288. text = fragment_list_to_text(self._get_formatted_text_cached())
  289. line_lengths = [get_cwidth(l) for l in text.split("\n")]
  290. return max(line_lengths)
  291. def preferred_height(
  292. self,
  293. width: int,
  294. max_available_height: int,
  295. wrap_lines: bool,
  296. get_line_prefix: GetLinePrefixCallable | None,
  297. ) -> int | None:
  298. """
  299. Return the preferred height for this control.
  300. """
  301. content = self.create_content(width, None)
  302. if wrap_lines:
  303. height = 0
  304. for i in range(content.line_count):
  305. height += content.get_height_for_line(i, width, get_line_prefix)
  306. if height >= max_available_height:
  307. return max_available_height
  308. return height
  309. else:
  310. return content.line_count
  311. def create_content(self, width: int, height: int | None) -> UIContent:
  312. # Get fragments
  313. fragments_with_mouse_handlers = self._get_formatted_text_cached()
  314. fragment_lines_with_mouse_handlers = list(
  315. split_lines(fragments_with_mouse_handlers)
  316. )
  317. # Strip mouse handlers from fragments.
  318. fragment_lines: list[StyleAndTextTuples] = [
  319. [(item[0], item[1]) for item in line]
  320. for line in fragment_lines_with_mouse_handlers
  321. ]
  322. # Keep track of the fragments with mouse handler, for later use in
  323. # `mouse_handler`.
  324. self._fragments = fragments_with_mouse_handlers
  325. # If there is a `[SetCursorPosition]` in the fragment list, set the
  326. # cursor position here.
  327. def get_cursor_position(
  328. fragment: str = "[SetCursorPosition]",
  329. ) -> Point | None:
  330. for y, line in enumerate(fragment_lines):
  331. x = 0
  332. for style_str, text, *_ in line:
  333. if fragment in style_str:
  334. return Point(x=x, y=y)
  335. x += len(text)
  336. return None
  337. # If there is a `[SetMenuPosition]`, set the menu over here.
  338. def get_menu_position() -> Point | None:
  339. return get_cursor_position("[SetMenuPosition]")
  340. cursor_position = (self.get_cursor_position or get_cursor_position)()
  341. # Create content, or take it from the cache.
  342. key = (tuple(fragments_with_mouse_handlers), width, cursor_position)
  343. def get_content() -> UIContent:
  344. return UIContent(
  345. get_line=lambda i: fragment_lines[i],
  346. line_count=len(fragment_lines),
  347. show_cursor=self.show_cursor,
  348. cursor_position=cursor_position,
  349. menu_position=get_menu_position(),
  350. )
  351. return self._content_cache.get(key, get_content)
  352. def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
  353. """
  354. Handle mouse events.
  355. (When the fragment list contained mouse handlers and the user clicked on
  356. on any of these, the matching handler is called. This handler can still
  357. return `NotImplemented` in case we want the
  358. :class:`~prompt_toolkit.layout.Window` to handle this particular
  359. event.)
  360. """
  361. if self._fragments:
  362. # Read the generator.
  363. fragments_for_line = list(split_lines(self._fragments))
  364. try:
  365. fragments = fragments_for_line[mouse_event.position.y]
  366. except IndexError:
  367. return NotImplemented
  368. else:
  369. # Find position in the fragment list.
  370. xpos = mouse_event.position.x
  371. # Find mouse handler for this character.
  372. count = 0
  373. for item in fragments:
  374. count += len(item[1])
  375. if count > xpos:
  376. if len(item) >= 3:
  377. # Handler found. Call it.
  378. # (Handler can return NotImplemented, so return
  379. # that result.)
  380. handler = item[2]
  381. return handler(mouse_event)
  382. else:
  383. break
  384. # Otherwise, don't handle here.
  385. return NotImplemented
  386. def is_modal(self) -> bool:
  387. return self.modal
  388. def get_key_bindings(self) -> KeyBindingsBase | None:
  389. return self.key_bindings
  390. class DummyControl(UIControl):
  391. """
  392. A dummy control object that doesn't paint any content.
  393. Useful for filling a :class:`~prompt_toolkit.layout.Window`. (The
  394. `fragment` and `char` attributes of the `Window` class can be used to
  395. define the filling.)
  396. """
  397. def create_content(self, width: int, height: int) -> UIContent:
  398. def get_line(i: int) -> StyleAndTextTuples:
  399. return []
  400. return UIContent(get_line=get_line, line_count=100**100) # Something very big.
  401. def is_focusable(self) -> bool:
  402. return False
  403. class _ProcessedLine(NamedTuple):
  404. fragments: StyleAndTextTuples
  405. source_to_display: Callable[[int], int]
  406. display_to_source: Callable[[int], int]
  407. class BufferControl(UIControl):
  408. """
  409. Control for visualizing the content of a :class:`.Buffer`.
  410. :param buffer: The :class:`.Buffer` object to be displayed.
  411. :param input_processors: A list of
  412. :class:`~prompt_toolkit.layout.processors.Processor` objects.
  413. :param include_default_input_processors: When True, include the default
  414. processors for highlighting of selection, search and displaying of
  415. multiple cursors.
  416. :param lexer: :class:`.Lexer` instance for syntax highlighting.
  417. :param preview_search: `bool` or :class:`.Filter`: Show search while
  418. typing. When this is `True`, probably you want to add a
  419. ``HighlightIncrementalSearchProcessor`` as well. Otherwise only the
  420. cursor position will move, but the text won't be highlighted.
  421. :param focusable: `bool` or :class:`.Filter`: Tell whether this control is focusable.
  422. :param focus_on_click: Focus this buffer when it's click, but not yet focused.
  423. :param key_bindings: a :class:`.KeyBindings` object.
  424. """
  425. def __init__(
  426. self,
  427. buffer: Buffer | None = None,
  428. input_processors: list[Processor] | None = None,
  429. include_default_input_processors: bool = True,
  430. lexer: Lexer | None = None,
  431. preview_search: FilterOrBool = False,
  432. focusable: FilterOrBool = True,
  433. search_buffer_control: (
  434. None | SearchBufferControl | Callable[[], SearchBufferControl]
  435. ) = None,
  436. menu_position: Callable[[], int | None] | None = None,
  437. focus_on_click: FilterOrBool = False,
  438. key_bindings: KeyBindingsBase | None = None,
  439. ):
  440. self.input_processors = input_processors
  441. self.include_default_input_processors = include_default_input_processors
  442. self.default_input_processors = [
  443. HighlightSearchProcessor(),
  444. HighlightIncrementalSearchProcessor(),
  445. HighlightSelectionProcessor(),
  446. DisplayMultipleCursors(),
  447. ]
  448. self.preview_search = to_filter(preview_search)
  449. self.focusable = to_filter(focusable)
  450. self.focus_on_click = to_filter(focus_on_click)
  451. self.buffer = buffer or Buffer()
  452. self.menu_position = menu_position
  453. self.lexer = lexer or SimpleLexer()
  454. self.key_bindings = key_bindings
  455. self._search_buffer_control = search_buffer_control
  456. #: Cache for the lexer.
  457. #: Often, due to cursor movement, undo/redo and window resizing
  458. #: operations, it happens that a short time, the same document has to be
  459. #: lexed. This is a fairly easy way to cache such an expensive operation.
  460. self._fragment_cache: SimpleCache[
  461. Hashable, Callable[[int], StyleAndTextTuples]
  462. ] = SimpleCache(maxsize=8)
  463. self._last_click_timestamp: float | None = None
  464. self._last_get_processed_line: Callable[[int], _ProcessedLine] | None = None
  465. def __repr__(self) -> str:
  466. return f"<{self.__class__.__name__} buffer={self.buffer!r} at {id(self)!r}>"
  467. @property
  468. def search_buffer_control(self) -> SearchBufferControl | None:
  469. result: SearchBufferControl | None
  470. if callable(self._search_buffer_control):
  471. result = self._search_buffer_control()
  472. else:
  473. result = self._search_buffer_control
  474. assert result is None or isinstance(result, SearchBufferControl)
  475. return result
  476. @property
  477. def search_buffer(self) -> Buffer | None:
  478. control = self.search_buffer_control
  479. if control is not None:
  480. return control.buffer
  481. return None
  482. @property
  483. def search_state(self) -> SearchState:
  484. """
  485. Return the `SearchState` for searching this `BufferControl`. This is
  486. always associated with the search control. If one search bar is used
  487. for searching multiple `BufferControls`, then they share the same
  488. `SearchState`.
  489. """
  490. search_buffer_control = self.search_buffer_control
  491. if search_buffer_control:
  492. return search_buffer_control.searcher_search_state
  493. else:
  494. return SearchState()
  495. def is_focusable(self) -> bool:
  496. return self.focusable()
  497. def preferred_width(self, max_available_width: int) -> int | None:
  498. """
  499. This should return the preferred width.
  500. Note: We don't specify a preferred width according to the content,
  501. because it would be too expensive. Calculating the preferred
  502. width can be done by calculating the longest line, but this would
  503. require applying all the processors to each line. This is
  504. unfeasible for a larger document, and doing it for small
  505. documents only would result in inconsistent behavior.
  506. """
  507. return None
  508. def preferred_height(
  509. self,
  510. width: int,
  511. max_available_height: int,
  512. wrap_lines: bool,
  513. get_line_prefix: GetLinePrefixCallable | None,
  514. ) -> int | None:
  515. # Calculate the content height, if it was drawn on a screen with the
  516. # given width.
  517. height = 0
  518. content = self.create_content(width, height=1) # Pass a dummy '1' as height.
  519. # When line wrapping is off, the height should be equal to the amount
  520. # of lines.
  521. if not wrap_lines:
  522. return content.line_count
  523. # When the number of lines exceeds the max_available_height, just
  524. # return max_available_height. No need to calculate anything.
  525. if content.line_count >= max_available_height:
  526. return max_available_height
  527. for i in range(content.line_count):
  528. height += content.get_height_for_line(i, width, get_line_prefix)
  529. if height >= max_available_height:
  530. return max_available_height
  531. return height
  532. def _get_formatted_text_for_line_func(
  533. self, document: Document
  534. ) -> Callable[[int], StyleAndTextTuples]:
  535. """
  536. Create a function that returns the fragments for a given line.
  537. """
  538. # Cache using `document.text`.
  539. def get_formatted_text_for_line() -> Callable[[int], StyleAndTextTuples]:
  540. return self.lexer.lex_document(document)
  541. key = (document.text, self.lexer.invalidation_hash())
  542. return self._fragment_cache.get(key, get_formatted_text_for_line)
  543. def _create_get_processed_line_func(
  544. self, document: Document, width: int, height: int
  545. ) -> Callable[[int], _ProcessedLine]:
  546. """
  547. Create a function that takes a line number of the current document and
  548. returns a _ProcessedLine(processed_fragments, source_to_display, display_to_source)
  549. tuple.
  550. """
  551. # Merge all input processors together.
  552. input_processors = self.input_processors or []
  553. if self.include_default_input_processors:
  554. input_processors = self.default_input_processors + input_processors
  555. merged_processor = merge_processors(input_processors)
  556. def transform(lineno: int, fragments: StyleAndTextTuples) -> _ProcessedLine:
  557. "Transform the fragments for a given line number."
  558. # Get cursor position at this line.
  559. def source_to_display(i: int) -> int:
  560. """X position from the buffer to the x position in the
  561. processed fragment list. By default, we start from the 'identity'
  562. operation."""
  563. return i
  564. transformation = merged_processor.apply_transformation(
  565. TransformationInput(
  566. self, document, lineno, source_to_display, fragments, width, height
  567. )
  568. )
  569. return _ProcessedLine(
  570. transformation.fragments,
  571. transformation.source_to_display,
  572. transformation.display_to_source,
  573. )
  574. def create_func() -> Callable[[int], _ProcessedLine]:
  575. get_line = self._get_formatted_text_for_line_func(document)
  576. cache: dict[int, _ProcessedLine] = {}
  577. def get_processed_line(i: int) -> _ProcessedLine:
  578. try:
  579. return cache[i]
  580. except KeyError:
  581. processed_line = transform(i, get_line(i))
  582. cache[i] = processed_line
  583. return processed_line
  584. return get_processed_line
  585. return create_func()
  586. def create_content(
  587. self, width: int, height: int, preview_search: bool = False
  588. ) -> UIContent:
  589. """
  590. Create a UIContent.
  591. """
  592. buffer = self.buffer
  593. # Trigger history loading of the buffer. We do this during the
  594. # rendering of the UI here, because it needs to happen when an
  595. # `Application` with its event loop is running. During the rendering of
  596. # the buffer control is the earliest place we can achieve this, where
  597. # we're sure the right event loop is active, and don't require user
  598. # interaction (like in a key binding).
  599. buffer.load_history_if_not_yet_loaded()
  600. # Get the document to be shown. If we are currently searching (the
  601. # search buffer has focus, and the preview_search filter is enabled),
  602. # then use the search document, which has possibly a different
  603. # text/cursor position.)
  604. search_control = self.search_buffer_control
  605. preview_now = preview_search or bool(
  606. # Only if this feature is enabled.
  607. self.preview_search()
  608. and
  609. # And something was typed in the associated search field.
  610. search_control
  611. and search_control.buffer.text
  612. and
  613. # And we are searching in this control. (Many controls can point to
  614. # the same search field, like in Pyvim.)
  615. get_app().layout.search_target_buffer_control == self
  616. )
  617. if preview_now and search_control is not None:
  618. ss = self.search_state
  619. document = buffer.document_for_search(
  620. SearchState(
  621. text=search_control.buffer.text,
  622. direction=ss.direction,
  623. ignore_case=ss.ignore_case,
  624. )
  625. )
  626. else:
  627. document = buffer.document
  628. get_processed_line = self._create_get_processed_line_func(
  629. document, width, height
  630. )
  631. self._last_get_processed_line = get_processed_line
  632. def translate_rowcol(row: int, col: int) -> Point:
  633. "Return the content column for this coordinate."
  634. return Point(x=get_processed_line(row).source_to_display(col), y=row)
  635. def get_line(i: int) -> StyleAndTextTuples:
  636. "Return the fragments for a given line number."
  637. fragments = get_processed_line(i).fragments
  638. # Add a space at the end, because that is a possible cursor
  639. # position. (When inserting after the input.) We should do this on
  640. # all the lines, not just the line containing the cursor. (Because
  641. # otherwise, line wrapping/scrolling could change when moving the
  642. # cursor around.)
  643. fragments = fragments + [("", " ")]
  644. return fragments
  645. content = UIContent(
  646. get_line=get_line,
  647. line_count=document.line_count,
  648. cursor_position=translate_rowcol(
  649. document.cursor_position_row, document.cursor_position_col
  650. ),
  651. )
  652. # If there is an auto completion going on, use that start point for a
  653. # pop-up menu position. (But only when this buffer has the focus --
  654. # there is only one place for a menu, determined by the focused buffer.)
  655. if get_app().layout.current_control == self:
  656. menu_position = self.menu_position() if self.menu_position else None
  657. if menu_position is not None:
  658. assert isinstance(menu_position, int)
  659. menu_row, menu_col = buffer.document.translate_index_to_position(
  660. menu_position
  661. )
  662. content.menu_position = translate_rowcol(menu_row, menu_col)
  663. elif buffer.complete_state:
  664. # Position for completion menu.
  665. # Note: We use 'min', because the original cursor position could be
  666. # behind the input string when the actual completion is for
  667. # some reason shorter than the text we had before. (A completion
  668. # can change and shorten the input.)
  669. menu_row, menu_col = buffer.document.translate_index_to_position(
  670. min(
  671. buffer.cursor_position,
  672. buffer.complete_state.original_document.cursor_position,
  673. )
  674. )
  675. content.menu_position = translate_rowcol(menu_row, menu_col)
  676. else:
  677. content.menu_position = None
  678. return content
  679. def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
  680. """
  681. Mouse handler for this control.
  682. """
  683. buffer = self.buffer
  684. position = mouse_event.position
  685. # Focus buffer when clicked.
  686. if get_app().layout.current_control == self:
  687. if self._last_get_processed_line:
  688. processed_line = self._last_get_processed_line(position.y)
  689. # Translate coordinates back to the cursor position of the
  690. # original input.
  691. xpos = processed_line.display_to_source(position.x)
  692. index = buffer.document.translate_row_col_to_index(position.y, xpos)
  693. # Set the cursor position.
  694. if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
  695. buffer.exit_selection()
  696. buffer.cursor_position = index
  697. elif (
  698. mouse_event.event_type == MouseEventType.MOUSE_MOVE
  699. and mouse_event.button != MouseButton.NONE
  700. ):
  701. # Click and drag to highlight a selection
  702. if (
  703. buffer.selection_state is None
  704. and abs(buffer.cursor_position - index) > 0
  705. ):
  706. buffer.start_selection(selection_type=SelectionType.CHARACTERS)
  707. buffer.cursor_position = index
  708. elif mouse_event.event_type == MouseEventType.MOUSE_UP:
  709. # When the cursor was moved to another place, select the text.
  710. # (The >1 is actually a small but acceptable workaround for
  711. # selecting text in Vi navigation mode. In navigation mode,
  712. # the cursor can never be after the text, so the cursor
  713. # will be repositioned automatically.)
  714. if abs(buffer.cursor_position - index) > 1:
  715. if buffer.selection_state is None:
  716. buffer.start_selection(
  717. selection_type=SelectionType.CHARACTERS
  718. )
  719. buffer.cursor_position = index
  720. # Select word around cursor on double click.
  721. # Two MOUSE_UP events in a short timespan are considered a double click.
  722. double_click = (
  723. self._last_click_timestamp
  724. and time.time() - self._last_click_timestamp < 0.3
  725. )
  726. self._last_click_timestamp = time.time()
  727. if double_click:
  728. start, end = buffer.document.find_boundaries_of_current_word()
  729. buffer.cursor_position += start
  730. buffer.start_selection(selection_type=SelectionType.CHARACTERS)
  731. buffer.cursor_position += end - start
  732. else:
  733. # Don't handle scroll events here.
  734. return NotImplemented
  735. # Not focused, but focusing on click events.
  736. else:
  737. if (
  738. self.focus_on_click()
  739. and mouse_event.event_type == MouseEventType.MOUSE_UP
  740. ):
  741. # Focus happens on mouseup. (If we did this on mousedown, the
  742. # up event will be received at the point where this widget is
  743. # focused and be handled anyway.)
  744. get_app().layout.current_control = self
  745. else:
  746. return NotImplemented
  747. return None
  748. def move_cursor_down(self) -> None:
  749. b = self.buffer
  750. b.cursor_position += b.document.get_cursor_down_position()
  751. def move_cursor_up(self) -> None:
  752. b = self.buffer
  753. b.cursor_position += b.document.get_cursor_up_position()
  754. def get_key_bindings(self) -> KeyBindingsBase | None:
  755. """
  756. When additional key bindings are given. Return these.
  757. """
  758. return self.key_bindings
  759. def get_invalidate_events(self) -> Iterable[Event[object]]:
  760. """
  761. Return the Window invalidate events.
  762. """
  763. # Whenever the buffer changes, the UI has to be updated.
  764. yield self.buffer.on_text_changed
  765. yield self.buffer.on_cursor_position_changed
  766. yield self.buffer.on_completions_changed
  767. yield self.buffer.on_suggestion_set
  768. class SearchBufferControl(BufferControl):
  769. """
  770. :class:`.BufferControl` which is used for searching another
  771. :class:`.BufferControl`.
  772. :param ignore_case: Search case insensitive.
  773. """
  774. def __init__(
  775. self,
  776. buffer: Buffer | None = None,
  777. input_processors: list[Processor] | None = None,
  778. lexer: Lexer | None = None,
  779. focus_on_click: FilterOrBool = False,
  780. key_bindings: KeyBindingsBase | None = None,
  781. ignore_case: FilterOrBool = False,
  782. ):
  783. super().__init__(
  784. buffer=buffer,
  785. input_processors=input_processors,
  786. lexer=lexer,
  787. focus_on_click=focus_on_click,
  788. key_bindings=key_bindings,
  789. )
  790. # If this BufferControl is used as a search field for one or more other
  791. # BufferControls, then represents the search state.
  792. self.searcher_search_state = SearchState(ignore_case=ignore_case)