prompt.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  1. """
  2. Line editing functionality.
  3. ---------------------------
  4. This provides a UI for a line input, similar to GNU Readline, libedit and
  5. linenoise.
  6. Either call the `prompt` function for every line input. Or create an instance
  7. of the :class:`.PromptSession` class and call the `prompt` method from that
  8. class. In the second case, we'll have a 'session' that keeps all the state like
  9. the history in between several calls.
  10. There is a lot of overlap between the arguments taken by the `prompt` function
  11. and the `PromptSession` (like `completer`, `style`, etcetera). There we have
  12. the freedom to decide which settings we want for the whole 'session', and which
  13. we want for an individual `prompt`.
  14. Example::
  15. # Simple `prompt` call.
  16. result = prompt('Say something: ')
  17. # Using a 'session'.
  18. s = PromptSession()
  19. result = s.prompt('Say something: ')
  20. """
  21. from __future__ import annotations
  22. from asyncio import get_running_loop
  23. from contextlib import contextmanager
  24. from enum import Enum
  25. from functools import partial
  26. from typing import TYPE_CHECKING, Callable, Generic, Iterator, TypeVar, Union, cast
  27. from prompt_toolkit.application import Application
  28. from prompt_toolkit.application.current import get_app
  29. from prompt_toolkit.auto_suggest import AutoSuggest, DynamicAutoSuggest
  30. from prompt_toolkit.buffer import Buffer
  31. from prompt_toolkit.clipboard import Clipboard, DynamicClipboard, InMemoryClipboard
  32. from prompt_toolkit.completion import Completer, DynamicCompleter, ThreadedCompleter
  33. from prompt_toolkit.cursor_shapes import (
  34. AnyCursorShapeConfig,
  35. CursorShapeConfig,
  36. DynamicCursorShapeConfig,
  37. )
  38. from prompt_toolkit.document import Document
  39. from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode
  40. from prompt_toolkit.eventloop import InputHook
  41. from prompt_toolkit.filters import (
  42. Condition,
  43. FilterOrBool,
  44. has_arg,
  45. has_focus,
  46. is_done,
  47. is_true,
  48. renderer_height_is_known,
  49. to_filter,
  50. )
  51. from prompt_toolkit.formatted_text import (
  52. AnyFormattedText,
  53. StyleAndTextTuples,
  54. fragment_list_to_text,
  55. merge_formatted_text,
  56. to_formatted_text,
  57. )
  58. from prompt_toolkit.history import History, InMemoryHistory
  59. from prompt_toolkit.input.base import Input
  60. from prompt_toolkit.key_binding.bindings.auto_suggest import load_auto_suggest_bindings
  61. from prompt_toolkit.key_binding.bindings.completion import (
  62. display_completions_like_readline,
  63. )
  64. from prompt_toolkit.key_binding.bindings.open_in_editor import (
  65. load_open_in_editor_bindings,
  66. )
  67. from prompt_toolkit.key_binding.key_bindings import (
  68. ConditionalKeyBindings,
  69. DynamicKeyBindings,
  70. KeyBindings,
  71. KeyBindingsBase,
  72. merge_key_bindings,
  73. )
  74. from prompt_toolkit.key_binding.key_processor import KeyPressEvent
  75. from prompt_toolkit.keys import Keys
  76. from prompt_toolkit.layout import Float, FloatContainer, HSplit, Window
  77. from prompt_toolkit.layout.containers import ConditionalContainer, WindowAlign
  78. from prompt_toolkit.layout.controls import (
  79. BufferControl,
  80. FormattedTextControl,
  81. SearchBufferControl,
  82. )
  83. from prompt_toolkit.layout.dimension import Dimension
  84. from prompt_toolkit.layout.layout import Layout
  85. from prompt_toolkit.layout.menus import CompletionsMenu, MultiColumnCompletionsMenu
  86. from prompt_toolkit.layout.processors import (
  87. AfterInput,
  88. AppendAutoSuggestion,
  89. ConditionalProcessor,
  90. DisplayMultipleCursors,
  91. DynamicProcessor,
  92. HighlightIncrementalSearchProcessor,
  93. HighlightSelectionProcessor,
  94. PasswordProcessor,
  95. Processor,
  96. ReverseSearchProcessor,
  97. merge_processors,
  98. )
  99. from prompt_toolkit.layout.utils import explode_text_fragments
  100. from prompt_toolkit.lexers import DynamicLexer, Lexer
  101. from prompt_toolkit.output import ColorDepth, DummyOutput, Output
  102. from prompt_toolkit.styles import (
  103. BaseStyle,
  104. ConditionalStyleTransformation,
  105. DynamicStyle,
  106. DynamicStyleTransformation,
  107. StyleTransformation,
  108. SwapLightAndDarkStyleTransformation,
  109. merge_style_transformations,
  110. )
  111. from prompt_toolkit.utils import (
  112. get_cwidth,
  113. is_dumb_terminal,
  114. suspend_to_background_supported,
  115. to_str,
  116. )
  117. from prompt_toolkit.validation import DynamicValidator, Validator
  118. from prompt_toolkit.widgets import Frame
  119. from prompt_toolkit.widgets.toolbars import (
  120. SearchToolbar,
  121. SystemToolbar,
  122. ValidationToolbar,
  123. )
  124. if TYPE_CHECKING:
  125. from prompt_toolkit.formatted_text.base import MagicFormattedText
  126. __all__ = [
  127. "PromptSession",
  128. "prompt",
  129. "confirm",
  130. "create_confirm_session", # Used by '_display_completions_like_readline'.
  131. "CompleteStyle",
  132. ]
  133. _StyleAndTextTuplesCallable = Callable[[], StyleAndTextTuples]
  134. E = KeyPressEvent
  135. def _split_multiline_prompt(
  136. get_prompt_text: _StyleAndTextTuplesCallable,
  137. ) -> tuple[
  138. Callable[[], bool], _StyleAndTextTuplesCallable, _StyleAndTextTuplesCallable
  139. ]:
  140. """
  141. Take a `get_prompt_text` function and return three new functions instead.
  142. One that tells whether this prompt consists of multiple lines; one that
  143. returns the fragments to be shown on the lines above the input; and another
  144. one with the fragments to be shown at the first line of the input.
  145. """
  146. def has_before_fragments() -> bool:
  147. for fragment, char, *_ in get_prompt_text():
  148. if "\n" in char:
  149. return True
  150. return False
  151. def before() -> StyleAndTextTuples:
  152. result: StyleAndTextTuples = []
  153. found_nl = False
  154. for fragment, char, *_ in reversed(explode_text_fragments(get_prompt_text())):
  155. if found_nl:
  156. result.insert(0, (fragment, char))
  157. elif char == "\n":
  158. found_nl = True
  159. return result
  160. def first_input_line() -> StyleAndTextTuples:
  161. result: StyleAndTextTuples = []
  162. for fragment, char, *_ in reversed(explode_text_fragments(get_prompt_text())):
  163. if char == "\n":
  164. break
  165. else:
  166. result.insert(0, (fragment, char))
  167. return result
  168. return has_before_fragments, before, first_input_line
  169. class _RPrompt(Window):
  170. """
  171. The prompt that is displayed on the right side of the Window.
  172. """
  173. def __init__(self, text: AnyFormattedText) -> None:
  174. super().__init__(
  175. FormattedTextControl(text=text),
  176. align=WindowAlign.RIGHT,
  177. style="class:rprompt",
  178. )
  179. class CompleteStyle(str, Enum):
  180. """
  181. How to display autocompletions for the prompt.
  182. """
  183. value: str
  184. COLUMN = "COLUMN"
  185. MULTI_COLUMN = "MULTI_COLUMN"
  186. READLINE_LIKE = "READLINE_LIKE"
  187. # Formatted text for the continuation prompt. It's the same like other
  188. # formatted text, except that if it's a callable, it takes three arguments.
  189. PromptContinuationText = Union[
  190. str,
  191. "MagicFormattedText",
  192. StyleAndTextTuples,
  193. # (prompt_width, line_number, wrap_count) -> AnyFormattedText.
  194. Callable[[int, int, int], AnyFormattedText],
  195. ]
  196. _T = TypeVar("_T")
  197. class PromptSession(Generic[_T]):
  198. """
  199. PromptSession for a prompt application, which can be used as a GNU Readline
  200. replacement.
  201. This is a wrapper around a lot of ``prompt_toolkit`` functionality and can
  202. be a replacement for `raw_input`.
  203. All parameters that expect "formatted text" can take either just plain text
  204. (a unicode object), a list of ``(style_str, text)`` tuples or an HTML object.
  205. Example usage::
  206. s = PromptSession(message='>')
  207. text = s.prompt()
  208. :param message: Plain text or formatted text to be shown before the prompt.
  209. This can also be a callable that returns formatted text.
  210. :param multiline: `bool` or :class:`~prompt_toolkit.filters.Filter`.
  211. When True, prefer a layout that is more adapted for multiline input.
  212. Text after newlines is automatically indented, and search/arg input is
  213. shown below the input, instead of replacing the prompt.
  214. :param wrap_lines: `bool` or :class:`~prompt_toolkit.filters.Filter`.
  215. When True (the default), automatically wrap long lines instead of
  216. scrolling horizontally.
  217. :param is_password: Show asterisks instead of the actual typed characters.
  218. :param editing_mode: ``EditingMode.VI`` or ``EditingMode.EMACS``.
  219. :param vi_mode: `bool`, if True, Identical to ``editing_mode=EditingMode.VI``.
  220. :param complete_while_typing: `bool` or
  221. :class:`~prompt_toolkit.filters.Filter`. Enable autocompletion while
  222. typing.
  223. :param validate_while_typing: `bool` or
  224. :class:`~prompt_toolkit.filters.Filter`. Enable input validation while
  225. typing.
  226. :param enable_history_search: `bool` or
  227. :class:`~prompt_toolkit.filters.Filter`. Enable up-arrow parting
  228. string matching.
  229. :param search_ignore_case:
  230. :class:`~prompt_toolkit.filters.Filter`. Search case insensitive.
  231. :param lexer: :class:`~prompt_toolkit.lexers.Lexer` to be used for the
  232. syntax highlighting.
  233. :param validator: :class:`~prompt_toolkit.validation.Validator` instance
  234. for input validation.
  235. :param completer: :class:`~prompt_toolkit.completion.Completer` instance
  236. for input completion.
  237. :param complete_in_thread: `bool` or
  238. :class:`~prompt_toolkit.filters.Filter`. Run the completer code in a
  239. background thread in order to avoid blocking the user interface.
  240. For ``CompleteStyle.READLINE_LIKE``, this setting has no effect. There
  241. we always run the completions in the main thread.
  242. :param reserve_space_for_menu: Space to be reserved for displaying the menu.
  243. (0 means that no space needs to be reserved.)
  244. :param auto_suggest: :class:`~prompt_toolkit.auto_suggest.AutoSuggest`
  245. instance for input suggestions.
  246. :param style: :class:`.Style` instance for the color scheme.
  247. :param include_default_pygments_style: `bool` or
  248. :class:`~prompt_toolkit.filters.Filter`. Tell whether the default
  249. styling for Pygments lexers has to be included. By default, this is
  250. true, but it is recommended to be disabled if another Pygments style is
  251. passed as the `style` argument, otherwise, two Pygments styles will be
  252. merged.
  253. :param style_transformation:
  254. :class:`~prompt_toolkit.style.StyleTransformation` instance.
  255. :param swap_light_and_dark_colors: `bool` or
  256. :class:`~prompt_toolkit.filters.Filter`. When enabled, apply
  257. :class:`~prompt_toolkit.style.SwapLightAndDarkStyleTransformation`.
  258. This is useful for switching between dark and light terminal
  259. backgrounds.
  260. :param enable_system_prompt: `bool` or
  261. :class:`~prompt_toolkit.filters.Filter`. Pressing Meta+'!' will show
  262. a system prompt.
  263. :param enable_suspend: `bool` or :class:`~prompt_toolkit.filters.Filter`.
  264. Enable Control-Z style suspension.
  265. :param enable_open_in_editor: `bool` or
  266. :class:`~prompt_toolkit.filters.Filter`. Pressing 'v' in Vi mode or
  267. C-X C-E in emacs mode will open an external editor.
  268. :param history: :class:`~prompt_toolkit.history.History` instance.
  269. :param clipboard: :class:`~prompt_toolkit.clipboard.Clipboard` instance.
  270. (e.g. :class:`~prompt_toolkit.clipboard.InMemoryClipboard`)
  271. :param rprompt: Text or formatted text to be displayed on the right side.
  272. This can also be a callable that returns (formatted) text.
  273. :param bottom_toolbar: Formatted text or callable that returns formatted
  274. text to be displayed at the bottom of the screen.
  275. :param prompt_continuation: Text that needs to be displayed for a multiline
  276. prompt continuation. This can either be formatted text or a callable
  277. that takes a `prompt_width`, `line_number` and `wrap_count` as input
  278. and returns formatted text. When this is `None` (the default), then
  279. `prompt_width` spaces will be used.
  280. :param complete_style: ``CompleteStyle.COLUMN``,
  281. ``CompleteStyle.MULTI_COLUMN`` or ``CompleteStyle.READLINE_LIKE``.
  282. :param mouse_support: `bool` or :class:`~prompt_toolkit.filters.Filter`
  283. to enable mouse support.
  284. :param placeholder: Text to be displayed when no input has been given
  285. yet. Unlike the `default` parameter, this won't be returned as part of
  286. the output ever. This can be formatted text or a callable that returns
  287. formatted text.
  288. :param show_frame: `bool` or
  289. :class:`~prompt_toolkit.filters.Filter`. When True, surround the input
  290. with a frame.
  291. :param refresh_interval: (number; in seconds) When given, refresh the UI
  292. every so many seconds.
  293. :param input: `Input` object. (Note that the preferred way to change the
  294. input/output is by creating an `AppSession`.)
  295. :param output: `Output` object.
  296. :param interrupt_exception: The exception type that will be raised when
  297. there is a keyboard interrupt (control-c keypress).
  298. :param eof_exception: The exception type that will be raised when there is
  299. an end-of-file/exit event (control-d keypress).
  300. """
  301. _fields = (
  302. "message",
  303. "lexer",
  304. "completer",
  305. "complete_in_thread",
  306. "is_password",
  307. "editing_mode",
  308. "key_bindings",
  309. "is_password",
  310. "bottom_toolbar",
  311. "style",
  312. "style_transformation",
  313. "swap_light_and_dark_colors",
  314. "color_depth",
  315. "cursor",
  316. "include_default_pygments_style",
  317. "rprompt",
  318. "multiline",
  319. "prompt_continuation",
  320. "wrap_lines",
  321. "enable_history_search",
  322. "search_ignore_case",
  323. "complete_while_typing",
  324. "validate_while_typing",
  325. "complete_style",
  326. "mouse_support",
  327. "auto_suggest",
  328. "clipboard",
  329. "validator",
  330. "refresh_interval",
  331. "input_processors",
  332. "placeholder",
  333. "enable_system_prompt",
  334. "enable_suspend",
  335. "enable_open_in_editor",
  336. "reserve_space_for_menu",
  337. "tempfile_suffix",
  338. "tempfile",
  339. "show_frame",
  340. )
  341. def __init__(
  342. self,
  343. message: AnyFormattedText = "",
  344. *,
  345. multiline: FilterOrBool = False,
  346. wrap_lines: FilterOrBool = True,
  347. is_password: FilterOrBool = False,
  348. vi_mode: bool = False,
  349. editing_mode: EditingMode = EditingMode.EMACS,
  350. complete_while_typing: FilterOrBool = True,
  351. validate_while_typing: FilterOrBool = True,
  352. enable_history_search: FilterOrBool = False,
  353. search_ignore_case: FilterOrBool = False,
  354. lexer: Lexer | None = None,
  355. enable_system_prompt: FilterOrBool = False,
  356. enable_suspend: FilterOrBool = False,
  357. enable_open_in_editor: FilterOrBool = False,
  358. validator: Validator | None = None,
  359. completer: Completer | None = None,
  360. complete_in_thread: bool = False,
  361. reserve_space_for_menu: int = 8,
  362. complete_style: CompleteStyle = CompleteStyle.COLUMN,
  363. auto_suggest: AutoSuggest | None = None,
  364. style: BaseStyle | None = None,
  365. style_transformation: StyleTransformation | None = None,
  366. swap_light_and_dark_colors: FilterOrBool = False,
  367. color_depth: ColorDepth | None = None,
  368. cursor: AnyCursorShapeConfig = None,
  369. include_default_pygments_style: FilterOrBool = True,
  370. history: History | None = None,
  371. clipboard: Clipboard | None = None,
  372. prompt_continuation: PromptContinuationText | None = None,
  373. rprompt: AnyFormattedText = None,
  374. bottom_toolbar: AnyFormattedText = None,
  375. mouse_support: FilterOrBool = False,
  376. input_processors: list[Processor] | None = None,
  377. placeholder: AnyFormattedText | None = None,
  378. key_bindings: KeyBindingsBase | None = None,
  379. erase_when_done: bool = False,
  380. tempfile_suffix: str | Callable[[], str] | None = ".txt",
  381. tempfile: str | Callable[[], str] | None = None,
  382. refresh_interval: float = 0,
  383. show_frame: FilterOrBool = False,
  384. input: Input | None = None,
  385. output: Output | None = None,
  386. interrupt_exception: type[BaseException] = KeyboardInterrupt,
  387. eof_exception: type[BaseException] = EOFError,
  388. ) -> None:
  389. history = history or InMemoryHistory()
  390. clipboard = clipboard or InMemoryClipboard()
  391. # Ensure backwards-compatibility, when `vi_mode` is passed.
  392. if vi_mode:
  393. editing_mode = EditingMode.VI
  394. # Store all settings in this class.
  395. self._input = input
  396. self._output = output
  397. # Store attributes.
  398. # (All except 'editing_mode'.)
  399. self.message = message
  400. self.lexer = lexer
  401. self.completer = completer
  402. self.complete_in_thread = complete_in_thread
  403. self.is_password = is_password
  404. self.key_bindings = key_bindings
  405. self.bottom_toolbar = bottom_toolbar
  406. self.style = style
  407. self.style_transformation = style_transformation
  408. self.swap_light_and_dark_colors = swap_light_and_dark_colors
  409. self.color_depth = color_depth
  410. self.cursor = cursor
  411. self.include_default_pygments_style = include_default_pygments_style
  412. self.rprompt = rprompt
  413. self.multiline = multiline
  414. self.prompt_continuation = prompt_continuation
  415. self.wrap_lines = wrap_lines
  416. self.enable_history_search = enable_history_search
  417. self.search_ignore_case = search_ignore_case
  418. self.complete_while_typing = complete_while_typing
  419. self.validate_while_typing = validate_while_typing
  420. self.complete_style = complete_style
  421. self.mouse_support = mouse_support
  422. self.auto_suggest = auto_suggest
  423. self.clipboard = clipboard
  424. self.validator = validator
  425. self.refresh_interval = refresh_interval
  426. self.input_processors = input_processors
  427. self.placeholder = placeholder
  428. self.enable_system_prompt = enable_system_prompt
  429. self.enable_suspend = enable_suspend
  430. self.enable_open_in_editor = enable_open_in_editor
  431. self.reserve_space_for_menu = reserve_space_for_menu
  432. self.tempfile_suffix = tempfile_suffix
  433. self.tempfile = tempfile
  434. self.show_frame = show_frame
  435. self.interrupt_exception = interrupt_exception
  436. self.eof_exception = eof_exception
  437. # Create buffers, layout and Application.
  438. self.history = history
  439. self.default_buffer = self._create_default_buffer()
  440. self.search_buffer = self._create_search_buffer()
  441. self.layout = self._create_layout()
  442. self.app = self._create_application(editing_mode, erase_when_done)
  443. def _dyncond(self, attr_name: str) -> Condition:
  444. """
  445. Dynamically take this setting from this 'PromptSession' class.
  446. `attr_name` represents an attribute name of this class. Its value
  447. can either be a boolean or a `Filter`.
  448. This returns something that can be used as either a `Filter`
  449. or `Filter`.
  450. """
  451. @Condition
  452. def dynamic() -> bool:
  453. value = cast(FilterOrBool, getattr(self, attr_name))
  454. return to_filter(value)()
  455. return dynamic
  456. def _create_default_buffer(self) -> Buffer:
  457. """
  458. Create and return the default input buffer.
  459. """
  460. dyncond = self._dyncond
  461. # Create buffers list.
  462. def accept(buff: Buffer) -> bool:
  463. """Accept the content of the default buffer. This is called when
  464. the validation succeeds."""
  465. cast(Application[str], get_app()).exit(
  466. result=buff.document.text, style="class:accepted"
  467. )
  468. return True # Keep text, we call 'reset' later on.
  469. return Buffer(
  470. name=DEFAULT_BUFFER,
  471. # Make sure that complete_while_typing is disabled when
  472. # enable_history_search is enabled. (First convert to Filter,
  473. # to avoid doing bitwise operations on bool objects.)
  474. complete_while_typing=Condition(
  475. lambda: is_true(self.complete_while_typing)
  476. and not is_true(self.enable_history_search)
  477. and not self.complete_style == CompleteStyle.READLINE_LIKE
  478. ),
  479. validate_while_typing=dyncond("validate_while_typing"),
  480. enable_history_search=dyncond("enable_history_search"),
  481. validator=DynamicValidator(lambda: self.validator),
  482. completer=DynamicCompleter(
  483. lambda: ThreadedCompleter(self.completer)
  484. if self.complete_in_thread and self.completer
  485. else self.completer
  486. ),
  487. history=self.history,
  488. auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest),
  489. accept_handler=accept,
  490. tempfile_suffix=lambda: to_str(self.tempfile_suffix or ""),
  491. tempfile=lambda: to_str(self.tempfile or ""),
  492. )
  493. def _create_search_buffer(self) -> Buffer:
  494. return Buffer(name=SEARCH_BUFFER)
  495. def _create_layout(self) -> Layout:
  496. """
  497. Create `Layout` for this prompt.
  498. """
  499. dyncond = self._dyncond
  500. # Create functions that will dynamically split the prompt. (If we have
  501. # a multiline prompt.)
  502. (
  503. has_before_fragments,
  504. get_prompt_text_1,
  505. get_prompt_text_2,
  506. ) = _split_multiline_prompt(self._get_prompt)
  507. default_buffer = self.default_buffer
  508. search_buffer = self.search_buffer
  509. # Create processors list.
  510. @Condition
  511. def display_placeholder() -> bool:
  512. return self.placeholder is not None and self.default_buffer.text == ""
  513. all_input_processors = [
  514. HighlightIncrementalSearchProcessor(),
  515. HighlightSelectionProcessor(),
  516. ConditionalProcessor(
  517. AppendAutoSuggestion(), has_focus(default_buffer) & ~is_done
  518. ),
  519. ConditionalProcessor(PasswordProcessor(), dyncond("is_password")),
  520. DisplayMultipleCursors(),
  521. # Users can insert processors here.
  522. DynamicProcessor(lambda: merge_processors(self.input_processors or [])),
  523. ConditionalProcessor(
  524. AfterInput(lambda: self.placeholder),
  525. filter=display_placeholder,
  526. ),
  527. ]
  528. # Create bottom toolbars.
  529. bottom_toolbar = ConditionalContainer(
  530. Window(
  531. FormattedTextControl(
  532. lambda: self.bottom_toolbar, style="class:bottom-toolbar.text"
  533. ),
  534. style="class:bottom-toolbar",
  535. dont_extend_height=True,
  536. height=Dimension(min=1),
  537. ),
  538. filter=Condition(lambda: self.bottom_toolbar is not None)
  539. & ~is_done
  540. & renderer_height_is_known,
  541. )
  542. search_toolbar = SearchToolbar(
  543. search_buffer, ignore_case=dyncond("search_ignore_case")
  544. )
  545. search_buffer_control = SearchBufferControl(
  546. buffer=search_buffer,
  547. input_processors=[ReverseSearchProcessor()],
  548. ignore_case=dyncond("search_ignore_case"),
  549. )
  550. system_toolbar = SystemToolbar(
  551. enable_global_bindings=dyncond("enable_system_prompt")
  552. )
  553. def get_search_buffer_control() -> SearchBufferControl:
  554. "Return the UIControl to be focused when searching start."
  555. if is_true(self.multiline):
  556. return search_toolbar.control
  557. else:
  558. return search_buffer_control
  559. default_buffer_control = BufferControl(
  560. buffer=default_buffer,
  561. search_buffer_control=get_search_buffer_control,
  562. input_processors=all_input_processors,
  563. include_default_input_processors=False,
  564. lexer=DynamicLexer(lambda: self.lexer),
  565. preview_search=True,
  566. )
  567. default_buffer_window = Window(
  568. default_buffer_control,
  569. height=self._get_default_buffer_control_height,
  570. get_line_prefix=partial(
  571. self._get_line_prefix, get_prompt_text_2=get_prompt_text_2
  572. ),
  573. wrap_lines=dyncond("wrap_lines"),
  574. )
  575. @Condition
  576. def multi_column_complete_style() -> bool:
  577. return self.complete_style == CompleteStyle.MULTI_COLUMN
  578. # Build the layout.
  579. # The main input, with completion menus floating on top of it.
  580. main_input_container = FloatContainer(
  581. HSplit(
  582. [
  583. ConditionalContainer(
  584. Window(
  585. FormattedTextControl(get_prompt_text_1),
  586. dont_extend_height=True,
  587. ),
  588. Condition(has_before_fragments),
  589. ),
  590. ConditionalContainer(
  591. default_buffer_window,
  592. Condition(
  593. lambda: get_app().layout.current_control
  594. != search_buffer_control
  595. ),
  596. ),
  597. ConditionalContainer(
  598. Window(search_buffer_control),
  599. Condition(
  600. lambda: get_app().layout.current_control
  601. == search_buffer_control
  602. ),
  603. ),
  604. ]
  605. ),
  606. [
  607. # Completion menus.
  608. # NOTE: Especially the multi-column menu needs to be
  609. # transparent, because the shape is not always
  610. # rectangular due to the meta-text below the menu.
  611. Float(
  612. xcursor=True,
  613. ycursor=True,
  614. transparent=True,
  615. content=CompletionsMenu(
  616. max_height=16,
  617. scroll_offset=1,
  618. extra_filter=has_focus(default_buffer)
  619. & ~multi_column_complete_style,
  620. ),
  621. ),
  622. Float(
  623. xcursor=True,
  624. ycursor=True,
  625. transparent=True,
  626. content=MultiColumnCompletionsMenu(
  627. show_meta=True,
  628. extra_filter=has_focus(default_buffer)
  629. & multi_column_complete_style,
  630. ),
  631. ),
  632. # The right prompt.
  633. Float(
  634. right=0,
  635. top=0,
  636. hide_when_covering_content=True,
  637. content=_RPrompt(lambda: self.rprompt),
  638. ),
  639. ],
  640. )
  641. layout = HSplit(
  642. [
  643. # Wrap the main input in a frame, if requested.
  644. ConditionalContainer(
  645. Frame(main_input_container),
  646. filter=dyncond("show_frame"),
  647. alternative_content=main_input_container,
  648. ),
  649. ConditionalContainer(ValidationToolbar(), filter=~is_done),
  650. ConditionalContainer(
  651. system_toolbar, dyncond("enable_system_prompt") & ~is_done
  652. ),
  653. # In multiline mode, we use two toolbars for 'arg' and 'search'.
  654. ConditionalContainer(
  655. Window(FormattedTextControl(self._get_arg_text), height=1),
  656. dyncond("multiline") & has_arg,
  657. ),
  658. ConditionalContainer(search_toolbar, dyncond("multiline") & ~is_done),
  659. bottom_toolbar,
  660. ]
  661. )
  662. return Layout(layout, default_buffer_window)
  663. def _create_application(
  664. self, editing_mode: EditingMode, erase_when_done: bool
  665. ) -> Application[_T]:
  666. """
  667. Create the `Application` object.
  668. """
  669. dyncond = self._dyncond
  670. # Default key bindings.
  671. auto_suggest_bindings = load_auto_suggest_bindings()
  672. open_in_editor_bindings = load_open_in_editor_bindings()
  673. prompt_bindings = self._create_prompt_bindings()
  674. # Create application
  675. application: Application[_T] = Application(
  676. layout=self.layout,
  677. style=DynamicStyle(lambda: self.style),
  678. style_transformation=merge_style_transformations(
  679. [
  680. DynamicStyleTransformation(lambda: self.style_transformation),
  681. ConditionalStyleTransformation(
  682. SwapLightAndDarkStyleTransformation(),
  683. dyncond("swap_light_and_dark_colors"),
  684. ),
  685. ]
  686. ),
  687. include_default_pygments_style=dyncond("include_default_pygments_style"),
  688. clipboard=DynamicClipboard(lambda: self.clipboard),
  689. key_bindings=merge_key_bindings(
  690. [
  691. merge_key_bindings(
  692. [
  693. auto_suggest_bindings,
  694. ConditionalKeyBindings(
  695. open_in_editor_bindings,
  696. dyncond("enable_open_in_editor")
  697. & has_focus(DEFAULT_BUFFER),
  698. ),
  699. prompt_bindings,
  700. ]
  701. ),
  702. DynamicKeyBindings(lambda: self.key_bindings),
  703. ]
  704. ),
  705. mouse_support=dyncond("mouse_support"),
  706. editing_mode=editing_mode,
  707. erase_when_done=erase_when_done,
  708. reverse_vi_search_direction=True,
  709. color_depth=lambda: self.color_depth,
  710. cursor=DynamicCursorShapeConfig(lambda: self.cursor),
  711. refresh_interval=self.refresh_interval,
  712. input=self._input,
  713. output=self._output,
  714. )
  715. # During render time, make sure that we focus the right search control
  716. # (if we are searching). - This could be useful if people make the
  717. # 'multiline' property dynamic.
  718. """
  719. def on_render(app):
  720. multiline = is_true(self.multiline)
  721. current_control = app.layout.current_control
  722. if multiline:
  723. if current_control == search_buffer_control:
  724. app.layout.current_control = search_toolbar.control
  725. app.invalidate()
  726. else:
  727. if current_control == search_toolbar.control:
  728. app.layout.current_control = search_buffer_control
  729. app.invalidate()
  730. app.on_render += on_render
  731. """
  732. return application
  733. def _create_prompt_bindings(self) -> KeyBindings:
  734. """
  735. Create the KeyBindings for a prompt application.
  736. """
  737. kb = KeyBindings()
  738. handle = kb.add
  739. default_focused = has_focus(DEFAULT_BUFFER)
  740. @Condition
  741. def do_accept() -> bool:
  742. return not is_true(self.multiline) and self.app.layout.has_focus(
  743. DEFAULT_BUFFER
  744. )
  745. @handle("enter", filter=do_accept & default_focused)
  746. def _accept_input(event: E) -> None:
  747. "Accept input when enter has been pressed."
  748. self.default_buffer.validate_and_handle()
  749. @Condition
  750. def readline_complete_style() -> bool:
  751. return self.complete_style == CompleteStyle.READLINE_LIKE
  752. @handle("tab", filter=readline_complete_style & default_focused)
  753. def _complete_like_readline(event: E) -> None:
  754. "Display completions (like Readline)."
  755. display_completions_like_readline(event)
  756. @handle("c-c", filter=default_focused)
  757. @handle("<sigint>")
  758. def _keyboard_interrupt(event: E) -> None:
  759. "Abort when Control-C has been pressed."
  760. event.app.exit(exception=self.interrupt_exception(), style="class:aborting")
  761. @Condition
  762. def ctrl_d_condition() -> bool:
  763. """Ctrl-D binding is only active when the default buffer is selected
  764. and empty."""
  765. app = get_app()
  766. return (
  767. app.current_buffer.name == DEFAULT_BUFFER
  768. and not app.current_buffer.text
  769. )
  770. @handle("c-d", filter=ctrl_d_condition & default_focused)
  771. def _eof(event: E) -> None:
  772. "Exit when Control-D has been pressed."
  773. event.app.exit(exception=self.eof_exception(), style="class:exiting")
  774. suspend_supported = Condition(suspend_to_background_supported)
  775. @Condition
  776. def enable_suspend() -> bool:
  777. return to_filter(self.enable_suspend)()
  778. @handle("c-z", filter=suspend_supported & enable_suspend)
  779. def _suspend(event: E) -> None:
  780. """
  781. Suspend process to background.
  782. """
  783. event.app.suspend_to_background()
  784. return kb
  785. def prompt(
  786. self,
  787. # When any of these arguments are passed, this value is overwritten
  788. # in this PromptSession.
  789. message: AnyFormattedText | None = None,
  790. # `message` should go first, because people call it as
  791. # positional argument.
  792. *,
  793. editing_mode: EditingMode | None = None,
  794. refresh_interval: float | None = None,
  795. vi_mode: bool | None = None,
  796. lexer: Lexer | None = None,
  797. completer: Completer | None = None,
  798. complete_in_thread: bool | None = None,
  799. is_password: bool | None = None,
  800. key_bindings: KeyBindingsBase | None = None,
  801. bottom_toolbar: AnyFormattedText | None = None,
  802. style: BaseStyle | None = None,
  803. color_depth: ColorDepth | None = None,
  804. cursor: AnyCursorShapeConfig | None = None,
  805. include_default_pygments_style: FilterOrBool | None = None,
  806. style_transformation: StyleTransformation | None = None,
  807. swap_light_and_dark_colors: FilterOrBool | None = None,
  808. rprompt: AnyFormattedText | None = None,
  809. multiline: FilterOrBool | None = None,
  810. prompt_continuation: PromptContinuationText | None = None,
  811. wrap_lines: FilterOrBool | None = None,
  812. enable_history_search: FilterOrBool | None = None,
  813. search_ignore_case: FilterOrBool | None = None,
  814. complete_while_typing: FilterOrBool | None = None,
  815. validate_while_typing: FilterOrBool | None = None,
  816. complete_style: CompleteStyle | None = None,
  817. auto_suggest: AutoSuggest | None = None,
  818. validator: Validator | None = None,
  819. clipboard: Clipboard | None = None,
  820. mouse_support: FilterOrBool | None = None,
  821. input_processors: list[Processor] | None = None,
  822. placeholder: AnyFormattedText | None = None,
  823. reserve_space_for_menu: int | None = None,
  824. enable_system_prompt: FilterOrBool | None = None,
  825. enable_suspend: FilterOrBool | None = None,
  826. enable_open_in_editor: FilterOrBool | None = None,
  827. tempfile_suffix: str | Callable[[], str] | None = None,
  828. tempfile: str | Callable[[], str] | None = None,
  829. show_frame: FilterOrBool | None = None,
  830. # Following arguments are specific to the current `prompt()` call.
  831. default: str | Document = "",
  832. accept_default: bool = False,
  833. pre_run: Callable[[], None] | None = None,
  834. set_exception_handler: bool = True,
  835. handle_sigint: bool = True,
  836. in_thread: bool = False,
  837. inputhook: InputHook | None = None,
  838. ) -> _T:
  839. """
  840. Display the prompt.
  841. The first set of arguments is a subset of the :class:`~.PromptSession`
  842. class itself. For these, passing in ``None`` will keep the current
  843. values that are active in the session. Passing in a value will set the
  844. attribute for the session, which means that it applies to the current,
  845. but also to the next prompts.
  846. Note that in order to erase a ``Completer``, ``Validator`` or
  847. ``AutoSuggest``, you can't use ``None``. Instead pass in a
  848. ``DummyCompleter``, ``DummyValidator`` or ``DummyAutoSuggest`` instance
  849. respectively. For a ``Lexer`` you can pass in an empty ``SimpleLexer``.
  850. Additional arguments, specific for this prompt:
  851. :param default: The default input text to be shown. (This can be edited
  852. by the user).
  853. :param accept_default: When `True`, automatically accept the default
  854. value without allowing the user to edit the input.
  855. :param pre_run: Callable, called at the start of `Application.run`.
  856. :param in_thread: Run the prompt in a background thread; block the
  857. current thread. This avoids interference with an event loop in the
  858. current thread. Like `Application.run(in_thread=True)`.
  859. This method will raise ``KeyboardInterrupt`` when control-c has been
  860. pressed (for abort) and ``EOFError`` when control-d has been pressed
  861. (for exit).
  862. """
  863. # NOTE: We used to create a backup of the PromptSession attributes and
  864. # restore them after exiting the prompt. This code has been
  865. # removed, because it was confusing and didn't really serve a use
  866. # case. (People were changing `Application.editing_mode`
  867. # dynamically and surprised that it was reset after every call.)
  868. # NOTE 2: YES, this is a lot of repeation below...
  869. # However, it is a very convenient for a user to accept all
  870. # these parameters in this `prompt` method as well. We could
  871. # use `locals()` and `setattr` to avoid the repetition, but
  872. # then we loose the advantage of mypy and pyflakes to be able
  873. # to verify the code.
  874. if message is not None:
  875. self.message = message
  876. if editing_mode is not None:
  877. self.editing_mode = editing_mode
  878. if refresh_interval is not None:
  879. self.refresh_interval = refresh_interval
  880. if vi_mode:
  881. self.editing_mode = EditingMode.VI
  882. if lexer is not None:
  883. self.lexer = lexer
  884. if completer is not None:
  885. self.completer = completer
  886. if complete_in_thread is not None:
  887. self.complete_in_thread = complete_in_thread
  888. if is_password is not None:
  889. self.is_password = is_password
  890. if key_bindings is not None:
  891. self.key_bindings = key_bindings
  892. if bottom_toolbar is not None:
  893. self.bottom_toolbar = bottom_toolbar
  894. if style is not None:
  895. self.style = style
  896. if color_depth is not None:
  897. self.color_depth = color_depth
  898. if cursor is not None:
  899. self.cursor = cursor
  900. if include_default_pygments_style is not None:
  901. self.include_default_pygments_style = include_default_pygments_style
  902. if style_transformation is not None:
  903. self.style_transformation = style_transformation
  904. if swap_light_and_dark_colors is not None:
  905. self.swap_light_and_dark_colors = swap_light_and_dark_colors
  906. if rprompt is not None:
  907. self.rprompt = rprompt
  908. if multiline is not None:
  909. self.multiline = multiline
  910. if prompt_continuation is not None:
  911. self.prompt_continuation = prompt_continuation
  912. if wrap_lines is not None:
  913. self.wrap_lines = wrap_lines
  914. if enable_history_search is not None:
  915. self.enable_history_search = enable_history_search
  916. if search_ignore_case is not None:
  917. self.search_ignore_case = search_ignore_case
  918. if complete_while_typing is not None:
  919. self.complete_while_typing = complete_while_typing
  920. if validate_while_typing is not None:
  921. self.validate_while_typing = validate_while_typing
  922. if complete_style is not None:
  923. self.complete_style = complete_style
  924. if auto_suggest is not None:
  925. self.auto_suggest = auto_suggest
  926. if validator is not None:
  927. self.validator = validator
  928. if clipboard is not None:
  929. self.clipboard = clipboard
  930. if mouse_support is not None:
  931. self.mouse_support = mouse_support
  932. if input_processors is not None:
  933. self.input_processors = input_processors
  934. if placeholder is not None:
  935. self.placeholder = placeholder
  936. if reserve_space_for_menu is not None:
  937. self.reserve_space_for_menu = reserve_space_for_menu
  938. if enable_system_prompt is not None:
  939. self.enable_system_prompt = enable_system_prompt
  940. if enable_suspend is not None:
  941. self.enable_suspend = enable_suspend
  942. if enable_open_in_editor is not None:
  943. self.enable_open_in_editor = enable_open_in_editor
  944. if tempfile_suffix is not None:
  945. self.tempfile_suffix = tempfile_suffix
  946. if tempfile is not None:
  947. self.tempfile = tempfile
  948. if show_frame is not None:
  949. self.show_frame = show_frame
  950. self._add_pre_run_callables(pre_run, accept_default)
  951. self.default_buffer.reset(
  952. default if isinstance(default, Document) else Document(default)
  953. )
  954. self.app.refresh_interval = self.refresh_interval # This is not reactive.
  955. # If we are using the default output, and have a dumb terminal. Use the
  956. # dumb prompt.
  957. if self._output is None and is_dumb_terminal():
  958. with self._dumb_prompt(self.message) as dump_app:
  959. return dump_app.run(in_thread=in_thread, handle_sigint=handle_sigint)
  960. return self.app.run(
  961. set_exception_handler=set_exception_handler,
  962. in_thread=in_thread,
  963. handle_sigint=handle_sigint,
  964. inputhook=inputhook,
  965. )
  966. @contextmanager
  967. def _dumb_prompt(self, message: AnyFormattedText = "") -> Iterator[Application[_T]]:
  968. """
  969. Create prompt `Application` for prompt function for dumb terminals.
  970. Dumb terminals have minimum rendering capabilities. We can only print
  971. text to the screen. We can't use colors, and we can't do cursor
  972. movements. The Emacs inferior shell is an example of a dumb terminal.
  973. We will show the prompt, and wait for the input. We still handle arrow
  974. keys, and all custom key bindings, but we don't really render the
  975. cursor movements. Instead we only print the typed character that's
  976. right before the cursor.
  977. """
  978. # Send prompt to output.
  979. self.output.write(fragment_list_to_text(to_formatted_text(self.message)))
  980. self.output.flush()
  981. # Key bindings for the dumb prompt: mostly the same as the full prompt.
  982. key_bindings: KeyBindingsBase = self._create_prompt_bindings()
  983. if self.key_bindings:
  984. key_bindings = merge_key_bindings([self.key_bindings, key_bindings])
  985. # Create and run application.
  986. application = cast(
  987. Application[_T],
  988. Application(
  989. input=self.input,
  990. output=DummyOutput(),
  991. layout=self.layout,
  992. key_bindings=key_bindings,
  993. ),
  994. )
  995. def on_text_changed(_: object) -> None:
  996. self.output.write(self.default_buffer.document.text_before_cursor[-1:])
  997. self.output.flush()
  998. self.default_buffer.on_text_changed += on_text_changed
  999. try:
  1000. yield application
  1001. finally:
  1002. # Render line ending.
  1003. self.output.write("\r\n")
  1004. self.output.flush()
  1005. self.default_buffer.on_text_changed -= on_text_changed
  1006. async def prompt_async(
  1007. self,
  1008. # When any of these arguments are passed, this value is overwritten
  1009. # in this PromptSession.
  1010. message: AnyFormattedText | None = None,
  1011. # `message` should go first, because people call it as
  1012. # positional argument.
  1013. *,
  1014. editing_mode: EditingMode | None = None,
  1015. refresh_interval: float | None = None,
  1016. vi_mode: bool | None = None,
  1017. lexer: Lexer | None = None,
  1018. completer: Completer | None = None,
  1019. complete_in_thread: bool | None = None,
  1020. is_password: bool | None = None,
  1021. key_bindings: KeyBindingsBase | None = None,
  1022. bottom_toolbar: AnyFormattedText | None = None,
  1023. style: BaseStyle | None = None,
  1024. color_depth: ColorDepth | None = None,
  1025. cursor: CursorShapeConfig | None = None,
  1026. include_default_pygments_style: FilterOrBool | None = None,
  1027. style_transformation: StyleTransformation | None = None,
  1028. swap_light_and_dark_colors: FilterOrBool | None = None,
  1029. rprompt: AnyFormattedText | None = None,
  1030. multiline: FilterOrBool | None = None,
  1031. prompt_continuation: PromptContinuationText | None = None,
  1032. wrap_lines: FilterOrBool | None = None,
  1033. enable_history_search: FilterOrBool | None = None,
  1034. search_ignore_case: FilterOrBool | None = None,
  1035. complete_while_typing: FilterOrBool | None = None,
  1036. validate_while_typing: FilterOrBool | None = None,
  1037. complete_style: CompleteStyle | None = None,
  1038. auto_suggest: AutoSuggest | None = None,
  1039. validator: Validator | None = None,
  1040. clipboard: Clipboard | None = None,
  1041. mouse_support: FilterOrBool | None = None,
  1042. input_processors: list[Processor] | None = None,
  1043. placeholder: AnyFormattedText | None = None,
  1044. reserve_space_for_menu: int | None = None,
  1045. enable_system_prompt: FilterOrBool | None = None,
  1046. enable_suspend: FilterOrBool | None = None,
  1047. enable_open_in_editor: FilterOrBool | None = None,
  1048. tempfile_suffix: str | Callable[[], str] | None = None,
  1049. tempfile: str | Callable[[], str] | None = None,
  1050. show_frame: FilterOrBool = False,
  1051. # Following arguments are specific to the current `prompt()` call.
  1052. default: str | Document = "",
  1053. accept_default: bool = False,
  1054. pre_run: Callable[[], None] | None = None,
  1055. set_exception_handler: bool = True,
  1056. handle_sigint: bool = True,
  1057. ) -> _T:
  1058. if message is not None:
  1059. self.message = message
  1060. if editing_mode is not None:
  1061. self.editing_mode = editing_mode
  1062. if refresh_interval is not None:
  1063. self.refresh_interval = refresh_interval
  1064. if vi_mode:
  1065. self.editing_mode = EditingMode.VI
  1066. if lexer is not None:
  1067. self.lexer = lexer
  1068. if completer is not None:
  1069. self.completer = completer
  1070. if complete_in_thread is not None:
  1071. self.complete_in_thread = complete_in_thread
  1072. if is_password is not None:
  1073. self.is_password = is_password
  1074. if key_bindings is not None:
  1075. self.key_bindings = key_bindings
  1076. if bottom_toolbar is not None:
  1077. self.bottom_toolbar = bottom_toolbar
  1078. if style is not None:
  1079. self.style = style
  1080. if color_depth is not None:
  1081. self.color_depth = color_depth
  1082. if cursor is not None:
  1083. self.cursor = cursor
  1084. if include_default_pygments_style is not None:
  1085. self.include_default_pygments_style = include_default_pygments_style
  1086. if style_transformation is not None:
  1087. self.style_transformation = style_transformation
  1088. if swap_light_and_dark_colors is not None:
  1089. self.swap_light_and_dark_colors = swap_light_and_dark_colors
  1090. if rprompt is not None:
  1091. self.rprompt = rprompt
  1092. if multiline is not None:
  1093. self.multiline = multiline
  1094. if prompt_continuation is not None:
  1095. self.prompt_continuation = prompt_continuation
  1096. if wrap_lines is not None:
  1097. self.wrap_lines = wrap_lines
  1098. if enable_history_search is not None:
  1099. self.enable_history_search = enable_history_search
  1100. if search_ignore_case is not None:
  1101. self.search_ignore_case = search_ignore_case
  1102. if complete_while_typing is not None:
  1103. self.complete_while_typing = complete_while_typing
  1104. if validate_while_typing is not None:
  1105. self.validate_while_typing = validate_while_typing
  1106. if complete_style is not None:
  1107. self.complete_style = complete_style
  1108. if auto_suggest is not None:
  1109. self.auto_suggest = auto_suggest
  1110. if validator is not None:
  1111. self.validator = validator
  1112. if clipboard is not None:
  1113. self.clipboard = clipboard
  1114. if mouse_support is not None:
  1115. self.mouse_support = mouse_support
  1116. if input_processors is not None:
  1117. self.input_processors = input_processors
  1118. if placeholder is not None:
  1119. self.placeholder = placeholder
  1120. if reserve_space_for_menu is not None:
  1121. self.reserve_space_for_menu = reserve_space_for_menu
  1122. if enable_system_prompt is not None:
  1123. self.enable_system_prompt = enable_system_prompt
  1124. if enable_suspend is not None:
  1125. self.enable_suspend = enable_suspend
  1126. if enable_open_in_editor is not None:
  1127. self.enable_open_in_editor = enable_open_in_editor
  1128. if tempfile_suffix is not None:
  1129. self.tempfile_suffix = tempfile_suffix
  1130. if tempfile is not None:
  1131. self.tempfile = tempfile
  1132. if show_frame is not None:
  1133. self.show_frame = show_frame
  1134. self._add_pre_run_callables(pre_run, accept_default)
  1135. self.default_buffer.reset(
  1136. default if isinstance(default, Document) else Document(default)
  1137. )
  1138. self.app.refresh_interval = self.refresh_interval # This is not reactive.
  1139. # If we are using the default output, and have a dumb terminal. Use the
  1140. # dumb prompt.
  1141. if self._output is None and is_dumb_terminal():
  1142. with self._dumb_prompt(self.message) as dump_app:
  1143. return await dump_app.run_async(handle_sigint=handle_sigint)
  1144. return await self.app.run_async(
  1145. set_exception_handler=set_exception_handler, handle_sigint=handle_sigint
  1146. )
  1147. def _add_pre_run_callables(
  1148. self, pre_run: Callable[[], None] | None, accept_default: bool
  1149. ) -> None:
  1150. def pre_run2() -> None:
  1151. if pre_run:
  1152. pre_run()
  1153. if accept_default:
  1154. # Validate and handle input. We use `call_from_executor` in
  1155. # order to run it "soon" (during the next iteration of the
  1156. # event loop), instead of right now. Otherwise, it won't
  1157. # display the default value.
  1158. get_running_loop().call_soon(self.default_buffer.validate_and_handle)
  1159. self.app.pre_run_callables.append(pre_run2)
  1160. @property
  1161. def editing_mode(self) -> EditingMode:
  1162. return self.app.editing_mode
  1163. @editing_mode.setter
  1164. def editing_mode(self, value: EditingMode) -> None:
  1165. self.app.editing_mode = value
  1166. def _get_default_buffer_control_height(self) -> Dimension:
  1167. # If there is an autocompletion menu to be shown, make sure that our
  1168. # layout has at least a minimal height in order to display it.
  1169. if (
  1170. self.completer is not None
  1171. and self.complete_style != CompleteStyle.READLINE_LIKE
  1172. ):
  1173. space = self.reserve_space_for_menu
  1174. else:
  1175. space = 0
  1176. if space and not get_app().is_done:
  1177. buff = self.default_buffer
  1178. # Reserve the space, either when there are completions, or when
  1179. # `complete_while_typing` is true and we expect completions very
  1180. # soon.
  1181. if buff.complete_while_typing() or buff.complete_state is not None:
  1182. return Dimension(min=space)
  1183. return Dimension()
  1184. def _get_prompt(self) -> StyleAndTextTuples:
  1185. return to_formatted_text(self.message, style="class:prompt")
  1186. def _get_continuation(
  1187. self, width: int, line_number: int, wrap_count: int
  1188. ) -> StyleAndTextTuples:
  1189. """
  1190. Insert the prompt continuation.
  1191. :param width: The width that was used for the prompt. (more or less can
  1192. be used.)
  1193. :param line_number:
  1194. :param wrap_count: Amount of times that the line has been wrapped.
  1195. """
  1196. prompt_continuation = self.prompt_continuation
  1197. if callable(prompt_continuation):
  1198. continuation: AnyFormattedText = prompt_continuation(
  1199. width, line_number, wrap_count
  1200. )
  1201. else:
  1202. continuation = prompt_continuation
  1203. # When the continuation prompt is not given, choose the same width as
  1204. # the actual prompt.
  1205. if continuation is None and is_true(self.multiline):
  1206. continuation = " " * width
  1207. return to_formatted_text(continuation, style="class:prompt-continuation")
  1208. def _get_line_prefix(
  1209. self,
  1210. line_number: int,
  1211. wrap_count: int,
  1212. get_prompt_text_2: _StyleAndTextTuplesCallable,
  1213. ) -> StyleAndTextTuples:
  1214. """
  1215. Return whatever needs to be inserted before every line.
  1216. (the prompt, or a line continuation.)
  1217. """
  1218. # First line: display the "arg" or the prompt.
  1219. if line_number == 0 and wrap_count == 0:
  1220. if not is_true(self.multiline) and get_app().key_processor.arg is not None:
  1221. return self._inline_arg()
  1222. else:
  1223. return get_prompt_text_2()
  1224. # For the next lines, display the appropriate continuation.
  1225. prompt_width = get_cwidth(fragment_list_to_text(get_prompt_text_2()))
  1226. return self._get_continuation(prompt_width, line_number, wrap_count)
  1227. def _get_arg_text(self) -> StyleAndTextTuples:
  1228. "'arg' toolbar, for in multiline mode."
  1229. arg = self.app.key_processor.arg
  1230. if arg is None:
  1231. # Should not happen because of the `has_arg` filter in the layout.
  1232. return []
  1233. if arg == "-":
  1234. arg = "-1"
  1235. return [("class:arg-toolbar", "Repeat: "), ("class:arg-toolbar.text", arg)]
  1236. def _inline_arg(self) -> StyleAndTextTuples:
  1237. "'arg' prefix, for in single line mode."
  1238. app = get_app()
  1239. if app.key_processor.arg is None:
  1240. return []
  1241. else:
  1242. arg = app.key_processor.arg
  1243. return [
  1244. ("class:prompt.arg", "(arg: "),
  1245. ("class:prompt.arg.text", str(arg)),
  1246. ("class:prompt.arg", ") "),
  1247. ]
  1248. # Expose the Input and Output objects as attributes, mainly for
  1249. # backward-compatibility.
  1250. @property
  1251. def input(self) -> Input:
  1252. return self.app.input
  1253. @property
  1254. def output(self) -> Output:
  1255. return self.app.output
  1256. def prompt(
  1257. message: AnyFormattedText | None = None,
  1258. *,
  1259. history: History | None = None,
  1260. editing_mode: EditingMode | None = None,
  1261. refresh_interval: float | None = None,
  1262. vi_mode: bool | None = None,
  1263. lexer: Lexer | None = None,
  1264. completer: Completer | None = None,
  1265. complete_in_thread: bool | None = None,
  1266. is_password: bool | None = None,
  1267. key_bindings: KeyBindingsBase | None = None,
  1268. bottom_toolbar: AnyFormattedText | None = None,
  1269. style: BaseStyle | None = None,
  1270. color_depth: ColorDepth | None = None,
  1271. cursor: AnyCursorShapeConfig = None,
  1272. include_default_pygments_style: FilterOrBool | None = None,
  1273. style_transformation: StyleTransformation | None = None,
  1274. swap_light_and_dark_colors: FilterOrBool | None = None,
  1275. rprompt: AnyFormattedText | None = None,
  1276. multiline: FilterOrBool | None = None,
  1277. prompt_continuation: PromptContinuationText | None = None,
  1278. wrap_lines: FilterOrBool | None = None,
  1279. enable_history_search: FilterOrBool | None = None,
  1280. search_ignore_case: FilterOrBool | None = None,
  1281. complete_while_typing: FilterOrBool | None = None,
  1282. validate_while_typing: FilterOrBool | None = None,
  1283. complete_style: CompleteStyle | None = None,
  1284. auto_suggest: AutoSuggest | None = None,
  1285. validator: Validator | None = None,
  1286. clipboard: Clipboard | None = None,
  1287. mouse_support: FilterOrBool | None = None,
  1288. input_processors: list[Processor] | None = None,
  1289. placeholder: AnyFormattedText | None = None,
  1290. reserve_space_for_menu: int | None = None,
  1291. enable_system_prompt: FilterOrBool | None = None,
  1292. enable_suspend: FilterOrBool | None = None,
  1293. enable_open_in_editor: FilterOrBool | None = None,
  1294. tempfile_suffix: str | Callable[[], str] | None = None,
  1295. tempfile: str | Callable[[], str] | None = None,
  1296. show_frame: FilterOrBool | None = None,
  1297. # Following arguments are specific to the current `prompt()` call.
  1298. default: str = "",
  1299. accept_default: bool = False,
  1300. pre_run: Callable[[], None] | None = None,
  1301. set_exception_handler: bool = True,
  1302. handle_sigint: bool = True,
  1303. in_thread: bool = False,
  1304. inputhook: InputHook | None = None,
  1305. ) -> str:
  1306. """
  1307. The global `prompt` function. This will create a new `PromptSession`
  1308. instance for every call.
  1309. """
  1310. # The history is the only attribute that has to be passed to the
  1311. # `PromptSession`, it can't be passed into the `prompt()` method.
  1312. session: PromptSession[str] = PromptSession(history=history)
  1313. return session.prompt(
  1314. message,
  1315. editing_mode=editing_mode,
  1316. refresh_interval=refresh_interval,
  1317. vi_mode=vi_mode,
  1318. lexer=lexer,
  1319. completer=completer,
  1320. complete_in_thread=complete_in_thread,
  1321. is_password=is_password,
  1322. key_bindings=key_bindings,
  1323. bottom_toolbar=bottom_toolbar,
  1324. style=style,
  1325. color_depth=color_depth,
  1326. cursor=cursor,
  1327. include_default_pygments_style=include_default_pygments_style,
  1328. style_transformation=style_transformation,
  1329. swap_light_and_dark_colors=swap_light_and_dark_colors,
  1330. rprompt=rprompt,
  1331. multiline=multiline,
  1332. prompt_continuation=prompt_continuation,
  1333. wrap_lines=wrap_lines,
  1334. enable_history_search=enable_history_search,
  1335. search_ignore_case=search_ignore_case,
  1336. complete_while_typing=complete_while_typing,
  1337. validate_while_typing=validate_while_typing,
  1338. complete_style=complete_style,
  1339. auto_suggest=auto_suggest,
  1340. validator=validator,
  1341. clipboard=clipboard,
  1342. mouse_support=mouse_support,
  1343. input_processors=input_processors,
  1344. placeholder=placeholder,
  1345. reserve_space_for_menu=reserve_space_for_menu,
  1346. enable_system_prompt=enable_system_prompt,
  1347. enable_suspend=enable_suspend,
  1348. enable_open_in_editor=enable_open_in_editor,
  1349. tempfile_suffix=tempfile_suffix,
  1350. tempfile=tempfile,
  1351. show_frame=show_frame,
  1352. default=default,
  1353. accept_default=accept_default,
  1354. pre_run=pre_run,
  1355. set_exception_handler=set_exception_handler,
  1356. handle_sigint=handle_sigint,
  1357. in_thread=in_thread,
  1358. inputhook=inputhook,
  1359. )
  1360. prompt.__doc__ = PromptSession.prompt.__doc__
  1361. def create_confirm_session(
  1362. message: AnyFormattedText, suffix: str = " (y/n) "
  1363. ) -> PromptSession[bool]:
  1364. """
  1365. Create a `PromptSession` object for the 'confirm' function.
  1366. """
  1367. bindings = KeyBindings()
  1368. @bindings.add("y")
  1369. @bindings.add("Y")
  1370. def yes(event: E) -> None:
  1371. session.default_buffer.text = "y"
  1372. event.app.exit(result=True)
  1373. @bindings.add("n")
  1374. @bindings.add("N")
  1375. def no(event: E) -> None:
  1376. session.default_buffer.text = "n"
  1377. event.app.exit(result=False)
  1378. @bindings.add(Keys.Any)
  1379. def _(event: E) -> None:
  1380. "Disallow inserting other text."
  1381. pass
  1382. complete_message = merge_formatted_text([message, suffix])
  1383. session: PromptSession[bool] = PromptSession(
  1384. complete_message, key_bindings=bindings
  1385. )
  1386. return session
  1387. def confirm(message: AnyFormattedText = "Confirm?", suffix: str = " (y/n) ") -> bool:
  1388. """
  1389. Display a confirmation prompt that returns True/False.
  1390. """
  1391. session = create_confirm_session(message, suffix)
  1392. return session.prompt()