margins.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. """
  2. Margin implementations for a :class:`~prompt_toolkit.layout.containers.Window`.
  3. """
  4. from __future__ import annotations
  5. from abc import ABCMeta, abstractmethod
  6. from typing import TYPE_CHECKING, Callable
  7. from prompt_toolkit.filters import FilterOrBool, to_filter
  8. from prompt_toolkit.formatted_text import (
  9. StyleAndTextTuples,
  10. fragment_list_to_text,
  11. to_formatted_text,
  12. )
  13. from prompt_toolkit.utils import get_cwidth
  14. from .controls import UIContent
  15. if TYPE_CHECKING:
  16. from .containers import WindowRenderInfo
  17. __all__ = [
  18. "Margin",
  19. "NumberedMargin",
  20. "ScrollbarMargin",
  21. "ConditionalMargin",
  22. "PromptMargin",
  23. ]
  24. class Margin(metaclass=ABCMeta):
  25. """
  26. Base interface for a margin.
  27. """
  28. @abstractmethod
  29. def get_width(self, get_ui_content: Callable[[], UIContent]) -> int:
  30. """
  31. Return the width that this margin is going to consume.
  32. :param get_ui_content: Callable that asks the user control to create
  33. a :class:`.UIContent` instance. This can be used for instance to
  34. obtain the number of lines.
  35. """
  36. return 0
  37. @abstractmethod
  38. def create_margin(
  39. self, window_render_info: WindowRenderInfo, width: int, height: int
  40. ) -> StyleAndTextTuples:
  41. """
  42. Creates a margin.
  43. This should return a list of (style_str, text) tuples.
  44. :param window_render_info:
  45. :class:`~prompt_toolkit.layout.containers.WindowRenderInfo`
  46. instance, generated after rendering and copying the visible part of
  47. the :class:`~prompt_toolkit.layout.controls.UIControl` into the
  48. :class:`~prompt_toolkit.layout.containers.Window`.
  49. :param width: The width that's available for this margin. (As reported
  50. by :meth:`.get_width`.)
  51. :param height: The height that's available for this margin. (The height
  52. of the :class:`~prompt_toolkit.layout.containers.Window`.)
  53. """
  54. return []
  55. class NumberedMargin(Margin):
  56. """
  57. Margin that displays the line numbers.
  58. :param relative: Number relative to the cursor position. Similar to the Vi
  59. 'relativenumber' option.
  60. :param display_tildes: Display tildes after the end of the document, just
  61. like Vi does.
  62. """
  63. def __init__(
  64. self, relative: FilterOrBool = False, display_tildes: FilterOrBool = False
  65. ) -> None:
  66. self.relative = to_filter(relative)
  67. self.display_tildes = to_filter(display_tildes)
  68. def get_width(self, get_ui_content: Callable[[], UIContent]) -> int:
  69. line_count = get_ui_content().line_count
  70. return max(3, len(f"{line_count}") + 1)
  71. def create_margin(
  72. self, window_render_info: WindowRenderInfo, width: int, height: int
  73. ) -> StyleAndTextTuples:
  74. relative = self.relative()
  75. style = "class:line-number"
  76. style_current = "class:line-number.current"
  77. # Get current line number.
  78. current_lineno = window_render_info.ui_content.cursor_position.y
  79. # Construct margin.
  80. result: StyleAndTextTuples = []
  81. last_lineno = None
  82. for y, lineno in enumerate(window_render_info.displayed_lines):
  83. # Only display line number if this line is not a continuation of the previous line.
  84. if lineno != last_lineno:
  85. if lineno is None:
  86. pass
  87. elif lineno == current_lineno:
  88. # Current line.
  89. if relative:
  90. # Left align current number in relative mode.
  91. result.append((style_current, "%i" % (lineno + 1)))
  92. else:
  93. result.append(
  94. (style_current, ("%i " % (lineno + 1)).rjust(width))
  95. )
  96. else:
  97. # Other lines.
  98. if relative:
  99. lineno = abs(lineno - current_lineno) - 1
  100. result.append((style, ("%i " % (lineno + 1)).rjust(width)))
  101. last_lineno = lineno
  102. result.append(("", "\n"))
  103. # Fill with tildes.
  104. if self.display_tildes():
  105. while y < window_render_info.window_height:
  106. result.append(("class:tilde", "~\n"))
  107. y += 1
  108. return result
  109. class ConditionalMargin(Margin):
  110. """
  111. Wrapper around other :class:`.Margin` classes to show/hide them.
  112. """
  113. def __init__(self, margin: Margin, filter: FilterOrBool) -> None:
  114. self.margin = margin
  115. self.filter = to_filter(filter)
  116. def get_width(self, get_ui_content: Callable[[], UIContent]) -> int:
  117. if self.filter():
  118. return self.margin.get_width(get_ui_content)
  119. else:
  120. return 0
  121. def create_margin(
  122. self, window_render_info: WindowRenderInfo, width: int, height: int
  123. ) -> StyleAndTextTuples:
  124. if width and self.filter():
  125. return self.margin.create_margin(window_render_info, width, height)
  126. else:
  127. return []
  128. class ScrollbarMargin(Margin):
  129. """
  130. Margin displaying a scrollbar.
  131. :param display_arrows: Display scroll up/down arrows.
  132. """
  133. def __init__(
  134. self,
  135. display_arrows: FilterOrBool = False,
  136. up_arrow_symbol: str = "^",
  137. down_arrow_symbol: str = "v",
  138. ) -> None:
  139. self.display_arrows = to_filter(display_arrows)
  140. self.up_arrow_symbol = up_arrow_symbol
  141. self.down_arrow_symbol = down_arrow_symbol
  142. def get_width(self, get_ui_content: Callable[[], UIContent]) -> int:
  143. return 1
  144. def create_margin(
  145. self, window_render_info: WindowRenderInfo, width: int, height: int
  146. ) -> StyleAndTextTuples:
  147. content_height = window_render_info.content_height
  148. window_height = window_render_info.window_height
  149. display_arrows = self.display_arrows()
  150. if display_arrows:
  151. window_height -= 2
  152. try:
  153. fraction_visible = len(window_render_info.displayed_lines) / float(
  154. content_height
  155. )
  156. fraction_above = window_render_info.vertical_scroll / float(content_height)
  157. scrollbar_height = int(
  158. min(window_height, max(1, window_height * fraction_visible))
  159. )
  160. scrollbar_top = int(window_height * fraction_above)
  161. except ZeroDivisionError:
  162. return []
  163. else:
  164. def is_scroll_button(row: int) -> bool:
  165. "True if we should display a button on this row."
  166. return scrollbar_top <= row <= scrollbar_top + scrollbar_height
  167. # Up arrow.
  168. result: StyleAndTextTuples = []
  169. if display_arrows:
  170. result.extend(
  171. [
  172. ("class:scrollbar.arrow", self.up_arrow_symbol),
  173. ("class:scrollbar", "\n"),
  174. ]
  175. )
  176. # Scrollbar body.
  177. scrollbar_background = "class:scrollbar.background"
  178. scrollbar_background_start = "class:scrollbar.background,scrollbar.start"
  179. scrollbar_button = "class:scrollbar.button"
  180. scrollbar_button_end = "class:scrollbar.button,scrollbar.end"
  181. for i in range(window_height):
  182. if is_scroll_button(i):
  183. if not is_scroll_button(i + 1):
  184. # Give the last cell a different style, because we
  185. # want to underline this.
  186. result.append((scrollbar_button_end, " "))
  187. else:
  188. result.append((scrollbar_button, " "))
  189. else:
  190. if is_scroll_button(i + 1):
  191. result.append((scrollbar_background_start, " "))
  192. else:
  193. result.append((scrollbar_background, " "))
  194. result.append(("", "\n"))
  195. # Down arrow
  196. if display_arrows:
  197. result.append(("class:scrollbar.arrow", self.down_arrow_symbol))
  198. return result
  199. class PromptMargin(Margin):
  200. """
  201. [Deprecated]
  202. Create margin that displays a prompt.
  203. This can display one prompt at the first line, and a continuation prompt
  204. (e.g, just dots) on all the following lines.
  205. This `PromptMargin` implementation has been largely superseded in favor of
  206. the `get_line_prefix` attribute of `Window`. The reason is that a margin is
  207. always a fixed width, while `get_line_prefix` can return a variable width
  208. prefix in front of every line, making it more powerful, especially for line
  209. continuations.
  210. :param get_prompt: Callable returns formatted text or a list of
  211. `(style_str, type)` tuples to be shown as the prompt at the first line.
  212. :param get_continuation: Callable that takes three inputs. The width (int),
  213. line_number (int), and is_soft_wrap (bool). It should return formatted
  214. text or a list of `(style_str, type)` tuples for the next lines of the
  215. input.
  216. """
  217. def __init__(
  218. self,
  219. get_prompt: Callable[[], StyleAndTextTuples],
  220. get_continuation: None
  221. | (Callable[[int, int, bool], StyleAndTextTuples]) = None,
  222. ) -> None:
  223. self.get_prompt = get_prompt
  224. self.get_continuation = get_continuation
  225. def get_width(self, get_ui_content: Callable[[], UIContent]) -> int:
  226. "Width to report to the `Window`."
  227. # Take the width from the first line.
  228. text = fragment_list_to_text(self.get_prompt())
  229. return get_cwidth(text)
  230. def create_margin(
  231. self, window_render_info: WindowRenderInfo, width: int, height: int
  232. ) -> StyleAndTextTuples:
  233. get_continuation = self.get_continuation
  234. result: StyleAndTextTuples = []
  235. # First line.
  236. result.extend(to_formatted_text(self.get_prompt()))
  237. # Next lines.
  238. if get_continuation:
  239. last_y = None
  240. for y in window_render_info.displayed_lines[1:]:
  241. result.append(("", "\n"))
  242. result.extend(
  243. to_formatted_text(get_continuation(width, y, y == last_y))
  244. )
  245. last_y = y
  246. return result