processors.py 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. """
  2. Processors are little transformation blocks that transform the fragments list
  3. from a buffer before the BufferControl will render it to the screen.
  4. They can insert fragments before or after, or highlight fragments by replacing the
  5. fragment types.
  6. """
  7. from __future__ import annotations
  8. import re
  9. from abc import ABCMeta, abstractmethod
  10. from typing import TYPE_CHECKING, Callable, Hashable, cast
  11. from prompt_toolkit.application.current import get_app
  12. from prompt_toolkit.cache import SimpleCache
  13. from prompt_toolkit.document import Document
  14. from prompt_toolkit.filters import FilterOrBool, to_filter, vi_insert_multiple_mode
  15. from prompt_toolkit.formatted_text import (
  16. AnyFormattedText,
  17. StyleAndTextTuples,
  18. to_formatted_text,
  19. )
  20. from prompt_toolkit.formatted_text.utils import fragment_list_len, fragment_list_to_text
  21. from prompt_toolkit.search import SearchDirection
  22. from prompt_toolkit.utils import to_int, to_str
  23. from .utils import explode_text_fragments
  24. if TYPE_CHECKING:
  25. from .controls import BufferControl, UIContent
  26. __all__ = [
  27. "Processor",
  28. "TransformationInput",
  29. "Transformation",
  30. "DummyProcessor",
  31. "HighlightSearchProcessor",
  32. "HighlightIncrementalSearchProcessor",
  33. "HighlightSelectionProcessor",
  34. "PasswordProcessor",
  35. "HighlightMatchingBracketProcessor",
  36. "DisplayMultipleCursors",
  37. "BeforeInput",
  38. "ShowArg",
  39. "AfterInput",
  40. "AppendAutoSuggestion",
  41. "ConditionalProcessor",
  42. "ShowLeadingWhiteSpaceProcessor",
  43. "ShowTrailingWhiteSpaceProcessor",
  44. "TabsProcessor",
  45. "ReverseSearchProcessor",
  46. "DynamicProcessor",
  47. "merge_processors",
  48. ]
  49. class Processor(metaclass=ABCMeta):
  50. """
  51. Manipulate the fragments for a given line in a
  52. :class:`~prompt_toolkit.layout.controls.BufferControl`.
  53. """
  54. @abstractmethod
  55. def apply_transformation(
  56. self, transformation_input: TransformationInput
  57. ) -> Transformation:
  58. """
  59. Apply transformation. Returns a :class:`.Transformation` instance.
  60. :param transformation_input: :class:`.TransformationInput` object.
  61. """
  62. return Transformation(transformation_input.fragments)
  63. SourceToDisplay = Callable[[int], int]
  64. DisplayToSource = Callable[[int], int]
  65. class TransformationInput:
  66. """
  67. :param buffer_control: :class:`.BufferControl` instance.
  68. :param lineno: The number of the line to which we apply the processor.
  69. :param source_to_display: A function that returns the position in the
  70. `fragments` for any position in the source string. (This takes
  71. previous processors into account.)
  72. :param fragments: List of fragments that we can transform. (Received from the
  73. previous processor.)
  74. :param get_line: Optional ; a callable that returns the fragments of another
  75. line in the current buffer; This can be used to create processors capable
  76. of affecting transforms across multiple lines.
  77. """
  78. def __init__(
  79. self,
  80. buffer_control: BufferControl,
  81. document: Document,
  82. lineno: int,
  83. source_to_display: SourceToDisplay,
  84. fragments: StyleAndTextTuples,
  85. width: int,
  86. height: int,
  87. get_line: Callable[[int], StyleAndTextTuples] | None = None,
  88. ) -> None:
  89. self.buffer_control = buffer_control
  90. self.document = document
  91. self.lineno = lineno
  92. self.source_to_display = source_to_display
  93. self.fragments = fragments
  94. self.width = width
  95. self.height = height
  96. self.get_line = get_line
  97. def unpack(
  98. self,
  99. ) -> tuple[
  100. BufferControl, Document, int, SourceToDisplay, StyleAndTextTuples, int, int
  101. ]:
  102. return (
  103. self.buffer_control,
  104. self.document,
  105. self.lineno,
  106. self.source_to_display,
  107. self.fragments,
  108. self.width,
  109. self.height,
  110. )
  111. class Transformation:
  112. """
  113. Transformation result, as returned by :meth:`.Processor.apply_transformation`.
  114. Important: Always make sure that the length of `document.text` is equal to
  115. the length of all the text in `fragments`!
  116. :param fragments: The transformed fragments. To be displayed, or to pass to
  117. the next processor.
  118. :param source_to_display: Cursor position transformation from original
  119. string to transformed string.
  120. :param display_to_source: Cursor position transformed from source string to
  121. original string.
  122. """
  123. def __init__(
  124. self,
  125. fragments: StyleAndTextTuples,
  126. source_to_display: SourceToDisplay | None = None,
  127. display_to_source: DisplayToSource | None = None,
  128. ) -> None:
  129. self.fragments = fragments
  130. self.source_to_display = source_to_display or (lambda i: i)
  131. self.display_to_source = display_to_source or (lambda i: i)
  132. class DummyProcessor(Processor):
  133. """
  134. A `Processor` that doesn't do anything.
  135. """
  136. def apply_transformation(
  137. self, transformation_input: TransformationInput
  138. ) -> Transformation:
  139. return Transformation(transformation_input.fragments)
  140. class HighlightSearchProcessor(Processor):
  141. """
  142. Processor that highlights search matches in the document.
  143. Note that this doesn't support multiline search matches yet.
  144. The style classes 'search' and 'search.current' will be applied to the
  145. content.
  146. """
  147. _classname = "search"
  148. _classname_current = "search.current"
  149. def _get_search_text(self, buffer_control: BufferControl) -> str:
  150. """
  151. The text we are searching for.
  152. """
  153. return buffer_control.search_state.text
  154. def apply_transformation(
  155. self, transformation_input: TransformationInput
  156. ) -> Transformation:
  157. (
  158. buffer_control,
  159. document,
  160. lineno,
  161. source_to_display,
  162. fragments,
  163. _,
  164. _,
  165. ) = transformation_input.unpack()
  166. search_text = self._get_search_text(buffer_control)
  167. searchmatch_fragment = f" class:{self._classname} "
  168. searchmatch_current_fragment = f" class:{self._classname_current} "
  169. if search_text and not get_app().is_done:
  170. # For each search match, replace the style string.
  171. line_text = fragment_list_to_text(fragments)
  172. fragments = explode_text_fragments(fragments)
  173. if buffer_control.search_state.ignore_case():
  174. flags = re.IGNORECASE
  175. else:
  176. flags = re.RegexFlag(0)
  177. # Get cursor column.
  178. cursor_column: int | None
  179. if document.cursor_position_row == lineno:
  180. cursor_column = source_to_display(document.cursor_position_col)
  181. else:
  182. cursor_column = None
  183. for match in re.finditer(re.escape(search_text), line_text, flags=flags):
  184. if cursor_column is not None:
  185. on_cursor = match.start() <= cursor_column < match.end()
  186. else:
  187. on_cursor = False
  188. for i in range(match.start(), match.end()):
  189. old_fragment, text, *_ = fragments[i]
  190. if on_cursor:
  191. fragments[i] = (
  192. old_fragment + searchmatch_current_fragment,
  193. fragments[i][1],
  194. )
  195. else:
  196. fragments[i] = (
  197. old_fragment + searchmatch_fragment,
  198. fragments[i][1],
  199. )
  200. return Transformation(fragments)
  201. class HighlightIncrementalSearchProcessor(HighlightSearchProcessor):
  202. """
  203. Highlight the search terms that are used for highlighting the incremental
  204. search. The style class 'incsearch' will be applied to the content.
  205. Important: this requires the `preview_search=True` flag to be set for the
  206. `BufferControl`. Otherwise, the cursor position won't be set to the search
  207. match while searching, and nothing happens.
  208. """
  209. _classname = "incsearch"
  210. _classname_current = "incsearch.current"
  211. def _get_search_text(self, buffer_control: BufferControl) -> str:
  212. """
  213. The text we are searching for.
  214. """
  215. # When the search buffer has focus, take that text.
  216. search_buffer = buffer_control.search_buffer
  217. if search_buffer is not None and search_buffer.text:
  218. return search_buffer.text
  219. return ""
  220. class HighlightSelectionProcessor(Processor):
  221. """
  222. Processor that highlights the selection in the document.
  223. """
  224. def apply_transformation(
  225. self, transformation_input: TransformationInput
  226. ) -> Transformation:
  227. (
  228. buffer_control,
  229. document,
  230. lineno,
  231. source_to_display,
  232. fragments,
  233. _,
  234. _,
  235. ) = transformation_input.unpack()
  236. selected_fragment = " class:selected "
  237. # In case of selection, highlight all matches.
  238. selection_at_line = document.selection_range_at_line(lineno)
  239. if selection_at_line:
  240. from_, to = selection_at_line
  241. from_ = source_to_display(from_)
  242. to = source_to_display(to)
  243. fragments = explode_text_fragments(fragments)
  244. if from_ == 0 and to == 0 and len(fragments) == 0:
  245. # When this is an empty line, insert a space in order to
  246. # visualize the selection.
  247. return Transformation([(selected_fragment, " ")])
  248. else:
  249. for i in range(from_, to):
  250. if i < len(fragments):
  251. old_fragment, old_text, *_ = fragments[i]
  252. fragments[i] = (old_fragment + selected_fragment, old_text)
  253. elif i == len(fragments):
  254. fragments.append((selected_fragment, " "))
  255. return Transformation(fragments)
  256. class PasswordProcessor(Processor):
  257. """
  258. Processor that masks the input. (For passwords.)
  259. :param char: (string) Character to be used. "*" by default.
  260. """
  261. def __init__(self, char: str = "*") -> None:
  262. self.char = char
  263. def apply_transformation(self, ti: TransformationInput) -> Transformation:
  264. fragments: StyleAndTextTuples = cast(
  265. StyleAndTextTuples,
  266. [
  267. (style, self.char * len(text), *handler)
  268. for style, text, *handler in ti.fragments
  269. ],
  270. )
  271. return Transformation(fragments)
  272. class HighlightMatchingBracketProcessor(Processor):
  273. """
  274. When the cursor is on or right after a bracket, it highlights the matching
  275. bracket.
  276. :param max_cursor_distance: Only highlight matching brackets when the
  277. cursor is within this distance. (From inside a `Processor`, we can't
  278. know which lines will be visible on the screen. But we also don't want
  279. to scan the whole document for matching brackets on each key press, so
  280. we limit to this value.)
  281. """
  282. _closing_braces = "])}>"
  283. def __init__(
  284. self, chars: str = "[](){}<>", max_cursor_distance: int = 1000
  285. ) -> None:
  286. self.chars = chars
  287. self.max_cursor_distance = max_cursor_distance
  288. self._positions_cache: SimpleCache[Hashable, list[tuple[int, int]]] = (
  289. SimpleCache(maxsize=8)
  290. )
  291. def _get_positions_to_highlight(self, document: Document) -> list[tuple[int, int]]:
  292. """
  293. Return a list of (row, col) tuples that need to be highlighted.
  294. """
  295. pos: int | None
  296. # Try for the character under the cursor.
  297. if document.current_char and document.current_char in self.chars:
  298. pos = document.find_matching_bracket_position(
  299. start_pos=document.cursor_position - self.max_cursor_distance,
  300. end_pos=document.cursor_position + self.max_cursor_distance,
  301. )
  302. # Try for the character before the cursor.
  303. elif (
  304. document.char_before_cursor
  305. and document.char_before_cursor in self._closing_braces
  306. and document.char_before_cursor in self.chars
  307. ):
  308. document = Document(document.text, document.cursor_position - 1)
  309. pos = document.find_matching_bracket_position(
  310. start_pos=document.cursor_position - self.max_cursor_distance,
  311. end_pos=document.cursor_position + self.max_cursor_distance,
  312. )
  313. else:
  314. pos = None
  315. # Return a list of (row, col) tuples that need to be highlighted.
  316. if pos:
  317. pos += document.cursor_position # pos is relative.
  318. row, col = document.translate_index_to_position(pos)
  319. return [
  320. (row, col),
  321. (document.cursor_position_row, document.cursor_position_col),
  322. ]
  323. else:
  324. return []
  325. def apply_transformation(
  326. self, transformation_input: TransformationInput
  327. ) -> Transformation:
  328. (
  329. buffer_control,
  330. document,
  331. lineno,
  332. source_to_display,
  333. fragments,
  334. _,
  335. _,
  336. ) = transformation_input.unpack()
  337. # When the application is in the 'done' state, don't highlight.
  338. if get_app().is_done:
  339. return Transformation(fragments)
  340. # Get the highlight positions.
  341. key = (get_app().render_counter, document.text, document.cursor_position)
  342. positions = self._positions_cache.get(
  343. key, lambda: self._get_positions_to_highlight(document)
  344. )
  345. # Apply if positions were found at this line.
  346. if positions:
  347. for row, col in positions:
  348. if row == lineno:
  349. col = source_to_display(col)
  350. fragments = explode_text_fragments(fragments)
  351. style, text, *_ = fragments[col]
  352. if col == document.cursor_position_col:
  353. style += " class:matching-bracket.cursor "
  354. else:
  355. style += " class:matching-bracket.other "
  356. fragments[col] = (style, text)
  357. return Transformation(fragments)
  358. class DisplayMultipleCursors(Processor):
  359. """
  360. When we're in Vi block insert mode, display all the cursors.
  361. """
  362. def apply_transformation(
  363. self, transformation_input: TransformationInput
  364. ) -> Transformation:
  365. (
  366. buffer_control,
  367. document,
  368. lineno,
  369. source_to_display,
  370. fragments,
  371. _,
  372. _,
  373. ) = transformation_input.unpack()
  374. buff = buffer_control.buffer
  375. if vi_insert_multiple_mode():
  376. cursor_positions = buff.multiple_cursor_positions
  377. fragments = explode_text_fragments(fragments)
  378. # If any cursor appears on the current line, highlight that.
  379. start_pos = document.translate_row_col_to_index(lineno, 0)
  380. end_pos = start_pos + len(document.lines[lineno])
  381. fragment_suffix = " class:multiple-cursors"
  382. for p in cursor_positions:
  383. if start_pos <= p <= end_pos:
  384. column = source_to_display(p - start_pos)
  385. # Replace fragment.
  386. try:
  387. style, text, *_ = fragments[column]
  388. except IndexError:
  389. # Cursor needs to be displayed after the current text.
  390. fragments.append((fragment_suffix, " "))
  391. else:
  392. style += fragment_suffix
  393. fragments[column] = (style, text)
  394. return Transformation(fragments)
  395. else:
  396. return Transformation(fragments)
  397. class BeforeInput(Processor):
  398. """
  399. Insert text before the input.
  400. :param text: This can be either plain text or formatted text
  401. (or a callable that returns any of those).
  402. :param style: style to be applied to this prompt/prefix.
  403. """
  404. def __init__(self, text: AnyFormattedText, style: str = "") -> None:
  405. self.text = text
  406. self.style = style
  407. def apply_transformation(self, ti: TransformationInput) -> Transformation:
  408. source_to_display: SourceToDisplay | None
  409. display_to_source: DisplayToSource | None
  410. if ti.lineno == 0:
  411. # Get fragments.
  412. fragments_before = to_formatted_text(self.text, self.style)
  413. fragments = fragments_before + ti.fragments
  414. shift_position = fragment_list_len(fragments_before)
  415. source_to_display = lambda i: i + shift_position
  416. display_to_source = lambda i: i - shift_position
  417. else:
  418. fragments = ti.fragments
  419. source_to_display = None
  420. display_to_source = None
  421. return Transformation(
  422. fragments,
  423. source_to_display=source_to_display,
  424. display_to_source=display_to_source,
  425. )
  426. def __repr__(self) -> str:
  427. return f"BeforeInput({self.text!r}, {self.style!r})"
  428. class ShowArg(BeforeInput):
  429. """
  430. Display the 'arg' in front of the input.
  431. This was used by the `PromptSession`, but now it uses the
  432. `Window.get_line_prefix` function instead.
  433. """
  434. def __init__(self) -> None:
  435. super().__init__(self._get_text_fragments)
  436. def _get_text_fragments(self) -> StyleAndTextTuples:
  437. app = get_app()
  438. if app.key_processor.arg is None:
  439. return []
  440. else:
  441. arg = app.key_processor.arg
  442. return [
  443. ("class:prompt.arg", "(arg: "),
  444. ("class:prompt.arg.text", str(arg)),
  445. ("class:prompt.arg", ") "),
  446. ]
  447. def __repr__(self) -> str:
  448. return "ShowArg()"
  449. class AfterInput(Processor):
  450. """
  451. Insert text after the input.
  452. :param text: This can be either plain text or formatted text
  453. (or a callable that returns any of those).
  454. :param style: style to be applied to this prompt/prefix.
  455. """
  456. def __init__(self, text: AnyFormattedText, style: str = "") -> None:
  457. self.text = text
  458. self.style = style
  459. def apply_transformation(self, ti: TransformationInput) -> Transformation:
  460. # Insert fragments after the last line.
  461. if ti.lineno == ti.document.line_count - 1:
  462. # Get fragments.
  463. fragments_after = to_formatted_text(self.text, self.style)
  464. return Transformation(fragments=ti.fragments + fragments_after)
  465. else:
  466. return Transformation(fragments=ti.fragments)
  467. def __repr__(self) -> str:
  468. return f"{self.__class__.__name__}({self.text!r}, style={self.style!r})"
  469. class AppendAutoSuggestion(Processor):
  470. """
  471. Append the auto suggestion to the input.
  472. (The user can then press the right arrow the insert the suggestion.)
  473. """
  474. def __init__(self, style: str = "class:auto-suggestion") -> None:
  475. self.style = style
  476. def apply_transformation(self, ti: TransformationInput) -> Transformation:
  477. # Insert fragments after the last line.
  478. if ti.lineno == ti.document.line_count - 1:
  479. buffer = ti.buffer_control.buffer
  480. if buffer.suggestion and ti.document.is_cursor_at_the_end:
  481. suggestion = buffer.suggestion.text
  482. else:
  483. suggestion = ""
  484. return Transformation(fragments=ti.fragments + [(self.style, suggestion)])
  485. else:
  486. return Transformation(fragments=ti.fragments)
  487. class ShowLeadingWhiteSpaceProcessor(Processor):
  488. """
  489. Make leading whitespace visible.
  490. :param get_char: Callable that returns one character.
  491. """
  492. def __init__(
  493. self,
  494. get_char: Callable[[], str] | None = None,
  495. style: str = "class:leading-whitespace",
  496. ) -> None:
  497. def default_get_char() -> str:
  498. if "\xb7".encode(get_app().output.encoding(), "replace") == b"?":
  499. return "."
  500. else:
  501. return "\xb7"
  502. self.style = style
  503. self.get_char = get_char or default_get_char
  504. def apply_transformation(self, ti: TransformationInput) -> Transformation:
  505. fragments = ti.fragments
  506. # Walk through all te fragments.
  507. if fragments and fragment_list_to_text(fragments).startswith(" "):
  508. t = (self.style, self.get_char())
  509. fragments = explode_text_fragments(fragments)
  510. for i in range(len(fragments)):
  511. if fragments[i][1] == " ":
  512. fragments[i] = t
  513. else:
  514. break
  515. return Transformation(fragments)
  516. class ShowTrailingWhiteSpaceProcessor(Processor):
  517. """
  518. Make trailing whitespace visible.
  519. :param get_char: Callable that returns one character.
  520. """
  521. def __init__(
  522. self,
  523. get_char: Callable[[], str] | None = None,
  524. style: str = "class:training-whitespace",
  525. ) -> None:
  526. def default_get_char() -> str:
  527. if "\xb7".encode(get_app().output.encoding(), "replace") == b"?":
  528. return "."
  529. else:
  530. return "\xb7"
  531. self.style = style
  532. self.get_char = get_char or default_get_char
  533. def apply_transformation(self, ti: TransformationInput) -> Transformation:
  534. fragments = ti.fragments
  535. if fragments and fragments[-1][1].endswith(" "):
  536. t = (self.style, self.get_char())
  537. fragments = explode_text_fragments(fragments)
  538. # Walk backwards through all te fragments and replace whitespace.
  539. for i in range(len(fragments) - 1, -1, -1):
  540. char = fragments[i][1]
  541. if char == " ":
  542. fragments[i] = t
  543. else:
  544. break
  545. return Transformation(fragments)
  546. class TabsProcessor(Processor):
  547. """
  548. Render tabs as spaces (instead of ^I) or make them visible (for instance,
  549. by replacing them with dots.)
  550. :param tabstop: Horizontal space taken by a tab. (`int` or callable that
  551. returns an `int`).
  552. :param char1: Character or callable that returns a character (text of
  553. length one). This one is used for the first space taken by the tab.
  554. :param char2: Like `char1`, but for the rest of the space.
  555. """
  556. def __init__(
  557. self,
  558. tabstop: int | Callable[[], int] = 4,
  559. char1: str | Callable[[], str] = "|",
  560. char2: str | Callable[[], str] = "\u2508",
  561. style: str = "class:tab",
  562. ) -> None:
  563. self.char1 = char1
  564. self.char2 = char2
  565. self.tabstop = tabstop
  566. self.style = style
  567. def apply_transformation(self, ti: TransformationInput) -> Transformation:
  568. tabstop = to_int(self.tabstop)
  569. style = self.style
  570. # Create separator for tabs.
  571. separator1 = to_str(self.char1)
  572. separator2 = to_str(self.char2)
  573. # Transform fragments.
  574. fragments = explode_text_fragments(ti.fragments)
  575. position_mappings = {}
  576. result_fragments: StyleAndTextTuples = []
  577. pos = 0
  578. for i, fragment_and_text in enumerate(fragments):
  579. position_mappings[i] = pos
  580. if fragment_and_text[1] == "\t":
  581. # Calculate how many characters we have to insert.
  582. count = tabstop - (pos % tabstop)
  583. if count == 0:
  584. count = tabstop
  585. # Insert tab.
  586. result_fragments.append((style, separator1))
  587. result_fragments.append((style, separator2 * (count - 1)))
  588. pos += count
  589. else:
  590. result_fragments.append(fragment_and_text)
  591. pos += 1
  592. position_mappings[len(fragments)] = pos
  593. # Add `pos+1` to mapping, because the cursor can be right after the
  594. # line as well.
  595. position_mappings[len(fragments) + 1] = pos + 1
  596. def source_to_display(from_position: int) -> int:
  597. "Maps original cursor position to the new one."
  598. return position_mappings[from_position]
  599. def display_to_source(display_pos: int) -> int:
  600. "Maps display cursor position to the original one."
  601. position_mappings_reversed = {v: k for k, v in position_mappings.items()}
  602. while display_pos >= 0:
  603. try:
  604. return position_mappings_reversed[display_pos]
  605. except KeyError:
  606. display_pos -= 1
  607. return 0
  608. return Transformation(
  609. result_fragments,
  610. source_to_display=source_to_display,
  611. display_to_source=display_to_source,
  612. )
  613. class ReverseSearchProcessor(Processor):
  614. """
  615. Process to display the "(reverse-i-search)`...`:..." stuff around
  616. the search buffer.
  617. Note: This processor is meant to be applied to the BufferControl that
  618. contains the search buffer, it's not meant for the original input.
  619. """
  620. _excluded_input_processors: list[type[Processor]] = [
  621. HighlightSearchProcessor,
  622. HighlightSelectionProcessor,
  623. BeforeInput,
  624. AfterInput,
  625. ]
  626. def _get_main_buffer(self, buffer_control: BufferControl) -> BufferControl | None:
  627. from prompt_toolkit.layout.controls import BufferControl
  628. prev_control = get_app().layout.search_target_buffer_control
  629. if (
  630. isinstance(prev_control, BufferControl)
  631. and prev_control.search_buffer_control == buffer_control
  632. ):
  633. return prev_control
  634. return None
  635. def _content(
  636. self, main_control: BufferControl, ti: TransformationInput
  637. ) -> UIContent:
  638. from prompt_toolkit.layout.controls import BufferControl
  639. # Emulate the BufferControl through which we are searching.
  640. # For this we filter out some of the input processors.
  641. excluded_processors = tuple(self._excluded_input_processors)
  642. def filter_processor(item: Processor) -> Processor | None:
  643. """Filter processors from the main control that we want to disable
  644. here. This returns either an accepted processor or None."""
  645. # For a `_MergedProcessor`, check each individual processor, recursively.
  646. if isinstance(item, _MergedProcessor):
  647. accepted_processors = [filter_processor(p) for p in item.processors]
  648. return merge_processors(
  649. [p for p in accepted_processors if p is not None]
  650. )
  651. # For a `ConditionalProcessor`, check the body.
  652. elif isinstance(item, ConditionalProcessor):
  653. p = filter_processor(item.processor)
  654. if p:
  655. return ConditionalProcessor(p, item.filter)
  656. # Otherwise, check the processor itself.
  657. else:
  658. if not isinstance(item, excluded_processors):
  659. return item
  660. return None
  661. filtered_processor = filter_processor(
  662. merge_processors(main_control.input_processors or [])
  663. )
  664. highlight_processor = HighlightIncrementalSearchProcessor()
  665. if filtered_processor:
  666. new_processors = [filtered_processor, highlight_processor]
  667. else:
  668. new_processors = [highlight_processor]
  669. from .controls import SearchBufferControl
  670. assert isinstance(ti.buffer_control, SearchBufferControl)
  671. buffer_control = BufferControl(
  672. buffer=main_control.buffer,
  673. input_processors=new_processors,
  674. include_default_input_processors=False,
  675. lexer=main_control.lexer,
  676. preview_search=True,
  677. search_buffer_control=ti.buffer_control,
  678. )
  679. return buffer_control.create_content(ti.width, ti.height, preview_search=True)
  680. def apply_transformation(self, ti: TransformationInput) -> Transformation:
  681. from .controls import SearchBufferControl
  682. assert isinstance(ti.buffer_control, SearchBufferControl), (
  683. "`ReverseSearchProcessor` should be applied to a `SearchBufferControl` only."
  684. )
  685. source_to_display: SourceToDisplay | None
  686. display_to_source: DisplayToSource | None
  687. main_control = self._get_main_buffer(ti.buffer_control)
  688. if ti.lineno == 0 and main_control:
  689. content = self._content(main_control, ti)
  690. # Get the line from the original document for this search.
  691. line_fragments = content.get_line(content.cursor_position.y)
  692. if main_control.search_state.direction == SearchDirection.FORWARD:
  693. direction_text = "i-search"
  694. else:
  695. direction_text = "reverse-i-search"
  696. fragments_before: StyleAndTextTuples = [
  697. ("class:prompt.search", "("),
  698. ("class:prompt.search", direction_text),
  699. ("class:prompt.search", ")`"),
  700. ]
  701. fragments = (
  702. fragments_before
  703. + [
  704. ("class:prompt.search.text", fragment_list_to_text(ti.fragments)),
  705. ("", "': "),
  706. ]
  707. + line_fragments
  708. )
  709. shift_position = fragment_list_len(fragments_before)
  710. source_to_display = lambda i: i + shift_position
  711. display_to_source = lambda i: i - shift_position
  712. else:
  713. source_to_display = None
  714. display_to_source = None
  715. fragments = ti.fragments
  716. return Transformation(
  717. fragments,
  718. source_to_display=source_to_display,
  719. display_to_source=display_to_source,
  720. )
  721. class ConditionalProcessor(Processor):
  722. """
  723. Processor that applies another processor, according to a certain condition.
  724. Example::
  725. # Create a function that returns whether or not the processor should
  726. # currently be applied.
  727. def highlight_enabled():
  728. return true_or_false
  729. # Wrapped it in a `ConditionalProcessor` for usage in a `BufferControl`.
  730. BufferControl(input_processors=[
  731. ConditionalProcessor(HighlightSearchProcessor(),
  732. Condition(highlight_enabled))])
  733. :param processor: :class:`.Processor` instance.
  734. :param filter: :class:`~prompt_toolkit.filters.Filter` instance.
  735. """
  736. def __init__(self, processor: Processor, filter: FilterOrBool) -> None:
  737. self.processor = processor
  738. self.filter = to_filter(filter)
  739. def apply_transformation(
  740. self, transformation_input: TransformationInput
  741. ) -> Transformation:
  742. # Run processor when enabled.
  743. if self.filter():
  744. return self.processor.apply_transformation(transformation_input)
  745. else:
  746. return Transformation(transformation_input.fragments)
  747. def __repr__(self) -> str:
  748. return f"{self.__class__.__name__}(processor={self.processor!r}, filter={self.filter!r})"
  749. class DynamicProcessor(Processor):
  750. """
  751. Processor class that dynamically returns any Processor.
  752. :param get_processor: Callable that returns a :class:`.Processor` instance.
  753. """
  754. def __init__(self, get_processor: Callable[[], Processor | None]) -> None:
  755. self.get_processor = get_processor
  756. def apply_transformation(self, ti: TransformationInput) -> Transformation:
  757. processor = self.get_processor() or DummyProcessor()
  758. return processor.apply_transformation(ti)
  759. def merge_processors(processors: list[Processor]) -> Processor:
  760. """
  761. Merge multiple `Processor` objects into one.
  762. """
  763. if len(processors) == 0:
  764. return DummyProcessor()
  765. if len(processors) == 1:
  766. return processors[0] # Nothing to merge.
  767. return _MergedProcessor(processors)
  768. class _MergedProcessor(Processor):
  769. """
  770. Processor that groups multiple other `Processor` objects, but exposes an
  771. API as if it is one `Processor`.
  772. """
  773. def __init__(self, processors: list[Processor]):
  774. self.processors = processors
  775. def apply_transformation(self, ti: TransformationInput) -> Transformation:
  776. source_to_display_functions = [ti.source_to_display]
  777. display_to_source_functions = []
  778. fragments = ti.fragments
  779. def source_to_display(i: int) -> int:
  780. """Translate x position from the buffer to the x position in the
  781. processor fragments list."""
  782. for f in source_to_display_functions:
  783. i = f(i)
  784. return i
  785. for p in self.processors:
  786. transformation = p.apply_transformation(
  787. TransformationInput(
  788. ti.buffer_control,
  789. ti.document,
  790. ti.lineno,
  791. source_to_display,
  792. fragments,
  793. ti.width,
  794. ti.height,
  795. ti.get_line,
  796. )
  797. )
  798. fragments = transformation.fragments
  799. display_to_source_functions.append(transformation.display_to_source)
  800. source_to_display_functions.append(transformation.source_to_display)
  801. def display_to_source(i: int) -> int:
  802. for f in reversed(display_to_source_functions):
  803. i = f(i)
  804. return i
  805. # In the case of a nested _MergedProcessor, each processor wants to
  806. # receive a 'source_to_display' function (as part of the
  807. # TransformationInput) that has everything in the chain before
  808. # included, because it can be called as part of the
  809. # `apply_transformation` function. However, this first
  810. # `source_to_display` should not be part of the output that we are
  811. # returning. (This is the most consistent with `display_to_source`.)
  812. del source_to_display_functions[:1]
  813. return Transformation(fragments, source_to_display, display_to_source)