prompt.py 58 KB

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