prompt.py 59 KB

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