Module

formatters.terminal

Terminal formatter for Rosettes.

Generates ANSI-colored output for terminal consoles. Thread-safe and optimized for streaming.

Design Philosophy:

The terminal formatter maps semantic syntax roles to ANSI color codes. It uses the same role-based system as the HTML formatter, ensuring visual consistency between terminal and web output.

ANSI Color Mapping:

  • Control/Declaration: Magenta/Cyan (stand out for structure)
  • Strings: Green (universally recognized)
  • Numbers: Yellow (distinct from strings)
  • Functions: Blue (clear identifier category)
  • Comments: Gray (de-emphasized)
  • Errors: Red (universal error color)

Performance:

  • Pre-computed token-to-ANSI mapping (~100 entries)
  • O(1) color lookup per token
  • Streaming output (yields chunks, no intermediate list)

Benchmarks: ~30µs per 100-line file (vs ~50µs for HTML)

Terminal Compatibility:

Uses standard ANSI SGR (Select Graphic Rendition) codes:

  • \033[XXmfor color (30-37 normal, 90-97 bright)
  • \033[0mfor reset

Compatible with:

  • Modern terminals (iTerm2, Windows Terminal, GNOME Terminal)
  • VS Code integrated terminal
  • Most CI/CD log viewers

Thread-Safety:

The formatter is a frozen dataclass with no mutable state. Color mappings are module-level constants (immutable dicts).

See Also:

  • rosettes.formatters.html: HTML output (same role system)
  • rosettes.themes._roles: Semantic role definitions
  • rosettes.themes._mapping: TokenType → SyntaxRole mapping

Classes

TerminalFormatter 5
ANSI color formatter for terminals. Thread-safe: frozen dataclass with no mutable state. Uses pre-…

ANSI color formatter for terminals.

Thread-safe: frozen dataclass with no mutable state. Uses pre-computed color mappings for O(1) lookup per token.

Methods

name 0 str
property
def name(self) -> str
Returns
str
format_fast 2 Iterator[str]
Fast ANSI formatting using pre-computed color maps.
def format_fast(self, tokens: Iterator[tuple[TokenType, str]], config: FormatConfig | None = None) -> Iterator[str]
Parameters
Name Type Description
tokens
config Default:None
Returns
Iterator[str]
format 2 Iterator[str]
Format tokens as ANSI-colored strings.
def format(self, tokens: Iterator[Token], config: FormatConfig | None = None) -> Iterator[str]
Parameters
Name Type Description
tokens
config Default:None
Returns
Iterator[str]
format_string 2 str
def format_string(self, tokens: Iterator[Token], config: FormatConfig | None = None) -> str
Parameters
Name Type Description
tokens
config Default:None
Returns
str
format_string_fast 2 str
def format_string_fast(self, tokens: Iterator[tuple[TokenType, str]], config: FormatConfig | None = None) -> str
Parameters
Name Type Description
tokens
config Default:None
Returns
str