CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-prompt-toolkit

Library for building powerful interactive command lines in Python

Pending
Overview
Eval results
Files

prompts.mddocs/

Text Input and Prompting

Simple prompt functions and advanced prompt sessions with history, completion, validation, and auto-suggestions. These provide the primary interface for collecting user input in command-line applications.

Capabilities

Simple Prompt Function

The prompt() function provides a simple interface for collecting user input with optional features like default values, password masking, and multi-line input.

def prompt(
    message="",
    default="",
    password=False,
    multiline=False,
    complete_style=CompleteStyle.COLUMN,
    history=None,
    auto_suggest=None,
    completer=None,
    validator=None,
    bottom_toolbar=None,
    style=None,
    color_depth=None,
    cursor=CursorShape.BLOCK,
    include_default_pygments_style=True,
    lexer=None,
    reserve_space_for_menu=8,
    **kwargs
):
    """
    Prompt user for input with various options.
    
    Parameters:
    - message: str, prompt message to display
    - default: str, default value if user enters nothing
    - password: bool, mask input for password entry
    - multiline: bool, allow multi-line input
    - complete_style: CompleteStyle, how to display completions
    - history: History instance for command history
    - auto_suggest: AutoSuggest instance for suggestions
    - completer: Completer instance for auto-completion
    - validator: Validator instance for input validation
    - bottom_toolbar: toolbar content for bottom of screen
    - style: Style instance for visual formatting
    - color_depth: ColorDepth for color support level
    - lexer: Lexer instance for syntax highlighting
    
    Returns:
    str: User input text
    
    Raises:
    KeyboardInterrupt: On Ctrl-C
    EOFError: On Ctrl-D or EOF
    """

PromptSession Class

Advanced prompt session class that can be reused multiple times while maintaining state like history and configuration.

class PromptSession:
    def __init__(
        self,
        message="",
        multiline=False,
        wrap_lines=True,
        complete_style=CompleteStyle.COLUMN,
        history=None,
        auto_suggest=None,
        completer=None,
        validator=None,
        bottom_toolbar=None,
        style=None,
        color_depth=None,
        cursor=CursorShape.BLOCK,
        include_default_pygments_style=True,
        lexer=None,
        reserve_space_for_menu=8,
        **kwargs
    ):
        """
        Create a reusable prompt session.
        
        Parameters:
        - message: str, default prompt message
        - multiline: bool, allow multi-line input by default
        - wrap_lines: bool, wrap long lines in display
        - complete_style: CompleteStyle, completion display style
        - history: History instance for command history
        - auto_suggest: AutoSuggest instance for suggestions
        - completer: Completer instance for auto-completion
        - validator: Validator instance for input validation
        - bottom_toolbar: toolbar content for bottom of screen
        - style: Style instance for visual formatting
        - color_depth: ColorDepth for color support level
        - lexer: Lexer instance for syntax highlighting
        """
        
    def prompt(self, message=None, **kwargs):
        """
        Show prompt and collect user input.
        
        Parameters:
        - message: str, override default message
        - **kwargs: additional options to override session defaults
        
        Returns:
        str: User input text
        
        Raises:
        KeyboardInterrupt: On Ctrl-C
        EOFError: On Ctrl-D or EOF
        """

Choice Selection

Functions for presenting users with multiple choice selections.

def choice(
    choices,
    message="Please choose: ",
    default=None,
    style=None,
    **kwargs
):
    """
    Present user with a list of choices to select from.
    
    Parameters:
    - choices: List of choice options
    - message: str, prompt message
    - default: default choice if any
    - style: Style instance for formatting
    
    Returns:
    Selected choice value
    """

def confirm(message="Confirm?", default=False):
    """
    Show yes/no confirmation prompt.
    
    Parameters:
    - message: str, confirmation message
    - default: bool, default choice (True=Yes, False=No)
    
    Returns:
    bool: True for yes, False for no
    """

def create_confirm_session(message="Confirm?", suffix=" (y/n) "):
    """
    Create a reusable confirmation prompt session.
    
    Parameters:
    - message: str, confirmation message
    - suffix: str, suffix to append to message
    
    Returns:
    PromptSession configured for yes/no input
    """

Dialog Functions

Pre-built dialog functions for common user interaction patterns.

def input_dialog(
    title="",
    text="",
    ok_text="OK",
    cancel_text="Cancel",
    completer=None,
    validator=None,
    password=False,
    style=None,
    **kwargs
):
    """
    Show input dialog box.
    
    Parameters:
    - title: str, dialog title
    - text: str, dialog message text
    - ok_text: str, OK button text
    - cancel_text: str, Cancel button text
    - completer: Completer for input field
    - validator: Validator for input field
    - password: bool, mask input
    - style: Style for dialog
    
    Returns:
    str or None: Input text or None if cancelled
    """

def message_dialog(
    title="",
    text="",
    ok_text="OK",
    style=None,
    **kwargs
):
    """
    Show message dialog box.
    
    Parameters:
    - title: str, dialog title
    - text: str, message text to display
    - ok_text: str, OK button text
    - style: Style for dialog
    
    Returns:
    None
    """

def yes_no_dialog(
    title="",
    text="",
    yes_text="Yes",  
    no_text="No",
    style=None,
    **kwargs
):
    """
    Show yes/no confirmation dialog.
    
    Parameters:
    - title: str, dialog title
    - text: str, confirmation message
    - yes_text: str, Yes button text
    - no_text: str, No button text
    - style: Style for dialog
    
    Returns:
    bool: True for yes, False for no
    """

def button_dialog(
    title="",
    text="",
    buttons=None,
    style=None,
    **kwargs
):
    """
    Show dialog with custom buttons.
    
    Parameters:
    - title: str, dialog title
    - text: str, dialog message
    - buttons: List of button specifications
    - style: Style for dialog
    
    Returns:
    Button result value
    """

def radiolist_dialog(
    title="",
    text="",
    ok_text="OK",
    cancel_text="Cancel", 
    values=None,
    default=None,
    style=None,
    **kwargs
):
    """
    Show radio button selection dialog.
    
    Parameters:
    - title: str, dialog title
    - text: str, dialog message
    - ok_text: str, OK button text
    - cancel_text: str, Cancel button text
    - values: List of (value, label) tuples
    - default: default selected value
    - style: Style for dialog
    
    Returns:
    Selected value or None if cancelled
    """

def checkboxlist_dialog(
    title="",
    text="",
    ok_text="OK",
    cancel_text="Cancel",
    values=None,
    default_values=None,
    style=None,
    **kwargs
):
    """
    Show checkbox selection dialog.
    
    Parameters:
    - title: str, dialog title
    - text: str, dialog message  
    - ok_text: str, OK button text
    - cancel_text: str, Cancel button text
    - values: List of (value, label) tuples
    - default_values: List of initially selected values
    - style: Style for dialog
    
    Returns:
    List of selected values or None if cancelled
    """

def progress_dialog(
    title="",
    text="",
    run_callback=None,
    style=None,
    **kwargs
):
    """
    Show progress dialog with progress bar.
    
    Parameters:
    - title: str, dialog title
    - text: str, dialog message
    - run_callback: Function to execute with progress updates
    - style: Style for dialog
    
    Returns:
    Callback result
    """

Usage Examples

Basic Prompting

from prompt_toolkit import prompt

# Simple input
name = prompt('Enter your name: ')
print(f'Hello {name}!')

# Prompt with default value
city = prompt('Enter city: ', default='New York')

# Password input (masked)
password = prompt('Password: ', password=True)

# Multi-line input
text = prompt('Enter multi-line text (press ESC then Enter to finish): ',
              multiline=True)

Prompt Session with History

from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory

# Create session with file-based history
session = PromptSession(
    message='> ',
    history=FileHistory('.myapp_history'),
    auto_suggest=AutoSuggestFromHistory()
)

# Use session multiple times
while True:
    try:
        command = session.prompt()
        if command.lower() == 'exit':
            break
        print(f'You entered: {command}')
    except (EOFError, KeyboardInterrupt):
        break

Prompt with Validation

from prompt_toolkit import prompt
from prompt_toolkit.validation import Validator, ValidationError
import re

class EmailValidator(Validator):
    def validate(self, document):
        text = document.text
        if not re.match(r'^[^@]+@[^@]+\.[^@]+$', text):
            raise ValidationError(
                message='Invalid email format',
                cursor_position=len(text)
            )

# Prompt with email validation
email = prompt('Enter email: ', validator=EmailValidator())
print(f'Email: {email}')

Prompt with Completion

from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter

# Create completer with predefined words
completer = WordCompleter([
    'hello', 'world', 'python', 'programming',
    'prompt-toolkit', 'completion', 'validation'
])

# Prompt with tab completion
text = prompt('Enter command: ', completer=completer)
print(f'You chose: {text}')

Dialog Examples

from prompt_toolkit.shortcuts import (
    input_dialog, message_dialog, yes_no_dialog,
    radiolist_dialog, checkboxlist_dialog
)

# Input dialog
name = input_dialog(title='Name Input', text='Enter your name:')
if name:
    print(f'Hello {name}!')

# Message dialog  
message_dialog(
    title='Information',
    text='Operation completed successfully!'
)

# Yes/No confirmation
if yes_no_dialog(title='Confirm', text='Delete all files?'):
    print('Files deleted')
else:
    print('Operation cancelled')

# Radio button selection
choice = radiolist_dialog(
    title='Select Option',
    text='Choose your preferred editor:',
    values=[
        ('vim', 'Vim'),
        ('emacs', 'Emacs'),
        ('vscode', 'VS Code'),
        ('atom', 'Atom')
    ]
)
if choice:
    print(f'You selected: {choice}')

# Checkbox selection
selections = checkboxlist_dialog(
    title='Features',
    text='Select features to enable:',
    values=[
        ('syntax', 'Syntax highlighting'),
        ('completion', 'Auto-completion'),
        ('validation', 'Input validation'),
        ('history', 'Command history')
    ]
)
if selections:
    print(f'Selected features: {selections}')

Advanced Styling

from prompt_toolkit import prompt
from prompt_toolkit.styles import Style
from prompt_toolkit.formatted_text import HTML

# Create custom style
style = Style.from_dict({
    'prompt': '#00aa00 bold',
    'input': '#ffffff',
    'bottom-toolbar': '#333333 bg:#ffff00'
})

# Styled prompt with toolbar
result = prompt(
    HTML('<prompt>Enter command:</prompt> '),
    style=style,
    bottom_toolbar=HTML('<b>F1:</b> Help | <b>F2:</b> Save | <b>Ctrl-C:</b> Exit')
)

Install with Tessl CLI

npx tessl i tessl/pypi-prompt-toolkit

docs

application.md

completion.md

index.md

key-bindings.md

layout.md

prompts.md

styling.md

tile.json