or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

application.mdcompletion.mdindex.mdkey-bindings.mdlayout.mdprompts.mdstyling.md
tile.json

tessl/pypi-prompt-toolkit

Library for building powerful interactive command lines in Python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/prompt-toolkit@3.0.x

To install, run

npx @tessl/cli install tessl/pypi-prompt-toolkit@3.0.0

index.mddocs/

Prompt-Toolkit

A comprehensive Python library for building powerful interactive command-line applications. Prompt-toolkit provides advanced features including syntax highlighting, multi-line input editing, code completion, both Emacs and Vi key bindings, reverse and forward incremental search, Unicode support, text selection for copy/paste, bracketed paste support, mouse support, auto-suggestions, multiple input buffers, and cross-platform compatibility. It serves as a modern replacement for GNU readline while offering significantly more functionality.

Package Information

  • Package Name: prompt_toolkit
  • Language: Python
  • Installation: pip install prompt_toolkit

Core Imports

import prompt_toolkit

Most common imports for basic usage:

from prompt_toolkit import prompt, PromptSession
from prompt_toolkit import print_formatted_text
from prompt_toolkit.application import Application

For advanced formatting:

from prompt_toolkit.formatted_text import HTML, ANSI
from prompt_toolkit.styles import Style

Basic Usage

Simple Prompting

from prompt_toolkit import prompt

# Basic input prompt
answer = prompt('Give me some input: ')
print('You said:', answer)

# Prompt with default value
answer = prompt('Enter name: ', default='John')

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

Formatted Text Output

from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import HTML, ANSI
from prompt_toolkit.styles import Style

# Print with HTML-like formatting
print_formatted_text(HTML('<b>Bold</b> and <i>italic</i> text'))

# Print with ANSI sequences
print_formatted_text(ANSI('\x1b[31mRed text\x1b[0m'))

# Print with custom styles
style = Style.from_dict({
    'title': '#ff0066 bold',
    'subtitle': '#44ff44 italic'
})
print_formatted_text(HTML('<title>Hello</title> <subtitle>World</subtitle>'), 
                     style=style)

Advanced Prompt Session

from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.completion import WordCompleter

# Create reusable prompt session
session = PromptSession(
    history=FileHistory('.myhistory'),
    auto_suggest=AutoSuggestFromHistory(),
    completer=WordCompleter(['hello', 'world', 'python'])
)

while True:
    try:
        text = session.prompt('> ')
        print('You entered:', text)
    except (EOFError, KeyboardInterrupt):
        break

Architecture

Prompt-toolkit follows a layered, component-based architecture:

  • Application: Top-level application class managing the event loop, layout, input/output, and key bindings
  • Layout: Hierarchical container system (HSplit, VSplit, Window) for organizing UI components
  • Controls: UI elements that render content (BufferControl, FormattedTextControl)
  • Input/Output: Platform-specific input sources and output targets with color support
  • Key Bindings: Configurable key mapping system supporting Vi and Emacs modes
  • Filters: Conditional logic system for context-aware behavior
  • Styles: CSS-like styling system with Pygments integration

This design provides maximum flexibility while maintaining clean separation of concerns, enabling everything from simple prompts to complex interactive applications.

Capabilities

Core Application Building

Framework for building full-featured interactive terminal applications with event loops, layouts, and user interfaces.

class Application:
    def __init__(
        self,
        layout=None,
        style=None,
        key_bindings=None,
        clipboard=None,
        full_screen=False,
        mouse_support=False,
        **kwargs
    ): ...
    
    def run(self, pre_run=None, set_exception_handler=True): ...
    def run_async(self, pre_run=None, set_exception_handler=True): ...
    def exit(self, result=None, exception=None, style=""): ...

def get_app(): ...
def get_app_or_none(): ...

Application Building

Text Input and Prompting

Simple prompt functions and advanced prompt sessions with history, completion, and validation.

def prompt(
    message="",
    default="",
    password=False,
    multiline=False,
    complete_style=CompleteStyle.COLUMN,
    history=None,
    auto_suggest=None,
    completer=None,
    validator=None,
    **kwargs
): ...

class PromptSession:
    def __init__(
        self,
        message="",
        multiline=False,
        complete_style=CompleteStyle.COLUMN,
        history=None,
        auto_suggest=None,
        completer=None,
        validator=None,
        **kwargs
    ): ...
    
    def prompt(self, message=None, **kwargs): ...

Text Input and Prompting

Layout and UI Components

Comprehensive layout system with containers, windows, controls, and widgets for building complex interfaces.

class Layout:
    def __init__(self, container, focused_element=None): ...

class HSplit:
    def __init__(self, children, **kwargs): ...

class VSplit:
    def __init__(self, children, **kwargs): ...
    
class Window:
    def __init__(self, content=None, **kwargs): ...

class BufferControl:
    def __init__(self, buffer=None, **kwargs): ...

Layout and UI Components

Styling and Formatting

Rich text formatting with HTML-like syntax, ANSI sequences, and CSS-like styling with Pygments integration.

def print_formatted_text(
    *values,
    sep=" ",
    end="\n",
    file=None,
    flush=False,
    style=None,
    output=None,
    color_depth=None,
    style_transformation=None,
    include_default_pygments_style=None
): ...

class HTML:
    def __init__(self, value): ...

class ANSI:
    def __init__(self, value): ...
    
class Style:
    @classmethod
    def from_dict(cls, style_dict): ...

Styling and Formatting

Key Bindings and Input

Configurable key binding system supporting Vi and Emacs editing modes with customizable key mappings.

class KeyBindings:
    def __init__(self): ...
    def add(self, *keys, **kwargs): ...

class KeyPress:
    def __init__(self, key, data=""): ...

def load_vi_bindings(): ...
def load_emacs_bindings(): ...

Key Bindings and Input

Completion and Validation

Auto-completion system with built-in completers for files, words, and custom data, plus validation framework.

class Completer:
    def get_completions(self, document, complete_event): ...

class Completion:
    def __init__(
        self,
        text,
        start_position=0,
        display=None,
        display_meta=None,
        style="",
        selected_style=""
    ): ...

class Validator:
    def validate(self, document): ...

class ValidationError(Exception):
    def __init__(self, cursor_position=0, message=""): ...

Completion and Validation

Types

Core Application Types

from typing import Optional, List, Dict, Any, Callable, Union
from prompt_toolkit.filters import FilterOrBool

# Application result type
AppResult = Any

# Layout dimension type  
AnyDimension = Union[None, int, Dimension]

# Formatted text types
AnyFormattedText = Union[str, List[Tuple[str, str]], HTML, ANSI, FormattedText]
StyleAndTextTuples = List[Tuple[str, str]]

# Filter type for conditional behavior
FilterOrBool = Union[bool, Filter]

Buffer and Document Types

class Document:
    def __init__(self, text="", cursor_position=None): ...
    @property
    def text(self) -> str: ...
    @property 
    def cursor_position(self) -> int: ...
    @property
    def current_line(self) -> str: ...

class Buffer:
    def __init__(
        self,
        document=None,
        multiline=True,
        read_only=False,
        history=None,
        completer=None,
        validator=None,
        **kwargs
    ): ...

Completion Types

class CompleteEvent:
    def __init__(self, text_inserted=False, completion_requested=False): ...

# Completion style enumeration
class CompleteStyle(Enum):
    COLUMN = "column"
    MULTI_COLUMN = "multi-column" 
    READLINE_LIKE = "readline-like"

Key and Input Types

class Keys:
    # Common keys
    ControlA = "c-a"
    ControlC = "c-c"
    ControlD = "c-d"
    Enter = "\r"
    Escape = "\x1b"
    Backspace = "\x7f"
    Delete = "\x1b[3~"
    # Function keys
    F1 = "\x1bOP"
    F2 = "\x1bOQ"
    # Arrow keys
    Up = "\x1b[A"
    Down = "\x1b[B"
    Left = "\x1b[D"
    Right = "\x1b[C"

class EditingMode(Enum):
    EMACS = "EMACS"
    VI = "VI"