CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-prompt-toolkit

Library for building powerful interactive command lines in Python

Pending
Overview
Eval results
Files

layout.mddocs/

Layout and UI Components

Comprehensive layout system with containers, windows, controls, and widgets for building complex terminal interfaces. The layout system uses a hierarchical approach with containers that organize child components and controls that render actual content.

Capabilities

Layout Core

The Layout class serves as the root container for all UI components and manages focus and rendering.

class Layout:
    def __init__(self, container, focused_element=None):
        """
        Create a layout with a root container.
        
        Parameters:
        - container: Root Container instance
        - focused_element: Initial focused UI element
        """
        
    def focus(self, focusable):
        """
        Set focus to a specific UI element.
        
        Parameters:
        - focusable: UI element to focus
        """
        
    def focus_next(self):
        """Move focus to next focusable element."""
        
    def focus_previous(self):
        """Move focus to previous focusable element."""

def walk(container, skip_hidden=False):
    """
    Walk through all UI elements in layout tree.
    
    Parameters:
    - container: Container to walk through
    - skip_hidden: bool, whether to skip hidden elements
    
    Yields:
    UI elements in the container tree
    """

class InvalidLayoutError(Exception):
    """Exception raised for invalid layout configurations."""

Dimensions

System for specifying layout dimensions with support for fixed, percentage, and weighted sizing.

class Dimension:
    def __init__(self, min=None, max=None, weight=None, preferred=None):
        """
        Specify layout dimension constraints.
        
        Parameters:
        - min: int, minimum size
        - max: int, maximum size  
        - weight: int, relative weight for distribution
        - preferred: int, preferred size
        """

def D(min=None, max=None, weight=None, preferred=None):
    """
    Shortcut function to create Dimension.
    
    Parameters:
    - min: int, minimum size
    - max: int, maximum size
    - weight: int, relative weight
    - preferred: int, preferred size
    
    Returns:
    Dimension instance
    """

def sum_layout_dimensions(dimensions):
    """
    Sum multiple dimensions.
    
    Parameters:
    - dimensions: List of Dimension instances
    
    Returns:
    Combined Dimension
    """

def max_layout_dimensions(dimensions):
    """
    Get maximum of multiple dimensions.
    
    Parameters: 
    - dimensions: List of Dimension instances
    
    Returns:
    Maximum Dimension
    """

def to_dimension(value):
    """
    Convert value to Dimension.
    
    Parameters:
    - value: int, Dimension, or None
    
    Returns:
    Dimension instance
    """

def is_dimension(obj):
    """
    Check if object is a Dimension.
    
    Parameters:
    - obj: Object to check
    
    Returns:
    bool: True if object is Dimension
    """

# Type alias for dimension values
AnyDimension = Union[None, int, Dimension]

Container Classes

Container classes organize child UI elements with different layout strategies.

class Container:
    """Abstract base class for all containers."""
    
    def __init__(self):
        """Create base container."""

class HSplit(Container):
    def __init__(
        self,
        children,
        window_too_small=None,
        align=HorizontalAlign.JUSTIFY,
        padding=0,
        padding_char=None,
        padding_style="",
        width=None,
        height=None,
        z_index=None,
        modal=False,
        key_bindings=None,
        style=""
    ):
        """
        Horizontal split container that stacks children vertically.
        
        Parameters:
        - children: List of child containers/windows
        - window_too_small: Container to show when space is insufficient
        - align: HorizontalAlign, horizontal alignment of children
        - padding: int, padding around container
        - padding_char: str, character for padding
        - padding_style: str, style for padding
        - width: AnyDimension, container width
        - height: AnyDimension, container height
        - z_index: int, z-order for overlapping
        - modal: bool, whether container is modal
        - key_bindings: KeyBindings for container
        - style: str, CSS-like style
        """

class VSplit(Container):
    def __init__(
        self,
        children,
        window_too_small=None,
        align=VerticalAlign.JUSTIFY,
        padding=0,
        padding_char=None,
        padding_style="",
        width=None,
        height=None,
        z_index=None,
        modal=False,
        key_bindings=None,
        style=""
    ):
        """
        Vertical split container that arranges children horizontally.
        
        Parameters:
        - children: List of child containers/windows
        - window_too_small: Container to show when space is insufficient  
        - align: VerticalAlign, vertical alignment of children
        - padding: int, padding around container
        - padding_char: str, character for padding
        - padding_style: str, style for padding
        - width: AnyDimension, container width
        - height: AnyDimension, container height
        - z_index: int, z-order for overlapping
        - modal: bool, whether container is modal
        - key_bindings: KeyBindings for container
        - style: str, CSS-like style
        """

class FloatContainer(Container):
    def __init__(
        self,
        content,
        floats=None,
        modal=False,
        key_bindings=None,
        style=""
    ):
        """
        Container with floating overlay elements.
        
        Parameters:
        - content: Background container content
        - floats: List of Float instances for overlays
        - modal: bool, whether container is modal
        - key_bindings: KeyBindings for container
        - style: str, CSS-like style
        """

class Float:
    def __init__(
        self,
        content=None,
        top=None,
        right=None,
        bottom=None,
        left=None,
        width=None,
        height=None,
        xcursor=False,
        ycursor=False,
        transparent=False,
        allow_cover_cursor=False
    ):
        """
        Floating element specification.
        
        Parameters:
        - content: Container content for float
        - top: int, distance from top edge
        - right: int, distance from right edge
        - bottom: int, distance from bottom edge
        - left: int, distance from left edge
        - width: AnyDimension, float width
        - height: AnyDimension, float height
        - xcursor: bool, position relative to cursor X
        - ycursor: bool, position relative to cursor Y
        - transparent: bool, whether background is transparent
        - allow_cover_cursor: bool, allow covering cursor
        """

class Window(Container):
    def __init__(
        self,
        content=None,
        width=None,
        height=None,
        z_index=None,
        dont_extend_width=False,
        dont_extend_height=False,
        ignore_content_width=False,
        ignore_content_height=False,
        left_margins=None,
        right_margins=None,
        scroll_offsets=None,
        allow_scroll_beyond_bottom=False,
        wrap_lines=False,
        get_vertical_scroll=None,
        get_horizontal_scroll=None,
        always_hide_cursor=False,
        cursorline=False,
        cursorcolumn=False,
        colorcolumns=None,
        align=WindowAlign.LEFT,
        style="",
        char=None
    ):
        """
        Window container for displaying UI controls.
        
        Parameters:
        - content: UIControl instance to display
        - width: AnyDimension, window width
        - height: AnyDimension, window height
        - z_index: int, z-order for overlapping
        - dont_extend_width: bool, don't extend to fill width
        - dont_extend_height: bool, don't extend to fill height
        - ignore_content_width: bool, ignore content width
        - ignore_content_height: bool, ignore content height
        - left_margins: List of Margin instances for left side
        - right_margins: List of Margin instances for right side
        - scroll_offsets: ScrollOffsets for scrolling behavior
        - allow_scroll_beyond_bottom: bool, allow scrolling past end
        - wrap_lines: bool, wrap long lines
        - get_vertical_scroll: Function returning vertical scroll position
        - get_horizontal_scroll: Function returning horizontal scroll position
        - always_hide_cursor: bool, never show cursor
        - cursorline: bool, highlight cursor line
        - cursorcolumn: bool, highlight cursor column
        - colorcolumns: List of ColorColumn instances
        - align: WindowAlign, content alignment
        - style: str, CSS-like style
        - char: str, background character
        """

class WindowRenderInfo:
    """Information about rendered window."""
    def __init__(self):
        """Create window render info."""

class ConditionalContainer(Container):
    def __init__(self, container, filter):
        """
        Container shown based on condition.
        
        Parameters:
        - container: Container to wrap
        - filter: Filter determining visibility
        """

class DynamicContainer(Container):
    def __init__(self, get_container):
        """
        Container with dynamic content.
        
        Parameters:
        - get_container: Function returning container
        """

class ScrollablePane(Container):
    def __init__(
        self,
        content,
        scroll_offsets=None,
        keep_cursor_visible=True,
        keep_focused_window_visible=True,
        max_available_height=None,
        width=None,
        height=None,
        show_scrollbar=True,
        display_arrows=True,
        up_arrow_symbol="^",
        down_arrow_symbol="v"
    ):
        """
        Scrollable container for content larger than display area.
        
        Parameters:
        - content: Container content to make scrollable
        - scroll_offsets: ScrollOffsets configuration
        - keep_cursor_visible: bool, ensure cursor stays visible
        - keep_focused_window_visible: bool, keep focused window visible
        - max_available_height: int, maximum height available
        - width: AnyDimension, pane width
        - height: AnyDimension, pane height
        - show_scrollbar: bool, display scrollbar
        - display_arrows: bool, show scroll arrows
        - up_arrow_symbol: str, up arrow character
        - down_arrow_symbol: str, down arrow character
        """

class ColorColumn:
    def __init__(self, position, style="class:color-column"):
        """
        Color column background marker.
        
        Parameters:
        - position: int, column position
        - style: str, CSS-like style for column
        """

def to_container(container):
    """
    Convert value to Container.
    
    Parameters:
    - container: Container, Window, or UIControl
    
    Returns:
    Container instance
    """

def to_window(container):
    """
    Convert value to Window.
    
    Parameters:
    - container: Container, Window, or UIControl
    
    Returns:
    Window instance
    """

def is_container(obj):
    """
    Check if object is a Container.
    
    Parameters:
    - obj: Object to check
    
    Returns:
    bool: True if object is Container
    """

# Type alias for container values
AnyContainer = Union[Container, UIControl]

Alignment Enums

Enumeration classes for specifying alignment options.

class HorizontalAlign(Enum):
    """Horizontal alignment options."""
    LEFT = "left"
    CENTER = "center"
    RIGHT = "right"
    JUSTIFY = "justify"

class VerticalAlign(Enum):
    """Vertical alignment options."""
    TOP = "top"
    CENTER = "center"
    BOTTOM = "bottom"
    JUSTIFY = "justify"

class WindowAlign(Enum):
    """Window content alignment options."""
    LEFT = "left"
    RIGHT = "right"
    CENTER = "center"

UI Controls

Controls are the components that actually render content within windows.

class UIControl:
    """Abstract base class for UI controls."""
    
    def create_content(self, width, height):
        """
        Create content for rendering.
        
        Parameters:
        - width: int, available width
        - height: int, available height
        
        Returns:
        UIContent instance
        """

class UIContent:
    def __init__(
        self,
        get_line=None,
        line_count=0,
        cursor_position=None,
        menu_position=None,
        show_cursor=True
    ):
        """
        UI content data for rendering.
        
        Parameters:
        - get_line: Function to get line content by index
        - line_count: int, total number of lines
        - cursor_position: Point, cursor position
        - menu_position: Point, menu position
        - show_cursor: bool, whether to show cursor
        """

class FormattedTextControl(UIControl):
    def __init__(
        self,
        text="",
        style="",
        focusable=False,
        key_bindings=None,
        show_cursor=True
    ):
        """
        Control for displaying formatted text.
        
        Parameters:
        - text: AnyFormattedText, text content to display
        - style: str, CSS-like style
        - focusable: bool, whether control can receive focus
        - key_bindings: KeyBindings for control
        - show_cursor: bool, whether to show cursor
        """

class BufferControl(UIControl):
    def __init__(
        self,
        buffer=None,
        lexer=None,
        input_processors=None,
        include_default_input_processors=True,
        search_buffer_control=None,
        menu_position=None,
        focusable=True,
        focus_on_click=False,
        key_bindings=None,
        get_cursor_position=None
    ):
        """
        Control for displaying and editing buffer content.
        
        Parameters:
        - buffer: Buffer instance to display/edit
        - lexer: Lexer for syntax highlighting
        - input_processors: List of InputProcessor instances
        - include_default_input_processors: bool, include default processors
        - search_buffer_control: SearchBufferControl for search highlighting
        - menu_position: Function returning menu position
        - focusable: bool, whether control can receive focus
        - focus_on_click: bool, focus on mouse click
        - key_bindings: KeyBindings for control
        - get_cursor_position: Function returning cursor position
        """

class SearchBufferControl(BufferControl):
    def __init__(
        self,
        buffer=None,
        input_processors=None,
        lexer=None,
        ignore_case=False
    ):
        """
        Control for search buffer with highlighting.
        
        Parameters:
        - buffer: Buffer instance for search text
        - input_processors: List of InputProcessor instances
        - lexer: Lexer for syntax highlighting
        - ignore_case: bool, case-insensitive search
        """

class DummyControl(UIControl):
    def __init__(self):
        """Dummy control for testing and placeholders."""

Scroll Configuration

Classes for configuring scrolling behavior.

class ScrollOffsets:
    def __init__(self, top=0, bottom=0, left=0, right=0):
        """
        Scroll offset configuration.
        
        Parameters:
        - top: int, lines to keep visible above cursor
        - bottom: int, lines to keep visible below cursor
        - left: int, columns to keep visible left of cursor
        - right: int, columns to keep visible right of cursor
        """

Usage Examples

Basic Layout Structure

from prompt_toolkit.application import Application
from prompt_toolkit.layout import Layout
from prompt_toolkit.layout.containers import HSplit, VSplit, Window
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.key_binding import KeyBindings

# Create layout with horizontal and vertical splits
layout = Layout(
    HSplit([
        # Header
        Window(
            FormattedTextControl('Header Area'),
            height=1,
            style='class:header'
        ),
        # Main content area with sidebar
        VSplit([
            # Sidebar
            Window(
                FormattedTextControl('Sidebar'),
                width=20,
                style='class:sidebar'
            ),
            # Main content
            Window(FormattedTextControl('Main Content Area')),
        ]),
        # Footer
        Window(
            FormattedTextControl('Footer Area'),
            height=1,
            style='class:footer'
        )
    ])
)

# Key bindings
bindings = KeyBindings()

@bindings.add('c-c')
def exit_app(event):
    event.app.exit()

# Create and run application
app = Application(
    layout=layout,
    key_bindings=bindings,
    full_screen=True
)

app.run()

Dynamic Layout with Conditions

from prompt_toolkit.layout.containers import ConditionalContainer, HSplit, Window
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.filters import Condition

# Create condition for showing/hiding sidebar
show_sidebar = Condition(lambda: True)  # Can be dynamic

layout = Layout(
    HSplit([
        VSplit([
            # Conditional sidebar
            ConditionalContainer(
                Window(
                    FormattedTextControl('Sidebar Content'),
                    width=20
                ),
                filter=show_sidebar
            ),
            # Main content
            Window(FormattedTextControl('Main Content'))
        ])
    ])
)

Floating Elements

from prompt_toolkit.layout.containers import FloatContainer, Float, HSplit, Window
from prompt_toolkit.layout.controls import FormattedTextControl

# Create layout with floating dialog
layout = Layout(
    FloatContainer(
        # Background content
        HSplit([
            Window(FormattedTextControl('Background Content')),
        ]),
        # Floating elements
        floats=[
            Float(
                Window(
                    FormattedTextControl('Floating Dialog'),
                    width=40,
                    height=10
                ),
                left=10,
                top=5
            )
        ]
    )
)

Scrollable Content

from prompt_toolkit.layout.containers import ScrollablePane, HSplit, Window
from prompt_toolkit.layout.controls import FormattedTextControl

# Create large content that needs scrolling
large_content = '\n'.join([f'Line {i}' for i in range(100)])

layout = Layout(
    ScrollablePane(
        HSplit([
            Window(FormattedTextControl(large_content))
        ]),
        show_scrollbar=True
    )
)

Buffer Control with Editing

from prompt_toolkit.buffer import Buffer
from prompt_toolkit.layout import Layout
from prompt_toolkit.layout.containers import HSplit, Window
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.lexers import PygmentsLexer
from pygments.lexers import PythonLexer

# Create buffer with Python content
buffer = Buffer(
    document=Document('def hello():\n    print("Hello, World!")'),
    multiline=True
)

# Create buffer control with syntax highlighting
buffer_control = BufferControl(
    buffer=buffer,
    lexer=PygmentsLexer(PythonLexer)
)

layout = Layout(
    HSplit([
        Window(buffer_control),
        Window(
            FormattedTextControl('Press Ctrl-C to exit'),
            height=1
        )
    ])
)

Margins and Decorations

from prompt_toolkit.layout.margins import NumberedMargin, ScrollbarMargin
from prompt_toolkit.layout.containers import HSplit, Window
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.buffer import Buffer

# Create buffer
buffer = Buffer(multiline=True)

# Window with line numbers and scrollbar
layout = Layout(
    HSplit([
        Window(
            BufferControl(buffer),
            left_margins=[NumberedMargin()],
            right_margins=[ScrollbarMargin()],
            wrap_lines=True
        )
    ])
)

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