processors.py 33 KB

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