@@ -4,10 +4,13 @@ Asking for input (prompts)
44==========================
55
66This page is about building prompts. Pieces of code that we can embed in a
7- program for asking the user for input. If you want to use `prompt_toolkit ` for
8- building full screen terminal applications, it is probably still a good idea to
9- read this first, before heading to the :ref: `building full screen applications
10- <full_screen_applications>` page.
7+ program for asking the user for input. Even if you want to use `prompt_toolkit `
8+ for building full screen terminal applications, it is probably still a good
9+ idea to read this first, before heading to the :ref: `building full screen
10+ applications <full_screen_applications>` page.
11+
12+ In this page, we will cover autocompletion, syntax highlighting, key bindings,
13+ and so on.
1114
1215
1316Hello world
@@ -46,7 +49,7 @@ Instead of calling the :func:`~prompt_toolkit.shortcuts.prompt` function, it's
4649also possible to create a :class: `~prompt_toolkit.shortcuts.PromptSession `
4750instance followed by calling its
4851:meth: `~prompt_toolkit.shortcuts.PromptSession.prompt ` method for every input
49- call. This creates a kind of an input session.
52+ call. This creates a kind of an input session.
5053
5154.. code :: python
5255
@@ -107,9 +110,13 @@ you can do the following:
107110 from prompt_toolkit.styles.pygments import style_from_pygments
108111
109112 style = style_from_pygments(get_style_by_name(' monokai' ))
110- text = prompt(' Enter HTML: ' , lexer = PygmentsLexer(HtmlLexer), style = style)
113+ text = prompt(' Enter HTML: ' , lexer = PygmentsLexer(HtmlLexer), style = style,
114+ include_default_pygments_style = False )
111115 print (' You said: %s ' % text)
112116
117+ We pass ``include_default_pygments_style=False ``, because otherwise, both
118+ styles will be merged, possibly giving slightly different colors in the outcome
119+ for cases where where our custom Pygments style doesn't specify a color.
113120
114121.. _colors :
115122
@@ -165,14 +172,14 @@ Creating a custom style could be done like this:
165172.. code :: python
166173
167174 from prompt_toolkit.shortcuts import prompt
168- from prompt_toolkit.styles import style_from_pygments, merge_style
175+ from prompt_toolkit.styles import style_from_pygments_cls, merge_styles
169176 from prompt_toolkit.lexers import PygmentsLexer
170177
171178 from pygments.styles.tango import TangoStyle
172179 from pygments.lexers import HtmlLexer
173180
174- our_style = merge_style ([
175- style_from_pygments (TangoStyle),
181+ our_style = merge_styles ([
182+ style_from_pygments_cls (TangoStyle),
176183 Style.from_dict({
177184 ' pygments.comment' : ' #888888 bold' ,
178185 ' pygments.keyword' : ' #ff88ff bold' ,
@@ -186,9 +193,8 @@ Creating a custom style could be done like this:
186193 Coloring the prompt itself
187194^^^^^^^^^^^^^^^^^^^^^^^^^^
188195
189- It is possible to add some colors to the prompt itself. For this, we need a
190- ``get_prompt `` function. This is a function that can return a string, but also
191- a list of ``(style, text) `` tuples.
196+ It is possible to add some colors to the prompt itself. For this, we need to
197+ build some :ref: `formatted text <formatted_text >`.
192198
193199.. code :: python
194200
@@ -208,17 +214,19 @@ a list of ``(style, text)`` tuples.
208214 ' path' : ' #884444 underline' ,
209215 })
210216
211- def get_prompt ():
212- return [
213- (' class:username' , ' john' ),
214- (' class:at' , ' @' ),
215- (' class:host' , ' localhost' ),
216- (' class:colon' , ' :' ),
217- (' class:path' , ' /user/john' ),
218- (' class:pound' , ' # ' ),
219- ]
217+ message = [
218+ (' class:username' , ' john' ),
219+ (' class:at' , ' @' ),
220+ (' class:host' , ' localhost' ),
221+ (' class:colon' , ' :' ),
222+ (' class:path' , ' /user/john' ),
223+ (' class:pound' , ' # ' ),
224+ ]
225+
226+ text = prompt(message, style = style)
220227
221- text = prompt(get_prompt, style = style)
228+ The `message ` can be any kind of formatted text, as discussed :ref: `here
229+ <formatted_text>`. It can also be a callable that returns some formatted text.
222230
223231By default, colors are taking from the 256 color palette. If you want to have
22423224bit true color, this is possible by adding the ``true_color=True `` option to
@@ -285,7 +293,7 @@ that takes a :class:`~prompt_toolkit.document.Document` and yields the current
285293:class: `~prompt_toolkit.completion.Completion ` instances. Each completion
286294contains a portion of text, and a position.
287295
288- The position is used in for fixing text before the cursor. Pressing the tab key
296+ The position is used for fixing text before the cursor. Pressing the tab key
289297could for instance turn parts of the input from lowercase to uppercase. This
290298makes sense for a case insensitive completer. Or in case of a fuzzy completion,
291299it could fix typos. When ``start_position `` is something negative, this amount
@@ -295,8 +303,8 @@ of characters will be deleted and replaced.
295303Styling individual completions
296304^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
297305
298- Each completion can provide a custom style, which is used when its rendered in
299- the completion menu or toolbar. This is possible by passing a style to each
306+ Each completion can provide a custom style, which is used when it is rendered
307+ in the completion menu or toolbar. This is possible by passing a style to each
300308:class: `~prompt_toolkit.completion.Completion ` instance.
301309
302310.. code :: python
@@ -407,42 +415,38 @@ History
407415-------
408416
409417A :class: `~prompt_toolkit.history.History ` object keeps track of all the
410- previously entered strings. When nothing is passed into the
411- :func: `~prompt_toolkit.shortcuts.prompt ` function, it will start with an empty
412- history each time again. Usually, however, for a REPL, you want to keep the
413- same history between several calls to
414- :meth: `~prompt_toolkit.shortcuts.prompt `. This is possible by instantiating a
415- :class: `~prompt_toolkit.history.History ` object and passing that to each
416- :meth: `~prompt_toolkit.shortcuts.prompt ` call as follows:
417-
418- .. code :: python
418+ previously entered strings, so that the up-arrow can reveal previously entered
419+ items.
419420
420- from prompt_toolkit.history import InMemoryHistory
421- from prompt_toolkit import prompt
421+ The recommended way is to use a
422+ :class: `~prompt_toolkit.shortcuts.PromptSession `, which uses an
423+ :class: `~prompt_toolkit.history.InMemoryHistory ` for the entire session by
424+ default. The following example has a history out of the box:
422425
423- history = InMemoryHistory()
424-
425- while True :
426- prompt(history = history)
426+ .. code :: python
427427
428+ from prompt_toolkit import PromptSession
428429
429- To persist a history to disk, use :class: `~prompt_toolkit.history.FileHistory `
430- instead instead of :class: `~prompt_toolkit.history.InMemoryHistory `.
430+ session = PromptSession()
431431
432- .. note ::
432+ while True :
433+ session.prompt()
433434
434- Note that the same result as in the example above (with an
435- :class: `~prompt_toolkit.history.InMemoryHistory `) can be achieved by
436- creating a :func: `~prompt_toolkit.shortcuts.PromptSession ` instance.
435+ To persist a history to disk, use a :class: `~prompt_toolkit.history.FileHistory `
436+ instead instead of the default
437+ :class: `~prompt_toolkit.history.InMemoryHistory `. This history object can be
438+ passed either to a :class: `~prompt_toolkit.shortcuts.PromptSession ` or to the
439+ :meth: `~prompt_toolkit.shortcuts.prompt ` function. For instance:
437440
438- .. code :: python
441+ .. code :: python
439442
440- from prompt_toolkit import PromptSession
443+ from prompt_toolkit import PromptSession
444+ from prompt_toolkit.history import FileHistory
441445
442- session = PromptSession()
446+ session = PromptSession(history = FileHistory( ' ~/.myhistory ' ) )
443447
444- while True :
445- session.prompt()
448+ while True :
449+ session.prompt()
446450
447451
448452 Auto suggestion
@@ -459,20 +463,21 @@ the current input. Pressing the right arrow :kbd:`→` will insert this suggesti
459463
460464 When suggestions are based on the history, don't forget to share one
461465 :class: `~prompt_toolkit.history.History ` object between consecutive
462- :func: `~prompt_toolkit.shortcuts.prompt ` calls.
466+ :func: `~prompt_toolkit.shortcuts.prompt ` calls. Using a
467+ :class: `~prompt_toolkit.prompt.PromptSession ` does this for you.
463468
464469Example:
465470
466471.. code :: python
467472
468- from prompt_toolkit import prompt
473+ from prompt_toolkit import PromptSession
469474 from prompt_toolkit.history import InMemoryHistory
470475 from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
471476
472- history = InMemoryHistory ()
477+ session = PromptSession ()
473478
474479 while True :
475- text = prompt(' > ' , history = history , auto_suggest = AutoSuggestFromHistory())
480+ text = session. prompt(' > ' , auto_suggest = AutoSuggestFromHistory())
476481 print (' You said: %s ' % text)
477482
478483
@@ -566,7 +571,7 @@ By default, every prompt already has a set of key bindings which implements the
566571usual Vi or Emacs behaviour. We can extend this by passing another
567572:class: `~prompt_toolkit.key_binding.KeyBindings ` instance to the
568573``key_bindings `` argument of the :func: `~prompt_toolkit.shortcuts.prompt `
569- function.
574+ function or the :class: ` ~prompt_toolkit.shortcuts.PromptSession ` class .
570575
571576An example of a prompt that prints ``'hello world' `` when :kbd: `Control - T ` is pressed.
572577
@@ -674,7 +679,8 @@ Using control-space for completion
674679^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
675680
676681An popular short cut that people sometimes use it to use control-space for
677- opening the autocompletion menu.
682+ opening the autocompletion menu instead of the tab key. This can be done with
683+ the following key binding.
678684
679685.. code :: python
680686
@@ -710,15 +716,16 @@ of accepting and returning the input. The user will now have to press
710716:kbd: `Enter `.)
711717
712718It is possible to specify a continuation prompt. This works by passing a
713- ``get_continuation_tokens `` callable to ``prompt ``. This function can return a
714- list of ``(style, text) `` tuples. The width of the returned text should not
715- exceed the given width. (The width of the prompt margin is defined by the
716- prompt.)
719+ ``prompt_continuation `` callable to ``prompt ``. This function is supposed to
720+ return formatted text, or a list of ``(style, text) `` tuples. The width of the
721+ returned text should not exceed the given width. (The width of the prompt
722+ margin is defined by the prompt.)
717723
718724.. code :: python
719725
720726 def prompt_continuation (width ):
721- return [(' ' , ' .' * width)]
727+ return ' .' * width
728+ # Or: return [('', '.' * width)]
722729
723730 prompt(' > ' , multiline = True , prompt_continuation = prompt_continuation)
724731
@@ -756,7 +763,7 @@ Line wrapping
756763^^^^^^^^^^^^^
757764
758765Line wrapping is enabled by default. This is what most people are used to and
759- this is what GNU readline does. When it is disabled, the input string will
766+ this is what GNU Readline does. When it is disabled, the input string will
760767scroll horizontally.
761768
762769.. code :: python
@@ -793,14 +800,19 @@ interface to run in another thread. (If we have custom key bindings for
793800instance, it would be better to run them in the same thread as the other code.)
794801
795802The answer is to run the prompt_toolkit interface on top of the asyncio event
796- loop. Prompting the user for input is as simple as calling
803+ loop. First we have to tell prompt_toolkit to use the asyncio event loop. Then
804+ prompting the user for input is as simple as calling
797805:func: `~prompt_toolkit.shortcuts.prompt ` with the `async_=True ` argument.
798806
799807.. code :: python
800808
801809 from prompt_toolkit import prompt
810+ from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop
802811 from prompt_toolkit.patch_stdout import patch_stdout
803812
813+ # Tell prompt_toolkit to use the asyncio event loop.
814+ use_asyncio_event_loop()
815+
804816 async def my_coroutine ():
805817 while True :
806818 with patch_stdout():
0 commit comments