### Basic prompt_toolkit Usage Example Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/README.rst A simple example demonstrating how to get user input using the prompt function from the prompt_toolkit library. ```python from prompt_toolkit import prompt if __name__ == '__main__': answer = prompt('Give me some input: ') print('You said: %s' % answer) ``` -------------------------------- ### Simple Prompt Example Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/getting_started.md This is the most basic example of using the `prompt()` function to get input from the user, similar to Python's built-in `input()` function. ```python from prompt_toolkit import prompt text = prompt("Give me some input: ") print(f"You said: {text}") ``` -------------------------------- ### Initialize Application with Key Bindings Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/full_screen_apps.md Basic setup for an application with global key bindings. Ensure KeyBindings and Application are imported. ```python from prompt_toolkit import Application from prompt_toolkit.key_binding import KeyBindings kb = KeyBindings() app = Application(key_bindings=kb) app.run() ``` -------------------------------- ### Install prompt_toolkit using pip Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/README.rst Use this command to install the prompt_toolkit library via pip. ```bash pip install prompt_toolkit ``` -------------------------------- ### Install prompt_toolkit using Conda Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/README.rst Use this command to install the prompt_toolkit library via Conda. ```bash conda install -c https://conda.anaconda.org/conda-forge prompt_toolkit ``` -------------------------------- ### Install profiling tool Source: https://github.com/prompt-toolkit/python-prompt-toolkit/wiki/Profiling Install the 'profiling' package using pip. This tool can be used as a remote profiler. ```bash pip install profiling ``` -------------------------------- ### Launch application with remote debugger Source: https://github.com/prompt-toolkit/python-prompt-toolkit/wiki/Profiling Start your application with the profiling tool listening on a specific address and port. This is the first step in remote profiling. ```bash $ profiling view 127.0.0.1:8912 examples/get-input-vi-mode.py ``` -------------------------------- ### Create Buffer and Window Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/rendering_flow.md Instantiates a Buffer and wraps it in a BufferControl within a Window. This is a basic setup for displaying editable text. ```python from prompt_toolkit.enums import DEFAULT_BUFFER from prompt_toolkit.layout.containers import Window from prompt_toolkit.layout.controls import BufferControl from prompt_toolkit.buffer import Buffer b = Buffer(name=DEFAULT_BUFFER) Window(content=BufferControl(buffer=b)) ``` -------------------------------- ### Define UI Layout with Styles Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/styling.md Example of defining a UI layout using VSplit and HSplit, assigning style classes to different windows. ```python from prompt_toolkit.layout import VSplit, Window from prompt_toolkit.styles import Style layout = VSplit([ Window(BufferControl(...), style='class:left'), HSplit([ Window(BufferControl(...), style='class:top'), Window(BufferControl(...), style='class:bottom'), ], style='class:right') ]) style = Style([ ('left', 'bg:ansired'), ('top', 'fg:#00aaaa'), ('bottom', 'underline bold'), ]) ``` -------------------------------- ### Test with AppSession and DummyOutput Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/unit_testing.md Utilize `create_app_session` to set a consistent input/output for all prompt_toolkit applications within a context, useful when injection is not feasible. This example demonstrates printing text to a dummy output. ```python from prompt_toolkit.application import create_app_session from prompt_toolkit.shortcuts import print_formatted_text from prompt_toolkit.output import DummyOutput def test_something(): with create_app_session(output=DummyOutput()): ... print_formatted_text('Hello world') ... ``` -------------------------------- ### Detect prompt_toolkit Version Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/upgrading/3.0.md Check if the installed prompt_toolkit version starts with '3.'. This is useful for conditional logic during upgrades. ```python from prompt_toolkit import __version__ as ptk_version PTK3 = ptk_version.startswith('3.') ``` -------------------------------- ### Read User Input with prompt() Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/tutorials/repl.md Use the `prompt()` function from prompt_toolkit to accept user input. This basic example echoes the entered text back to the console. ```python from prompt_toolkit import prompt def main(): text = prompt('> ') print('You entered:', text) if __name__ == '__main__': main() ``` -------------------------------- ### Create a Basic Layout with VSplit Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/full_screen_apps.md Use VSplit to arrange controls horizontally. This example creates a layout with an editable buffer on the left and static text on the right, separated by a vertical line. ```python from prompt_toolkit import Application from prompt_toolkit.buffer import Buffer from prompt_toolkit.layout.containers import VSplit, Window from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl from prompt_toolkit.layout.layout import Layout buffer1 = Buffer() # Editable buffer. root_container = VSplit([ # One window that holds the BufferControl with the default buffer on # the left. Window(content=BufferControl(buffer=buffer1)), # A vertical line in the middle. We explicitly specify the width, to # make sure that the layout engine will not try to divide the whole # width by three for all these windows. The window will simply fill its # content by repeating this character. Window(width=1, char='|'), # Display the text 'Hello world' on the right. Window(content=FormattedTextControl(text='Hello world')), ]) layout = Layout(root_container) app = Application(layout=layout, full_screen=True) app.run() # You won't be able to Exit this app ``` -------------------------------- ### Custom Progress Bar Formatting (Apt-get Style) Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/progress_bars.md Customize the progress bar's appearance by providing a custom list of formatters and a style dictionary to the ProgressBar constructor. This example mimics an apt-get style progress bar. ```python from prompt_toolkit.shortcuts import ProgressBar from prompt_toolkit.styles import Style from prompt_toolkit.shortcuts.progress_bar import formatters import time style = Style.from_dict({ 'label': 'bg:#ffff00 #000000', 'percentage': 'bg:#ffff00 #000000', 'current': '#448844', 'bar': '', }) custom_formatters = [ formatters.Label(), formatters.Text(': [', style='class:percentage'), formatters.Percentage(), formatters.Text(']', style='class:percentage'), formatters.Text(' '), formatters.Bar(sym_a='#', sym_b='#', sym_c='.'), formatters.Text(' '), ] with ProgressBar(style=style, formatters=custom_formatters) as pb: for i in pb(range(1600), label='Installing'): time.sleep(.01) ``` -------------------------------- ### SQLite REPL with prompt-toolkit Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/tutorials/repl.md This script creates an interactive SQLite REPL. It uses prompt-toolkit for enhanced input handling, including SQL lexing and word completion. Ensure you have prompt-toolkit and Pygments installed. ```python #!/usr/bin/env python import sys import sqlite3 from prompt_toolkit import PromptSession from prompt_toolkit.completion import WordCompleter from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.styles import Style from pygments.lexers.sql import SqlLexer sql_completer = WordCompleter([ 'abort', 'action', 'add', 'after', 'all', 'alter', 'analyze', 'and', 'as', 'asc', 'attach', 'autoincrement', 'before', 'begin', 'between', 'by', 'cascade', 'case', 'cast', 'check', 'collate', 'column', 'commit', 'conflict', 'constraint', 'create', 'cross', 'current_date', 'current_time', 'current_timestamp', 'database', 'default', 'deferrable', 'deferred', 'delete', 'desc', 'detach', 'distinct', 'drop', 'each', 'else', 'end', 'escape', 'except', 'exclusive', 'exists', 'explain', 'fail', 'for', 'foreign', 'from', 'full', 'glob', 'group', 'having', 'if', 'ignore', 'immediate', 'in', 'index', 'indexed', 'initially', 'inner', 'insert', 'instead', 'intersect', 'into', 'is', 'isnull', 'join', 'key', 'left', 'like', 'limit', 'match', 'natural', 'no', 'not', 'notnull', 'null', 'of', 'offset', 'on', 'or', 'order', 'outer', 'plan', 'pragma', 'primary', 'query', 'raise', 'recursive', 'references', 'regexp', 'reindex', 'release', 'rename', 'replace', 'restrict', 'right', 'rollback', 'row', 'savepoint', 'select', 'set', 'table', 'temp', 'temporary', 'then', 'to', 'transaction', 'trigger', 'union', 'unique', 'update', 'using', 'vacuum', 'values', 'view', 'virtual', 'when', 'where', 'with', 'without'], ignore_case=True) style = Style.from_dict({ 'completion-menu.completion': 'bg:#008888 #ffffff', 'completion-menu.completion.current': 'bg:#00aaaa #000000', 'scrollbar.background': 'bg:#88aaaa', 'scrollbar.button': 'bg:#222222', }) def main(database): connection = sqlite3.connect(database) session = PromptSession( lexer=PygmentsLexer(SqlLexer), completer=sql_completer, style=style) while True: try: text = session.prompt('> ') except KeyboardInterrupt: continue # Control-C pressed. Try again. except EOFError: break # Control-D pressed. with connection: try: messages = connection.execute(text) except Exception as e: print(repr(e)) else: for message in messages: print(message) print('GoodBye!') if __name__ == '__main__': if len(sys.argv) < 2: db = ':memory:' else: db = sys.argv[1] main(db) ``` -------------------------------- ### Customize Completion Menu Styling Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/tutorials/repl.md Define a custom style for completion menus and apply it to a prompt session. This example uses `Style.from_dict` to set background and foreground colors for menu items and scrollbars. Requires `prompt_toolkit` and `pygments`. ```python from prompt_toolkit import PromptSession from prompt_toolkit.completion import WordCompleter from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.styles import Style from pygments.lexers.sql import SqlLexer sql_completer = WordCompleter([ 'abort', 'action', 'add', 'after', 'all', 'alter', 'analyze', 'and', 'as', 'asc', 'attach', 'autoincrement', 'before', 'begin', 'between', 'by', 'cascade', 'case', 'cast', 'check', 'collate', 'column', 'commit', 'conflict', 'constraint', 'create', 'cross', 'current_date', 'current_time', 'current_timestamp', 'database', 'default', 'deferrable', 'deferred', 'delete', 'desc', 'detach', 'distinct', 'drop', 'each', 'else', 'end', 'escape', 'except', 'exclusive', 'exists', 'explain', 'fail', 'for', 'foreign', 'from', 'full', 'glob', 'group', 'having', 'if', 'ignore', 'immediate', 'in', 'index', 'indexed', 'initially', 'inner', 'insert', 'instead', 'intersect', 'into', 'is', 'isnull', 'join', 'key', 'left', 'like', 'limit', 'match', 'natural', 'no', 'not', 'notnull', 'null', 'of', 'offset', 'on', 'or', 'order', 'outer', 'plan', 'pragma', 'primary', 'query', 'raise', 'recursive', 'references', 'regexp', 'reindex', 'release', 'rename', 'replace', 'restrict', 'right', 'rollback', 'row', 'savepoint', 'select', 'set', 'table', 'temp', 'temporary', 'then', 'to', 'transaction', 'trigger', 'union', 'unique', 'update', 'using', 'vacuum', 'values', 'view', 'virtual', 'when', 'where', 'with', 'without'], ignore_case=True) style = Style.from_dict({ 'completion-menu.completion': 'bg:#008888 #ffffff', 'completion-menu.completion.current': 'bg:#00aaaa #000000', 'scrollbar.background': 'bg:#88aaaa', 'scrollbar.button': 'bg:#222222', }) def main(): session = PromptSession( lexer=PygmentsLexer(SqlLexer), completer=sql_completer, style=style) while True: try: text = session.prompt('> ') except KeyboardInterrupt: continue except EOFError: break else: print('You entered:', text) print('GoodBye!') if __name__ == '__main__': main() ``` -------------------------------- ### Input Stream Processing Example Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/architecture.md Illustrates how the InputStream component translates terminal input like escape sequences into actionable events, such as mapping '\x1b[6~' to 'Keys.PageDown' and invoking the appropriate input processor. ```text +---------------------------------------------------------------+ | InputStream | | =========== | | - Parses the input stream coming from a VT100 | | compatible terminal. Translates it into data input | | and control characters. Calls the corresponding | | handlers of the `InputStreamHandler` instance. | | | | e.g. Translate '\x1b[6~' into "Keys.PageDown", call | | the `feed_key` method of `InputProcessor`. | +---------------------------------------------------------------+ | v +---------------------------------------------------------------+ | | InputStreamHandler | | ================== | | - Has a `Registry` of key bindings, it calls the | | bindings according to the received keys and the | | input mode. | | | | We have Vi and Emacs bindings. +---------------------------------------------------------------+ | | v +---------------------------------------------------------------+ | | Key bindings | | ============ | | - Every key binding consists of a function that | | receives an `Event` and usually it operates on | | the `Buffer` object. (It could insert data or | | move the cursor for example.) | +---------------------------------------------------------------+ | | | Most of the key bindings operate on a `Buffer` object, but | they don't have to. They could also change the visibility | of a menu for instance, or change the color scheme. | v +---------------------------------------------------------------+ | | Buffer | | ====== | | - Contains a data structure to hold the current | | input (text and cursor position). This class | | implements all text manipulations and cursor | | movements (Like e.g. cursor_forward, insert_char | | or delete_word.) | | | | +-----------------------------------------------+ | | | Document (text, cursor_position) | | | | ================================ | | | | Accessed as the `document` property of the | | | | `Buffer` class. This is a wrapper around the | | | | text and cursor position, and contains | | | | methods for querying this data , e.g. to give | | | the text before the cursor. | | | +-----------------------------------------------+ | +---------------------------------------------------------------+ | Normally after every key press, the output will be rendered again. This happens in the event loop of the `Application` where `Renderer.render` is called. | v +---------------------------------------------------------------+ | | Layout | | ====== | | - When the renderer should redraw, the renderer | | asks the layout what the output should look like. | | - The layout operates on a `Screen` object that he | | received from the `Renderer` and will put the | | toolbars, menus, highlighted content and prompt | | in place. | | | | +-----------------------------------------------+ | | | Menus, toolbars, prompt | | | | ======================= | | | | | | | +-----------------------------------------------+ | +---------------------------------------------------------------+ | | v +---------------------------------------------------------------+ | | Renderer | | ======== | | - Calculates the difference between the last output | | and the new one and writes it to the terminal | ``` -------------------------------- ### Print Pygments (Token, text) Tuples Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/printing_text.md Wrap a list of Pygments (Token, text) tuples in a `PygmentsTokens` object to print them with prompt-toolkit. Ensure `pygments` and `prompt_toolkit` are installed. ```python from pygments.token import Token from prompt_toolkit import print_formatted_text from prompt_toolkit.formatted_text import PygmentsTokens text = [ (Token.Keyword, 'print'), (Token.Punctuation, '('), (Token.Literal.String.Double, '"'), (Token.Literal.String.Double, 'hello'), (Token.Literal.String.Double, '"'), (Token.Punctuation, ')'), (Token.Text, '\n'), ] print_formatted_text(PygmentsTokens(text)) ``` -------------------------------- ### Set Default Input Value Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Provide a default value for the prompt, which will be pre-filled when the prompt appears. This example uses the current user's login name as the default. ```python from prompt_toolkit import prompt import getpass prompt("What is your name: ", default=f"{getpass.getuser()}") ``` -------------------------------- ### Use Control-Space for Autocompletion Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Configure the 'control-space' key combination to trigger autocompletion. If autocompletion is already active, it selects the next completion; otherwise, it starts the completion menu. ```python kb = KeyBindings() @kb.add("c-space") def _(event): """ Initialize autocompletion, or select the next completion. """ buff = event.app.current_buffer if buff.complete_state: buff.complete_next() else: buff.start_completion(select_first=False) ``` -------------------------------- ### Conditional Key Bindings Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Enable key bindings based on a condition using a `Filter`, typically a `Condition` instance. This example activates a binding only in the second half of each minute. ```python from prompt_toolkit import prompt from prompt_toolkit.filters import Condition from prompt_toolkit.key_binding import KeyBindings import datetime bindings = KeyBindings() @Condition def is_active(): """ Only activate key binding on the second half of each minute. """ return datetime.datetime.now().second > 30 @bindings.add("c-t", filter=is_active) def _(event): # ... pass prompt("> ", key_bindings=bindings) ``` -------------------------------- ### Read raw key presses without a prompt Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md This example demonstrates how to read individual key presses from stdin without rendering a visible prompt. It uses `create_input`, `raw_mode`, and `attach` to handle key events asynchronously. Pressing Control+C will exit the loop. ```python import asyncio from prompt_toolkit.input import create_input from prompt_toolkit.keys import Keys async def main() -> None: done = asyncio.Event() input = create_input() def keys_ready(): for key_press in input.read_keys(): print(key_press) if key_press.key == Keys.ControlC: done.set() with input.raw_mode(): with input.attach(keys_ready): await done.wait() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Remove asyncio Event Loop Setup Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/upgrading/3.0.md In prompt_toolkit 3.0, asyncio event loop integration is the default. Remove explicit calls to `use_asyncio_event_loop()` to avoid redundant configuration. ```default from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop use_asyncio_event_loop() ``` -------------------------------- ### Customize Pygments Token Styling Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/printing_text.md Apply custom styles to Pygments tokens by mapping Pygments token types to prompt-toolkit class names within a `Style` dictionary. This example applies underlining to keywords and a background/foreground color to string literals. ```python from prompt_toolkit.styles import Style from prompt_toolkit import print_formatted_text from prompt_toolkit.formatted_text import PygmentsTokens # Assuming 'tokens' is a list of Pygments tokens defined elsewhere. # Example: tokens = list(pygments.lex('print("Hello")', lexer=PythonLexer())) style = Style.from_dict({ 'pygments.keyword': 'underline', 'pygments.literal.string': 'bg:#00ff00 #ffffff', }) # print_formatted_text(PygmentsTokens(tokens), style=style) ``` -------------------------------- ### Create a Simple Full Screen Application Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/full_screen_apps.md Instantiate an Application with `full_screen=True` to run in the alternate screen buffer. The application will display a default message if no layout is specified. Press ENTER to quit. ```python from prompt_toolkit import Application app = Application(full_screen=True) app.run() ``` -------------------------------- ### Test Prompt Session with Pipe Input and Dummy Output Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/unit_testing.md Use `create_pipe_input` and `DummyOutput` to simulate user input and capture output for testing `PromptSession`. Remember to send '\n' to accept the prompt. ```python from prompt_toolkit.shortcuts import PromptSession from prompt_toolkit.input import create_pipe_input from prompt_toolkit.output import DummyOutput def test_prompt_session(): with create_pipe_input() as inp: inp.send_text("hello\n") session = PromptSession( input=inp, output=DummyOutput(), ) result = session.prompt() assert result == "hello" ``` -------------------------------- ### Define Styles for Combined Class Names Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/styling.md Example of defining a style rule that applies to elements having both 'header' and 'left' class names. ```python style = Style([ ('header left', 'underline'), ]) ``` -------------------------------- ### Define Basic Key Bindings Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/key_bindings.md Create a KeyBindings instance and add handlers for single key presses like 'a' or key combinations like Control-T. ```python from prompt_toolkit.key_binding import KeyBindings bindings = KeyBindings() @bindings.add('a') def _(event): """ Do something if 'a' has been pressed. """ ... @bindings.add('c-t') def _(event): """ Do something if Control-T has been pressed. """ ... ``` -------------------------------- ### Focus a Window using get_app() Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/full_screen_apps.md Obtain the current application instance using get_app() and then focus a specific window. This is typically done within key bindings. ```python from prompt_toolkit.application import get_app # This window was created earlier. w = Window() # ... # Now focus it. get_app().layout.focus(w) ``` -------------------------------- ### Evaluate Filter Value Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/filters.md Demonstrates how to get the current boolean value of a filter by calling it like a function. This is useful for debugging or conditional logic outside of key bindings. ```python print(is_searching()) ``` -------------------------------- ### Launch profiling screen Source: https://github.com/prompt-toolkit/python-prompt-toolkit/wiki/Profiling Open the profiling interface in a separate terminal. Connect to the same address and port used to launch the application. ```bash $ profiling view 127.0.0.1:8912 ``` -------------------------------- ### Bind to Any Key Following a Specific Key Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/key_bindings.md Use the '' wildcard to create bindings that trigger for any key press following a specified key. This allows for flexible handling of sequences. ```python from prompt_toolkit.key_binding import KeyBindings bindings = KeyBindings() @bindings.add('a', '') def _(event): """ This will handle aa, ab, ac, etcetera. """ # The event object can be inspected to determine the exact key pressed. ``` -------------------------------- ### Custom Prompt Styling with Style.from_dict Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Define custom syntax highlighting rules for prompts using a dictionary with `Style.from_dict`. ```python from pygments.lexers.html import HtmlLexer from prompt_toolkit.shortcuts import prompt from prompt_toolkit.styles import Style from prompt_toolkit.lexers import PygmentsLexer our_style = Style.from_dict({ "pygments.comment": "#888888 bold", "pygments.keyword": "#ff88ff bold", }) text = prompt( "Enter HTML: ", lexer=PygmentsLexer(HtmlLexer), style=our_style ) ``` -------------------------------- ### Implement Custom Number Validator Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Create a custom validator by subclassing `Validator` and implementing the `validate` method. This example validates that input consists only of digits, raising `ValidationError` with a specific cursor position for non-numeric characters. ```python from prompt_toolkit.validation import Validator, ValidationError from prompt_toolkit import prompt class NumberValidator(Validator): def validate(self, document): text = document.text if text and not text.isdigit(): i = 0 # Get index of first non numeric character. # We want to move the cursor here. for i, c in enumerate(text): if not c.isdigit(): break raise ValidationError( message="This input contains non-numeric characters", cursor_position=i ) number = int(prompt("Give a number: ", validator=NumberValidator())) print(f"You said: {number}") ``` -------------------------------- ### SQL Auto-completion REPL Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/tutorials/repl.md This snippet creates an auto-completing and syntax-highlighting REPL for SQL commands. It uses WordCompleter for keyword suggestions and PygmentsLexer for SQL syntax highlighting. The completer is configured to ignore case. ```python from prompt_toolkit import PromptSession from prompt_toolkit.completion import WordCompleter from prompt_toolkit.lexers import PygmentsLexer from pygments.lexers.sql import SqlLexer sql_completer = WordCompleter([ 'abort', 'action', 'add', 'after', 'all', 'alter', 'analyze', 'and', 'as', 'asc', 'attach', 'autoincrement', 'before', 'begin', 'between', 'by', 'cascade', 'case', 'cast', 'check', 'collate', 'column', 'commit', 'conflict', 'constraint', 'create', 'cross', 'current_date', 'current_time', 'current_timestamp', 'database', 'default', 'deferrable', 'deferred', 'delete', 'desc', 'detach', 'distinct', 'drop', 'each', 'else', 'end', 'escape', 'except', 'exclusive', 'exists', 'explain', 'fail', 'for', 'foreign', 'from', 'full', 'glob', 'group', 'having', 'if', 'ignore', 'immediate', 'in', 'index', 'indexed', 'initially', 'inner', 'insert', 'instead', 'intersect', 'into', 'is', 'isnull', 'join', 'key', 'left', 'like', 'limit', 'match', 'natural', 'no', 'not', 'notnull', 'null', 'of', 'offset', 'on', 'or', 'order', 'outer', 'plan', 'pragma', 'primary', 'query', 'raise', 'recursive', 'references', 'regexp', 'reindex', 'release', 'rename', 'replace', 'restrict', 'right', 'rollback', 'row', 'savepoint', 'select', 'set', 'table', 'temp', 'temporary', 'then', 'to', 'transaction', 'trigger', 'union', 'unique', 'update', 'using', 'vacuum', 'values', 'view', 'virtual', 'when', 'where', 'with', 'without'], ignore_case=True) def main(): session = PromptSession( lexer=PygmentsLexer(SqlLexer), completer=sql_completer) while True: try: text = session.prompt('> ') except KeyboardInterrupt: continue except EOFError: break else: print('You entered:', text) print('GoodBye!') if __name__ == '__main__': main() ``` -------------------------------- ### Basic Prompt Session with History Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Initialize a `PromptSession` which automatically includes an `InMemoryHistory` to store previously entered commands. This enables features like recalling commands with the up-arrow key. ```python from prompt_toolkit import PromptSession session = PromptSession() while True: session.prompt() ``` -------------------------------- ### Toggle Emacs/Vi Editing Mode with F4 Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Dynamically switch between Emacs and Vi editing modes by changing the `editing_mode` attribute of the application. This example uses the F4 key to toggle the mode and displays the current mode in the bottom toolbar. ```python from prompt_toolkit import prompt from prompt_toolkit.application.current import get_app from prompt_toolkit.enums import EditingMode from prompt_toolkit.key_binding import KeyBindings def run(): # Create a set of key bindings. bindings = KeyBindings() # Add an additional key binding for toggling this flag. @bindings.add("f4") def _(event): """ Toggle between Emacs and Vi mode. """ app = event.app if app.editing_mode == EditingMode.VI: app.editing_mode = EditingMode.EMACS else: app.editing_mode = EditingMode.VI # Add a toolbar at the bottom to display the current input mode. def bottom_toolbar(): """ Display the current input mode. """ text = "Vi" if get_app().editing_mode == EditingMode.VI else "Emacs" return [ ("class:toolbar", " [F4] %s " % text) ] prompt("> ", key_bindings=bindings, bottom_toolbar=bottom_toolbar) run() ``` -------------------------------- ### Apply Multiple Class Names to an Element Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/styling.md Shows how to assign multiple class names to a UI element, which can be done using a comma-separated list or repeated 'class:' prefixes. ```python Window(BufferControl(...), style='class:left,bottom') ``` ```python Window(BufferControl(...), style='class:left class:bottom') ``` -------------------------------- ### Add Custom Key Bindings Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Extend default key bindings by passing a `KeyBindings` instance to the `key_bindings` argument. Use `run_in_terminal` for actions that print output to avoid mixing with the prompt. ```python from prompt_toolkit import prompt from prompt_toolkit.application import run_in_terminal from prompt_toolkit.key_binding import KeyBindings bindings = KeyBindings() @bindings.add("c-t") def _(event): """ Say "hello" when `c-t` is pressed. """ def print_hello(): print("hello world") run_in_terminal(print_hello) @bindings.add("c-x") def _(event): """ Exit when `c-x` is pressed. """ event.app.exit() text = prompt("> ", key_bindings=bindings) print(f"You said: {text}") ``` -------------------------------- ### Use Pygments Style with prompt_toolkit Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Applies a Pygments style (e.g., TangoStyle) to the prompt and lexer. Requires importing necessary classes from prompt_toolkit and Pygments. ```python from prompt_toolkit.shortcuts import prompt from prompt_toolkit.styles import style_from_pygments_cls from prompt_toolkit.lexers import PygmentsLexer from pygments.styles.tango import TangoStyle from pygments.lexers.html import HtmlLexer tango_style = style_from_pygments_cls(TangoStyle) text = prompt( "Enter HTML: ", lexer=PygmentsLexer(HtmlLexer), style=tango_style ) ``` -------------------------------- ### Create a Simple Progress Bar Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/progress_bars.md Use the ProgressBar context manager to wrap an iterable for displaying progress. Ensure the iterable's total length is known or provided. ```python from prompt_toolkit.shortcuts import ProgressBar import time with ProgressBar() as pb: for i in pb(range(800)): time.sleep(.01) ``` -------------------------------- ### Create an Input Dialog Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/dialogs.md Use `input_dialog()` to prompt the user for text input. The function returns the entered string upon completion. ```python from prompt_toolkit.shortcuts import input_dialog text = input_dialog( title='Input dialog example', text='Please type your name:').run() ``` -------------------------------- ### Enable Vi Input Mode Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Switch to Vi key bindings by setting the `vi_mode` argument to `True` in the `prompt()` function. Emacs bindings are used by default. ```python from prompt_toolkit import prompt prompt("> ", vi_mode=True) ``` -------------------------------- ### Enable Completion While Typing Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Configure the prompt to automatically show completions as the user types by setting `complete_while_typing=True`. This feature is incompatible with `enable_history_search`. ```python text = prompt( "Enter HTML: ", completer=my_completer, complete_while_typing=True ) ``` -------------------------------- ### Loop REPL with PromptSession and History Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/tutorials/repl.md Implement a continuous REPL loop using `PromptSession`. This session manages input history, allowing users to navigate previous entries with the up-arrow key. It also handles `KeyboardInterrupt` (Ctrl+C) and `EOFError` (Ctrl+D) for graceful exiting. ```python from prompt_toolkit import PromptSession def main(): session = PromptSession() while True: try: text = session.prompt('> ') except KeyboardInterrupt: continue except EOFError: break else: print('You entered:', text) print('GoodBye!') if __name__ == '__main__': main() ``` -------------------------------- ### Style Individual Completions Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Provide custom styling for completions by passing a style string to the `Completion` constructor. Styles can be color combinations, underlines, or class names. ```python from prompt_toolkit.completion import Completer, Completion class MyCustomCompleter(Completer): def get_completions(self, document, complete_event): # Display this completion, black on yellow. yield Completion( "completion1", start_position=0, style="bg:ansiyellow fg:ansiblack" ) # Underline completion. yield Completion( "completion2", start_position=0, style="underline" ) # Specify class name, which will be looked up in the style sheet. yield Completion( "completion3", start_position=0, style="class:special-completion" ) ``` -------------------------------- ### Set Color Depth via Environment Variable Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/styling.md Configure the default color depth for prompt_toolkit applications by setting the PROMPT_TOOLKIT_COLOR_DEPTH environment variable. Options include DEPTH_1_BIT, DEPTH_4_BIT, DEPTH_8_BIT, and DEPTH_24_BIT. ```shell # export PROMPT_TOOLKIT_COLOR_DEPTH=DEPTH_1_BIT export PROMPT_TOOLKIT_COLOR_DEPTH=DEPTH_4_BIT # export PROMPT_TOOLKIT_COLOR_DEPTH=DEPTH_8_BIT # export PROMPT_TOOLKIT_COLOR_DEPTH=DEPTH_24_BIT ``` -------------------------------- ### Create a Custom Completer Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Implement a custom completer by subclassing `Completer` and defining the `get_completions` method. This method should yield `Completion` objects. ```python from prompt_toolkit import prompt from prompt_toolkit.completion import Completer, Completion class MyCustomCompleter(Completer): def get_completions(self, document, complete_event): yield Completion("completion", start_position=0) text = prompt("> ", completer=MyCustomCompleter()) ``` -------------------------------- ### Add Key Bindings and Toolbar to ProgressBar Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/progress_bars.md Use `KeyBindings` to define custom actions triggered by key presses. The `bottom_toolbar` displays hints for available key bindings. `patch_stdout` is essential for allowing prints within the progress bar context. ```python from prompt_toolkit import HTML from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.patch_stdout import patch_stdout from prompt_toolkit.shortcuts import ProgressBar import os import time import signal bottom_toolbar = HTML(' [f] Print "f" [x] Abort.') # Create custom key bindings first. kb = KeyBindings() cancel = [False] @kb.add('f') def _(event): print('You pressed `f`.') @kb.add('x') def _(event): """ Send Abort (control-c) signal. """ cancel[0] = True os.kill(os.getpid(), signal.SIGINT) # Use `patch_stdout`, to make sure that prints go above the # application. with patch_stdout(): with ProgressBar(key_bindings=kb, bottom_toolbar=bottom_toolbar) as pb: for i in pb(range(800)): time.sleep(.01) # Stop when the cancel flag has been set. if cancel[0]: break ``` -------------------------------- ### Use Formatted Text for Completion Display Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Enhance completion display by using formatted text, such as HTML, for the `display` attribute. This allows for rich text rendering within completions. ```python from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.formatted_text import HTML class MyCustomCompleter(Completer): def get_comcompletions(self, document, complete_event): yield Completion( "completion1", start_position=0, display=HTML("completion1"), style="bg:ansiyellow" ) ``` -------------------------------- ### Add Right Prompt (RPROMPT) Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Provide a callable or plain text to the `rprompt` argument of `prompt()` for a right-aligned prompt. Supports formatted text like HTML and custom styling. ```python from prompt_toolkit import prompt from prompt_toolkit.styles import Style example_style = Style.from_dict({ "rprompt": "bg:#ff0066 #ffffff", }) def get_rprompt(): return "" answer = prompt("> ", rprompt=get_rprompt, style=example_style) ``` -------------------------------- ### Combine Class Names and Inline Styling Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/styling.md Demonstrates how to combine a class name with inline styling, where the inline style overrides the class style. ```python Window(BufferControl(...), style='class:header bg:red') ``` -------------------------------- ### Create a Password Input Dialog Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/dialogs.md Configure `input_dialog()` with `password=True` to create a password input field that masks user input. ```python from prompt_toolkit.shortcuts import input_dialog text = input_dialog( title='Input dialog example', text='Please type your name:', password=True).run() ``` -------------------------------- ### Add SQL Syntax Highlighting to REPL Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/tutorials/repl.md Enhance the REPL by adding SQL syntax highlighting. This is achieved by wrapping a Pygments SQL lexer (`SqlLexer`) with `PygmentsLexer` and passing it to the `PromptSession`. ```python from prompt_toolkit import PromptSession from prompt_toolkit.lexers import PygmentsLexer from pygments.lexers.sql import SqlLexer def main(): session = PromptSession(lexer=PygmentsLexer(SqlLexer)) while True: try: text = session.prompt('> ') except KeyboardInterrupt: continue except EOFError: break else: print('You entered:', text) print('GoodBye!') if __name__ == '__main__': main() ``` -------------------------------- ### Handle Alt/Meta/Option Key Presses Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/advanced_topics/key_bindings.md Use 'escape' followed by the character key to bind alt, option, or meta key combinations. This approach is necessary because terminals often translate these keys into an escape sequence. ```python from prompt_toolkit.key_binding import KeyBindings bindings = KeyBindings() @bindings.add('escape', 'f') def _(event): """ Do something if alt-f or meta-f have been pressed. """ pass ``` -------------------------------- ### Print Plain Text with prompt-toolkit Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/printing_text.md Import and use print_formatted_text to display simple strings. This function handles terminal-specific output for colors and formatting. ```python from prompt_toolkit import print_formatted_text print_formatted_text('Hello world') ``` ```python from prompt_toolkit import print_formatted_text as print print('Hello world') ``` -------------------------------- ### Prompt Session with File History Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Configure a `PromptSession` to use `FileHistory` for persistent storage of command history. This ensures that previously entered commands are available across different sessions by saving them to a specified file. ```python from prompt_toolkit import PromptSession from prompt_toolkit.history import FileHistory session = PromptSession(history=FileHistory("~/.myhistory")) while True: session.prompt() ``` -------------------------------- ### Display a Button Dialog Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/dialogs.md Use `button_dialog()` to offer choices as clickable buttons. Each button is defined by a label and a return value. ```python from prompt_toolkit.shortcuts import button_dialog result = button_dialog( title='Button dialog example', text='Do you want to confirm?', buttons=[ ('Yes', True), ('No', False), ('Maybe...', None) ], ).run() ``` -------------------------------- ### Syntax Highlighting with PygmentsLexer Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Enable syntax highlighting for user input by integrating Pygments lexers using `PygmentsLexer`. ```python from pygments.lexers.html import HtmlLexer from prompt_toolkit.shortcuts import prompt from prompt_toolkit.lexers import PygmentsLexer text = prompt("Enter HTML: ", lexer=PygmentsLexer(HtmlLexer)) print(f"You said: {text}") ``` -------------------------------- ### Display a Yes/No Confirmation Dialog Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/dialogs.md Use `yes_no_dialog()` to present a confirmation prompt. It returns a boolean value based on the user's choice (True for Yes, False for No). ```python from prompt_toolkit.shortcuts import yes_no_dialog result = yes_no_dialog( title='Yes/No dialog example', text='Do you want to confirm?').run() ``` -------------------------------- ### Coloring the Prompt Itself with Formatted Text Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Applies custom colors and styles to different parts of the prompt message using a Style dictionary and formatted text tuples. Each tuple maps a class name to its style. ```python from prompt_toolkit.shortcuts import prompt from prompt_toolkit.styles import Style style = Style.from_dict({ "username": "#884444", "at": "#00aa00", "colon": "#0000aa", "pound": "#00aa00", "host": "#00ffff bg:#444400", "path": "ansicyan underline", }) message = [ ("class:username", "john"), ("class:at", "@"), ("class:host", "localhost"), ("class:colon", ":"), ("class:path", "/user/john"), ("class:pound", "# "), ] text = prompt(message, style=style) ``` -------------------------------- ### Display a Message Box Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/dialogs.md Use `message_dialog()` to show a simple message box. It displays text and waits for user interaction to close. ```python from prompt_toolkit.shortcuts import message_dialog message_dialog( title='Example dialog window', text='Do you want to continue?\nPress ENTER to quit.').run() ``` -------------------------------- ### Enable Multiline Input Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Allow users to input multiple lines by setting `multiline=True`. The Enter key inserts a newline, and `Meta+Enter` (or `Escape` then `Enter`) accepts the input. ```python from prompt_toolkit import prompt prompt("> ", multiline=True) ``` -------------------------------- ### Auto Suggestion from History Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Enable auto-suggestion based on command history using `AutoSuggestFromHistory`. When a user types, prompt-toolkit will suggest completions from previous inputs that match the current text. A `PromptSession` is recommended to manage history sharing. ```python from prompt_toolkit import PromptSession from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory session = PromptSession() while True: text = session.prompt("> ", auto_suggest=AutoSuggestFromHistory()) print(f"You said: {text}") ``` -------------------------------- ### Basic Choice Input Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_a_choice.md Use this function to prompt the user to select an option from a predefined list. The function returns the key of the selected option. ```python from prompt_toolkit.shortcuts import choice result = choice( message="Please choose a dish:", options=[ ("pizza", "Pizza with mushrooms"), ("salad", "Salad with tomatoes"), ("sushi", "Sushi"), ], default="salad", ) print(f"You have chosen: {result}") ``` -------------------------------- ### Enable Asynchronous Completion Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Run completion generation in a background thread to prevent UI freezing by setting `complete_in_thread=True`. This is useful for time-consuming completion tasks. ```python text = prompt("> ", completer=MyCustomCompleter(), complete_in_thread=True) ``` -------------------------------- ### Enable Mouse Support Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/asking_for_input.md Enable mouse support for actions like cursor positioning, scrolling in multiline inputs, and clicking in the autocompletion menu by setting `mouse_support=True`. ```python from prompt_toolkit import prompt prompt("What is your name: ", mouse_support=True) ``` -------------------------------- ### Create Formatted Text with (style, text) Tuples Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/printing_text.md Manually construct formatted text as a list of (style, text) tuples using the FormattedText class. This provides fine-grained control over styling, allowing direct specification of colors and styles. ```python from prompt_toolkit import print_formatted_text from prompt_toolkit.formatted_text import FormattedText text = FormattedText([ ('#ff0066', 'Hello'), ('', ' '), ('#44ff00 italic', 'World'), ]) print_formatted_text(text) ``` -------------------------------- ### Default Progress Bar Formatting Source: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/main/docs/pages/progress_bars.md This snippet shows the default sequence of formatters used by prompt-toolkit's ProgressBar to render the progress bar visualization. ```python from prompt_toolkit.shortcuts.progress_bar.formatters import * default_formatting = [ Label(), Text(' '), Percentage(), Text(' '), Bar(), Text(' '), Progress(), Text(' '), Text('eta [', style='class:time-left'), TimeLeft(), Text(']', style='class:time-left'), Text(' '), ] ```