controls.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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] # type: ignore
  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(
  401. get_line=get_line, line_count=100**100
  402. ) # Something very big.
  403. def is_focusable(self) -> bool:
  404. return False
  405. class _ProcessedLine(NamedTuple):
  406. fragments: StyleAndTextTuples
  407. source_to_display: Callable[[int], int]
  408. display_to_source: Callable[[int], int]
  409. class BufferControl(UIControl):
  410. """
  411. Control for visualising the content of a :class:`.Buffer`.
  412. :param buffer: The :class:`.Buffer` object to be displayed.
  413. :param input_processors: A list of
  414. :class:`~prompt_toolkit.layout.processors.Processor` objects.
  415. :param include_default_input_processors: When True, include the default
  416. processors for highlighting of selection, search and displaying of
  417. multiple cursors.
  418. :param lexer: :class:`.Lexer` instance for syntax highlighting.
  419. :param preview_search: `bool` or :class:`.Filter`: Show search while
  420. typing. When this is `True`, probably you want to add a
  421. ``HighlightIncrementalSearchProcessor`` as well. Otherwise only the
  422. cursor position will move, but the text won't be highlighted.
  423. :param focusable: `bool` or :class:`.Filter`: Tell whether this control is focusable.
  424. :param focus_on_click: Focus this buffer when it's click, but not yet focused.
  425. :param key_bindings: a :class:`.KeyBindings` object.
  426. """
  427. def __init__(
  428. self,
  429. buffer: Buffer | None = None,
  430. input_processors: list[Processor] | None = None,
  431. include_default_input_processors: bool = True,
  432. lexer: Lexer | None = None,
  433. preview_search: FilterOrBool = False,
  434. focusable: FilterOrBool = True,
  435. search_buffer_control: (
  436. None | SearchBufferControl | Callable[[], SearchBufferControl]
  437. ) = None,
  438. menu_position: Callable[[], int | None] | None = None,
  439. focus_on_click: FilterOrBool = False,
  440. key_bindings: KeyBindingsBase | None = None,
  441. ):
  442. self.input_processors = input_processors
  443. self.include_default_input_processors = include_default_input_processors
  444. self.default_input_processors = [
  445. HighlightSearchProcessor(),
  446. HighlightIncrementalSearchProcessor(),
  447. HighlightSelectionProcessor(),
  448. DisplayMultipleCursors(),
  449. ]
  450. self.preview_search = to_filter(preview_search)
  451. self.focusable = to_filter(focusable)
  452. self.focus_on_click = to_filter(focus_on_click)
  453. self.buffer = buffer or Buffer()
  454. self.menu_position = menu_position
  455. self.lexer = lexer or SimpleLexer()
  456. self.key_bindings = key_bindings
  457. self._search_buffer_control = search_buffer_control
  458. #: Cache for the lexer.
  459. #: Often, due to cursor movement, undo/redo and window resizing
  460. #: operations, it happens that a short time, the same document has to be
  461. #: lexed. This is a fairly easy way to cache such an expensive operation.
  462. self._fragment_cache: SimpleCache[
  463. Hashable, Callable[[int], StyleAndTextTuples]
  464. ] = SimpleCache(maxsize=8)
  465. self._last_click_timestamp: float | None = None
  466. self._last_get_processed_line: Callable[[int], _ProcessedLine] | None = None
  467. def __repr__(self) -> str:
  468. return f"<{self.__class__.__name__} buffer={self.buffer!r} at {id(self)!r}>"
  469. @property
  470. def search_buffer_control(self) -> SearchBufferControl | None:
  471. result: SearchBufferControl | None
  472. if callable(self._search_buffer_control):
  473. result = self._search_buffer_control()
  474. else:
  475. result = self._search_buffer_control
  476. assert result is None or isinstance(result, SearchBufferControl)
  477. return result
  478. @property
  479. def search_buffer(self) -> Buffer | None:
  480. control = self.search_buffer_control
  481. if control is not None:
  482. return control.buffer
  483. return None
  484. @property
  485. def search_state(self) -> SearchState:
  486. """
  487. Return the `SearchState` for searching this `BufferControl`. This is
  488. always associated with the search control. If one search bar is used
  489. for searching multiple `BufferControls`, then they share the same
  490. `SearchState`.
  491. """
  492. search_buffer_control = self.search_buffer_control
  493. if search_buffer_control:
  494. return search_buffer_control.searcher_search_state
  495. else:
  496. return SearchState()
  497. def is_focusable(self) -> bool:
  498. return self.focusable()
  499. def preferred_width(self, max_available_width: int) -> int | None:
  500. """
  501. This should return the preferred width.
  502. Note: We don't specify a preferred width according to the content,
  503. because it would be too expensive. Calculating the preferred
  504. width can be done by calculating the longest line, but this would
  505. require applying all the processors to each line. This is
  506. unfeasible for a larger document, and doing it for small
  507. documents only would result in inconsistent behaviour.
  508. """
  509. return None
  510. def preferred_height(
  511. self,
  512. width: int,
  513. max_available_height: int,
  514. wrap_lines: bool,
  515. get_line_prefix: GetLinePrefixCallable | None,
  516. ) -> int | None:
  517. # Calculate the content height, if it was drawn on a screen with the
  518. # given width.
  519. height = 0
  520. content = self.create_content(width, height=1) # Pass a dummy '1' as height.
  521. # When line wrapping is off, the height should be equal to the amount
  522. # of lines.
  523. if not wrap_lines:
  524. return content.line_count
  525. # When the number of lines exceeds the max_available_height, just
  526. # return max_available_height. No need to calculate anything.
  527. if content.line_count >= max_available_height:
  528. return max_available_height
  529. for i in range(content.line_count):
  530. height += content.get_height_for_line(i, width, get_line_prefix)
  531. if height >= max_available_height:
  532. return max_available_height
  533. return height
  534. def _get_formatted_text_for_line_func(
  535. self, document: Document
  536. ) -> Callable[[int], StyleAndTextTuples]:
  537. """
  538. Create a function that returns the fragments for a given line.
  539. """
  540. # Cache using `document.text`.
  541. def get_formatted_text_for_line() -> Callable[[int], StyleAndTextTuples]:
  542. return self.lexer.lex_document(document)
  543. key = (document.text, self.lexer.invalidation_hash())
  544. return self._fragment_cache.get(key, get_formatted_text_for_line)
  545. def _create_get_processed_line_func(
  546. self, document: Document, width: int, height: int
  547. ) -> Callable[[int], _ProcessedLine]:
  548. """
  549. Create a function that takes a line number of the current document and
  550. returns a _ProcessedLine(processed_fragments, source_to_display, display_to_source)
  551. tuple.
  552. """
  553. # Merge all input processors together.
  554. input_processors = self.input_processors or []
  555. if self.include_default_input_processors:
  556. input_processors = self.default_input_processors + input_processors
  557. merged_processor = merge_processors(input_processors)
  558. def transform(lineno: int, fragments: StyleAndTextTuples) -> _ProcessedLine:
  559. "Transform the fragments for a given line number."
  560. # Get cursor position at this line.
  561. def source_to_display(i: int) -> int:
  562. """X position from the buffer to the x position in the
  563. processed fragment list. By default, we start from the 'identity'
  564. operation."""
  565. return i
  566. transformation = merged_processor.apply_transformation(
  567. TransformationInput(
  568. self, document, lineno, source_to_display, fragments, width, height
  569. )
  570. )
  571. return _ProcessedLine(
  572. transformation.fragments,
  573. transformation.source_to_display,
  574. transformation.display_to_source,
  575. )
  576. def create_func() -> Callable[[int], _ProcessedLine]:
  577. get_line = self._get_formatted_text_for_line_func(document)
  578. cache: dict[int, _ProcessedLine] = {}
  579. def get_processed_line(i: int) -> _ProcessedLine:
  580. try:
  581. return cache[i]
  582. except KeyError:
  583. processed_line = transform(i, get_line(i))
  584. cache[i] = processed_line
  585. return processed_line
  586. return get_processed_line
  587. return create_func()
  588. def create_content(
  589. self, width: int, height: int, preview_search: bool = False
  590. ) -> UIContent:
  591. """
  592. Create a UIContent.
  593. """
  594. buffer = self.buffer
  595. # Trigger history loading of the buffer. We do this during the
  596. # rendering of the UI here, because it needs to happen when an
  597. # `Application` with its event loop is running. During the rendering of
  598. # the buffer control is the earliest place we can achieve this, where
  599. # we're sure the right event loop is active, and don't require user
  600. # interaction (like in a key binding).
  601. buffer.load_history_if_not_yet_loaded()
  602. # Get the document to be shown. If we are currently searching (the
  603. # search buffer has focus, and the preview_search filter is enabled),
  604. # then use the search document, which has possibly a different
  605. # text/cursor position.)
  606. search_control = self.search_buffer_control
  607. preview_now = preview_search or bool(
  608. # Only if this feature is enabled.
  609. self.preview_search()
  610. and
  611. # And something was typed in the associated search field.
  612. search_control
  613. and search_control.buffer.text
  614. and
  615. # And we are searching in this control. (Many controls can point to
  616. # the same search field, like in Pyvim.)
  617. get_app().layout.search_target_buffer_control == self
  618. )
  619. if preview_now and search_control is not None:
  620. ss = self.search_state
  621. document = buffer.document_for_search(
  622. SearchState(
  623. text=search_control.buffer.text,
  624. direction=ss.direction,
  625. ignore_case=ss.ignore_case,
  626. )
  627. )
  628. else:
  629. document = buffer.document
  630. get_processed_line = self._create_get_processed_line_func(
  631. document, width, height
  632. )
  633. self._last_get_processed_line = get_processed_line
  634. def translate_rowcol(row: int, col: int) -> Point:
  635. "Return the content column for this coordinate."
  636. return Point(x=get_processed_line(row).source_to_display(col), y=row)
  637. def get_line(i: int) -> StyleAndTextTuples:
  638. "Return the fragments for a given line number."
  639. fragments = get_processed_line(i).fragments
  640. # Add a space at the end, because that is a possible cursor
  641. # position. (When inserting after the input.) We should do this on
  642. # all the lines, not just the line containing the cursor. (Because
  643. # otherwise, line wrapping/scrolling could change when moving the
  644. # cursor around.)
  645. fragments = fragments + [("", " ")]
  646. return fragments
  647. content = UIContent(
  648. get_line=get_line,
  649. line_count=document.line_count,
  650. cursor_position=translate_rowcol(
  651. document.cursor_position_row, document.cursor_position_col
  652. ),
  653. )
  654. # If there is an auto completion going on, use that start point for a
  655. # pop-up menu position. (But only when this buffer has the focus --
  656. # there is only one place for a menu, determined by the focused buffer.)
  657. if get_app().layout.current_control == self:
  658. menu_position = self.menu_position() if self.menu_position else None
  659. if menu_position is not None:
  660. assert isinstance(menu_position, int)
  661. menu_row, menu_col = buffer.document.translate_index_to_position(
  662. menu_position
  663. )
  664. content.menu_position = translate_rowcol(menu_row, menu_col)
  665. elif buffer.complete_state:
  666. # Position for completion menu.
  667. # Note: We use 'min', because the original cursor position could be
  668. # behind the input string when the actual completion is for
  669. # some reason shorter than the text we had before. (A completion
  670. # can change and shorten the input.)
  671. menu_row, menu_col = buffer.document.translate_index_to_position(
  672. min(
  673. buffer.cursor_position,
  674. buffer.complete_state.original_document.cursor_position,
  675. )
  676. )
  677. content.menu_position = translate_rowcol(menu_row, menu_col)
  678. else:
  679. content.menu_position = None
  680. return content
  681. def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
  682. """
  683. Mouse handler for this control.
  684. """
  685. buffer = self.buffer
  686. position = mouse_event.position
  687. # Focus buffer when clicked.
  688. if get_app().layout.current_control == self:
  689. if self._last_get_processed_line:
  690. processed_line = self._last_get_processed_line(position.y)
  691. # Translate coordinates back to the cursor position of the
  692. # original input.
  693. xpos = processed_line.display_to_source(position.x)
  694. index = buffer.document.translate_row_col_to_index(position.y, xpos)
  695. # Set the cursor position.
  696. if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
  697. buffer.exit_selection()
  698. buffer.cursor_position = index
  699. elif (
  700. mouse_event.event_type == MouseEventType.MOUSE_MOVE
  701. and mouse_event.button != MouseButton.NONE
  702. ):
  703. # Click and drag to highlight a selection
  704. if (
  705. buffer.selection_state is None
  706. and abs(buffer.cursor_position - index) > 0
  707. ):
  708. buffer.start_selection(selection_type=SelectionType.CHARACTERS)
  709. buffer.cursor_position = index
  710. elif mouse_event.event_type == MouseEventType.MOUSE_UP:
  711. # When the cursor was moved to another place, select the text.
  712. # (The >1 is actually a small but acceptable workaround for
  713. # selecting text in Vi navigation mode. In navigation mode,
  714. # the cursor can never be after the text, so the cursor
  715. # will be repositioned automatically.)
  716. if abs(buffer.cursor_position - index) > 1:
  717. if buffer.selection_state is None:
  718. buffer.start_selection(
  719. selection_type=SelectionType.CHARACTERS
  720. )
  721. buffer.cursor_position = index
  722. # Select word around cursor on double click.
  723. # Two MOUSE_UP events in a short timespan are considered a double click.
  724. double_click = (
  725. self._last_click_timestamp
  726. and time.time() - self._last_click_timestamp < 0.3
  727. )
  728. self._last_click_timestamp = time.time()
  729. if double_click:
  730. start, end = buffer.document.find_boundaries_of_current_word()
  731. buffer.cursor_position += start
  732. buffer.start_selection(selection_type=SelectionType.CHARACTERS)
  733. buffer.cursor_position += end - start
  734. else:
  735. # Don't handle scroll events here.
  736. return NotImplemented
  737. # Not focused, but focusing on click events.
  738. else:
  739. if (
  740. self.focus_on_click()
  741. and mouse_event.event_type == MouseEventType.MOUSE_UP
  742. ):
  743. # Focus happens on mouseup. (If we did this on mousedown, the
  744. # up event will be received at the point where this widget is
  745. # focused and be handled anyway.)
  746. get_app().layout.current_control = self
  747. else:
  748. return NotImplemented
  749. return None
  750. def move_cursor_down(self) -> None:
  751. b = self.buffer
  752. b.cursor_position += b.document.get_cursor_down_position()
  753. def move_cursor_up(self) -> None:
  754. b = self.buffer
  755. b.cursor_position += b.document.get_cursor_up_position()
  756. def get_key_bindings(self) -> KeyBindingsBase | None:
  757. """
  758. When additional key bindings are given. Return these.
  759. """
  760. return self.key_bindings
  761. def get_invalidate_events(self) -> Iterable[Event[object]]:
  762. """
  763. Return the Window invalidate events.
  764. """
  765. # Whenever the buffer changes, the UI has to be updated.
  766. yield self.buffer.on_text_changed
  767. yield self.buffer.on_cursor_position_changed
  768. yield self.buffer.on_completions_changed
  769. yield self.buffer.on_suggestion_set
  770. class SearchBufferControl(BufferControl):
  771. """
  772. :class:`.BufferControl` which is used for searching another
  773. :class:`.BufferControl`.
  774. :param ignore_case: Search case insensitive.
  775. """
  776. def __init__(
  777. self,
  778. buffer: Buffer | None = None,
  779. input_processors: list[Processor] | None = None,
  780. lexer: Lexer | None = None,
  781. focus_on_click: FilterOrBool = False,
  782. key_bindings: KeyBindingsBase | None = None,
  783. ignore_case: FilterOrBool = False,
  784. ):
  785. super().__init__(
  786. buffer=buffer,
  787. input_processors=input_processors,
  788. lexer=lexer,
  789. focus_on_click=focus_on_click,
  790. key_bindings=key_bindings,
  791. )
  792. # If this BufferControl is used as a search field for one or more other
  793. # BufferControls, then represents the search state.
  794. self.searcher_search_state = SearchState(ignore_case=ignore_case)