Library for building powerful interactive command lines in Python
—
Rich text formatting with HTML-like syntax, ANSI sequences, and CSS-like styling with Pygments integration. The styling system provides comprehensive control over text appearance, colors, and formatting in terminal applications.
Core function for printing formatted text to the terminal with support for styles, colors, and formatting.
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
):
"""
Print formatted text with styling support.
Parameters:
- *values: AnyFormattedText values to print
- sep: str, separator between values
- end: str, string to append at end
- file: file-like object to write to
- flush: bool, whether to flush output
- style: Style instance for formatting
- output: Output instance for terminal control
- color_depth: ColorDepth for color support level
- style_transformation: StyleTransformation to apply
- include_default_pygments_style: bool, include Pygments defaults
"""Classes for creating formatted text with different markup styles.
class HTML:
def __init__(self, value):
"""
HTML-like formatted text with tag-based markup.
Parameters:
- value: str, HTML-like markup string
Supported tags:
- <b>bold</b>, <i>italic</i>, <u>underline</u>
- <style fg="color" bg="color">styled text</style>
- <reverse>reverse video</reverse>
- <hidden>hidden text</hidden>
- <blink>blinking text</blink>
"""
class ANSI:
def __init__(self, value):
"""
ANSI escape sequence formatted text.
Parameters:
- value: str, text with ANSI escape sequences
Common sequences:
- \\x1b[1m bold \\x1b[0m
- \\x1b[31m red \\x1b[0m
- \\x1b[42m green background \\x1b[0m
"""
class FormattedText:
def __init__(self, value):
"""
Generic formatted text container.
Parameters:
- value: List of (style, text) tuples or other formatted text
"""
class PygmentsTokens:
def __init__(self, tokens):
"""
Formatted text from Pygments syntax highlighting tokens.
Parameters:
- tokens: Iterator of (token_type, text) tuples from Pygments
"""Functions for working with and manipulating formatted text.
def to_formatted_text(value, style="", auto_convert=False):
"""
Convert various inputs to formatted text.
Parameters:
- value: str, FormattedText, HTML, ANSI, or list of tuples
- style: str, default style to apply
- auto_convert: bool, automatically convert strings
Returns:
FormattedText instance
"""
def is_formatted_text(value):
"""
Check if value is formatted text.
Parameters:
- value: Object to check
Returns:
bool: True if value is formatted text
"""
def merge_formatted_text(values):
"""
Merge multiple formatted text objects.
Parameters:
- values: List of formatted text objects
Returns:
Merged FormattedText instance
"""
def fragment_list_len(fragments):
"""
Get character length of fragment list.
Parameters:
- fragments: List of (style, text) tuples
Returns:
int: Total character count
"""
def fragment_list_width(fragments):
"""
Get display width of fragment list.
Parameters:
- fragments: List of (style, text) tuples
Returns:
int: Display width accounting for wide characters
"""
def fragment_list_to_text(fragments):
"""
Convert fragment list to plain text.
Parameters:
- fragments: List of (style, text) tuples
Returns:
str: Plain text without styling
"""
def split_lines(formatted_text):
"""
Split formatted text into lines.
Parameters:
- formatted_text: AnyFormattedText to split
Returns:
List of formatted text lines
"""
def to_plain_text(formatted_text):
"""
Extract plain text from formatted text.
Parameters:
- formatted_text: AnyFormattedText to convert
Returns:
str: Plain text without formatting
"""
class Template:
def __init__(self, template):
"""
Template for parameterized formatted text.
Parameters:
- template: str, template string with {variables}
"""
def format(self, **kwargs):
"""
Format template with values.
Parameters:
- **kwargs: Values to substitute in template
Returns:
FormattedText instance
"""CSS-like styling system for defining text appearance and colors.
class Style:
@classmethod
def from_dict(cls, style_dict):
"""
Create style from dictionary mapping.
Parameters:
- style_dict: Dict mapping class names to style strings
Returns:
Style instance
Style string format:
- Colors: fg:red bg:blue, #ff0000, ansiblue
- Attributes: bold, italic, underline, reverse, blink, hidden
- Combined: "bold italic fg:red bg:#ffffff"
"""
class BaseStyle:
"""Abstract base class for styles."""
def get_attrs_for_style_str(self, style_str):
"""
Get attributes for style string.
Parameters:
- style_str: str, CSS-like style specification
Returns:
Attrs instance
"""
class DummyStyle(BaseStyle):
"""Dummy style implementation for testing."""
def __init__(self):
"""Create dummy style with no formatting."""
class DynamicStyle(BaseStyle):
def __init__(self, get_style):
"""
Dynamic style that changes based on function.
Parameters:
- get_style: Function returning Style instance
"""
def merge_styles(styles):
"""
Merge multiple style objects.
Parameters:
- styles: List of Style instances
Returns:
Combined Style instance
"""
def default_ui_style():
"""
Get default UI style for prompt-toolkit interfaces.
Returns:
Style instance with default UI styling
"""
def default_pygments_style():
"""
Get default Pygments style for syntax highlighting.
Returns:
Style instance with Pygments defaults
"""
class Priority(Enum):
"""Style priority levels for override behavior."""
LOWEST = 0
LOW = 25
MEDIUM = 50
HIGH = 75
HIGHEST = 100Classes for specifying detailed text formatting attributes.
class Attrs:
def __init__(
self,
color=None,
bgcolor=None,
bold=None,
underline=None,
strike=None,
italic=None,
blink=None,
reverse=None,
hidden=None
):
"""
Text attribute specification.
Parameters:
- color: str, foreground color
- bgcolor: str, background color
- bold: bool, bold text
- underline: bool, underlined text
- strike: bool, strikethrough text
- italic: bool, italic text
- blink: bool, blinking text
- reverse: bool, reverse video
- hidden: bool, hidden text
"""
DEFAULT_ATTRS = Attrs() # Default text attributes
ANSI_COLOR_NAMES = {
# Standard ANSI color name mappings
'ansiblack': '000000',
'ansired': '800000',
'ansigreen': '008000',
'ansiyellow': '808000',
'ansiblue': '000080',
'ansimagenta': '800080',
'ansicyan': '008080',
'ansigray': 'c0c0c0',
# Bright colors
'ansibrightblack': '808080',
'ansibrightred': 'ff0000',
'ansibrightgreen': '00ff00',
'ansibrightyellow': 'ffff00',
'ansibrightblue': '0000ff',
'ansibrightmagenta': 'ff00ff',
'ansibrightcyan': '00ffff',
'ansiwhite': 'ffffff'
}
NAMED_COLORS = {
# Extended named color definitions
'red': 'ff0000',
'green': '00ff00',
'blue': '0000ff',
'yellow': 'ffff00',
'magenta': 'ff00ff',
'cyan': '00ffff',
'white': 'ffffff',
'black': '000000',
'gray': '808080',
'orange': 'ffa500',
'purple': '800080',
'brown': 'a52a2a',
'pink': 'ffc0cb'
}
def parse_color(color_str):
"""
Parse color specification string.
Parameters:
- color_str: str, color specification
Returns:
Parsed color value
Supported formats:
- Named colors: red, blue, ansiblue
- Hex colors: #ff0000, #f00
- RGB colors: rgb(255,0,0)
"""System for applying dynamic transformations to existing styles.
class StyleTransformation:
"""Abstract base class for style transformations."""
def transform_attrs(self, attrs, style_str):
"""
Transform text attributes.
Parameters:
- attrs: Attrs instance to transform
- style_str: str, original style string
Returns:
Transformed Attrs instance
"""
class SwapLightAndDarkStyleTransformation(StyleTransformation):
"""Swap light and dark colors in styles."""
def __init__(self):
"""Create light/dark swap transformation."""
class ReverseStyleTransformation(StyleTransformation):
"""Reverse foreground and background colors."""
def __init__(self):
"""Create color reversal transformation."""
class SetDefaultColorStyleTransformation(StyleTransformation):
def __init__(self, fg=None, bg=None):
"""
Set default foreground/background colors.
Parameters:
- fg: str, default foreground color
- bg: str, default background color
"""
class AdjustBrightnessStyleTransformation(StyleTransformation):
def __init__(self, min_brightness=0.0, max_brightness=1.0):
"""
Adjust color brightness levels.
Parameters:
- min_brightness: float, minimum brightness (0.0-1.0)
- max_brightness: float, maximum brightness (0.0-1.0)
"""
class DummyStyleTransformation(StyleTransformation):
"""Dummy transformation that makes no changes."""
def __init__(self):
"""Create no-op transformation."""
class ConditionalStyleTransformation(StyleTransformation):
def __init__(self, transformation, filter):
"""
Apply transformation conditionally.
Parameters:
- transformation: StyleTransformation to apply
- filter: Filter determining when to apply
"""
class DynamicStyleTransformation(StyleTransformation):
def __init__(self, get_transformation):
"""
Dynamic transformation based on function.
Parameters:
- get_transformation: Function returning StyleTransformation
"""
def merge_style_transformations(transformations):
"""
Merge multiple style transformations.
Parameters:
- transformations: List of StyleTransformation instances
Returns:
Combined StyleTransformation
"""Functions for integrating with Pygments syntax highlighting library.
def style_from_pygments_cls(pygments_style_cls):
"""
Create prompt-toolkit style from Pygments style class.
Parameters:
- pygments_style_cls: Pygments style class
Returns:
Style instance
"""
def style_from_pygments_dict(pygments_style_dict):
"""
Create prompt-toolkit style from Pygments style dictionary.
Parameters:
- pygments_style_dict: Dict of Pygments style definitions
Returns:
Style instance
"""
def pygments_token_to_classname(token):
"""
Convert Pygments token to CSS class name.
Parameters:
- token: Pygments token type
Returns:
str: CSS class name
"""from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import HTML, ANSI
# HTML-like formatting
print_formatted_text(HTML('<b>Bold text</b> and <i>italic text</i>'))
print_formatted_text(HTML('<style fg="red">Red text</style>'))
print_formatted_text(HTML('<style bg="blue" fg="white">Blue background</style>'))
# ANSI escape sequences
print_formatted_text(ANSI('\x1b[1mBold\x1b[0m \x1b[31mRed\x1b[0m'))
print_formatted_text(ANSI('\x1b[42mGreen background\x1b[0m'))
# Fragment list format
from prompt_toolkit.formatted_text import FormattedText
fragments = [
('class:title', 'Title: '),
('class:content', 'This is the content'),
('', '\n')
]
print_formatted_text(FormattedText(fragments))from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.styles import Style
# Define custom style
style = Style.from_dict({
'title': 'bold #ff0066',
'subtitle': 'italic #44ff44',
'content': '#ffffff',
'highlight': 'reverse',
'error': 'bold bg:red fg:white',
'warning': 'bold fg:yellow',
'success': 'bold fg:green'
})
# Use custom style
print_formatted_text(
HTML('<title>Application Title</title>\n'
'<subtitle>Version 1.0</subtitle>\n'
'<content>Normal content text</content>\n'
'<highlight>Highlighted text</highlight>\n'
'<error>Error message</error>\n'
'<warning>Warning message</warning>\n'
'<success>Success message</success>'),
style=style
)from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import PygmentsTokens
from prompt_toolkit.styles import style_from_pygments_cls
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.styles import get_style_by_name
# Python code to highlight
code = '''
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
result = fibonacci(10)
print(f"Fibonacci(10) = {result}")
'''
# Create Pygments tokens
lexer = PythonLexer()
tokens = list(lexer.get_tokens(code))
# Create style from Pygments
pygments_style = get_style_by_name('monokai')
style = style_from_pygments_cls(pygments_style)
# Print with syntax highlighting
print_formatted_text(PygmentsTokens(tokens), style=style)from prompt_toolkit.formatted_text import Template
from prompt_toolkit import print_formatted_text
from prompt_toolkit.styles import Style
# Create template
template = Template('''
<title>Welcome {username}!</title>
<info>Status: {status}</info>
<details>
- Login time: {login_time}
- Messages: {message_count}
- Last activity: {last_activity}
</details>
''')
# Define style for template
style = Style.from_dict({
'title': 'bold fg:blue',
'info': 'fg:green',
'details': 'fg:gray'
})
# Format and print template
formatted = template.format(
username='John Doe',
status='Online',
login_time='2023-12-01 09:30:00',
message_count='5',
last_activity='2 minutes ago'
)
print_formatted_text(formatted, style=style)from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.styles import DynamicStyle, Style
# Create dynamic style that changes based on conditions
def get_current_style():
# Could be based on user preferences, time of day, etc.
if some_condition:
return Style.from_dict({
'title': 'bold fg:blue',
'content': 'fg:white'
})
else:
return Style.from_dict({
'title': 'bold fg:red',
'content': 'fg:yellow'
})
dynamic_style = DynamicStyle(get_current_style)
# Use dynamic style
print_formatted_text(
HTML('<title>Dynamic Title</title>\n<content>Dynamic content</content>'),
style=dynamic_style
)from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.styles import Style
from prompt_toolkit.styles import (
SwapLightAndDarkStyleTransformation,
AdjustBrightnessStyleTransformation
)
# Base style
style = Style.from_dict({
'light': 'fg:white bg:black',
'dark': 'fg:black bg:white',
'colored': 'fg:red bg:blue'
})
text = HTML('<light>Light text</light> <dark>Dark text</dark> <colored>Colored</colored>')
# Original style
print_formatted_text('Original:', text, style=style)
# Swap light and dark
print_formatted_text(
'Swapped:',
text,
style=style,
style_transformation=SwapLightAndDarkStyleTransformation()
)
# Adjust brightness
print_formatted_text(
'Dimmed:',
text,
style=style,
style_transformation=AdjustBrightnessStyleTransformation(
min_brightness=0.3,
max_brightness=0.7
)
)Install with Tessl CLI
npx tessl i tessl/pypi-prompt-toolkit