search.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. """
  2. Search operations.
  3. For the key bindings implementation with attached filters, check
  4. `prompt_toolkit.key_binding.bindings.search`. (Use these for new key bindings
  5. instead of calling these function directly.)
  6. """
  7. from __future__ import annotations
  8. from enum import Enum
  9. from typing import TYPE_CHECKING
  10. from .application.current import get_app
  11. from .filters import FilterOrBool, is_searching, to_filter
  12. from .key_binding.vi_state import InputMode
  13. if TYPE_CHECKING:
  14. from prompt_toolkit.layout.controls import BufferControl, SearchBufferControl
  15. from prompt_toolkit.layout.layout import Layout
  16. __all__ = [
  17. "SearchDirection",
  18. "start_search",
  19. "stop_search",
  20. ]
  21. class SearchDirection(Enum):
  22. FORWARD = "FORWARD"
  23. BACKWARD = "BACKWARD"
  24. class SearchState:
  25. """
  26. A search 'query', associated with a search field (like a SearchToolbar).
  27. Every searchable `BufferControl` points to a `search_buffer_control`
  28. (another `BufferControls`) which represents the search field. The
  29. `SearchState` attached to that search field is used for storing the current
  30. search query.
  31. It is possible to have one searchfield for multiple `BufferControls`. In
  32. that case, they'll share the same `SearchState`.
  33. If there are multiple `BufferControls` that display the same `Buffer`, then
  34. they can have a different `SearchState` each (if they have a different
  35. search control).
  36. """
  37. __slots__ = ("text", "direction", "ignore_case")
  38. def __init__(
  39. self,
  40. text: str = "",
  41. direction: SearchDirection = SearchDirection.FORWARD,
  42. ignore_case: FilterOrBool = False,
  43. ) -> None:
  44. self.text = text
  45. self.direction = direction
  46. self.ignore_case = to_filter(ignore_case)
  47. def __repr__(self) -> str:
  48. return f"{self.__class__.__name__}({self.text!r}, direction={self.direction!r}, ignore_case={self.ignore_case!r})"
  49. def __invert__(self) -> SearchState:
  50. """
  51. Create a new SearchState where backwards becomes forwards and the other
  52. way around.
  53. """
  54. if self.direction == SearchDirection.BACKWARD:
  55. direction = SearchDirection.FORWARD
  56. else:
  57. direction = SearchDirection.BACKWARD
  58. return SearchState(
  59. text=self.text, direction=direction, ignore_case=self.ignore_case
  60. )
  61. def start_search(
  62. buffer_control: BufferControl | None = None,
  63. direction: SearchDirection = SearchDirection.FORWARD,
  64. ) -> None:
  65. """
  66. Start search through the given `buffer_control` using the
  67. `search_buffer_control`.
  68. :param buffer_control: Start search for this `BufferControl`. If not given,
  69. search through the current control.
  70. """
  71. from prompt_toolkit.layout.controls import BufferControl
  72. assert buffer_control is None or isinstance(buffer_control, BufferControl)
  73. layout = get_app().layout
  74. # When no control is given, use the current control if that's a BufferControl.
  75. if buffer_control is None:
  76. if not isinstance(layout.current_control, BufferControl):
  77. return
  78. buffer_control = layout.current_control
  79. # Only if this control is searchable.
  80. search_buffer_control = buffer_control.search_buffer_control
  81. if search_buffer_control:
  82. buffer_control.search_state.direction = direction
  83. # Make sure to focus the search BufferControl
  84. layout.focus(search_buffer_control)
  85. # Remember search link.
  86. layout.search_links[search_buffer_control] = buffer_control
  87. # If we're in Vi mode, make sure to go into insert mode.
  88. get_app().vi_state.input_mode = InputMode.INSERT
  89. def stop_search(buffer_control: BufferControl | None = None) -> None:
  90. """
  91. Stop search through the given `buffer_control`.
  92. """
  93. layout = get_app().layout
  94. if buffer_control is None:
  95. buffer_control = layout.search_target_buffer_control
  96. if buffer_control is None:
  97. # (Should not happen, but possible when `stop_search` is called
  98. # when we're not searching.)
  99. return
  100. search_buffer_control = buffer_control.search_buffer_control
  101. else:
  102. assert buffer_control in layout.search_links.values()
  103. search_buffer_control = _get_reverse_search_links(layout)[buffer_control]
  104. # Focus the original buffer again.
  105. layout.focus(buffer_control)
  106. if search_buffer_control is not None:
  107. # Remove the search link.
  108. del layout.search_links[search_buffer_control]
  109. # Reset content of search control.
  110. search_buffer_control.buffer.reset()
  111. # If we're in Vi mode, go back to navigation mode.
  112. get_app().vi_state.input_mode = InputMode.NAVIGATION
  113. def do_incremental_search(direction: SearchDirection, count: int = 1) -> None:
  114. """
  115. Apply search, but keep search buffer focused.
  116. """
  117. assert is_searching()
  118. layout = get_app().layout
  119. # Only search if the current control is a `BufferControl`.
  120. from prompt_toolkit.layout.controls import BufferControl
  121. search_control = layout.current_control
  122. if not isinstance(search_control, BufferControl):
  123. return
  124. prev_control = layout.search_target_buffer_control
  125. if prev_control is None:
  126. return
  127. search_state = prev_control.search_state
  128. # Update search_state.
  129. direction_changed = search_state.direction != direction
  130. search_state.text = search_control.buffer.text
  131. search_state.direction = direction
  132. # Apply search to current buffer.
  133. if not direction_changed:
  134. prev_control.buffer.apply_search(
  135. search_state, include_current_position=False, count=count
  136. )
  137. def accept_search() -> None:
  138. """
  139. Accept current search query. Focus original `BufferControl` again.
  140. """
  141. layout = get_app().layout
  142. search_control = layout.current_control
  143. target_buffer_control = layout.search_target_buffer_control
  144. from prompt_toolkit.layout.controls import BufferControl
  145. if not isinstance(search_control, BufferControl):
  146. return
  147. if target_buffer_control is None:
  148. return
  149. search_state = target_buffer_control.search_state
  150. # Update search state.
  151. if search_control.buffer.text:
  152. search_state.text = search_control.buffer.text
  153. # Apply search.
  154. target_buffer_control.buffer.apply_search(
  155. search_state, include_current_position=True
  156. )
  157. # Add query to history of search line.
  158. search_control.buffer.append_to_history()
  159. # Stop search and focus previous control again.
  160. stop_search(target_buffer_control)
  161. def _get_reverse_search_links(
  162. layout: Layout,
  163. ) -> dict[BufferControl, SearchBufferControl]:
  164. """
  165. Return mapping from BufferControl to SearchBufferControl.
  166. """
  167. return {
  168. buffer_control: search_buffer_control
  169. for search_buffer_control, buffer_control in layout.search_links.items()
  170. }