CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pygments

A syntax highlighting package that supports over 500 programming languages and text formats with extensive output format options

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

formatter-management.mddocs/

Formatter Management

Functions for working with output formatters that convert highlighted tokens into various formats including HTML, LaTeX, RTF, SVG, terminal colors, and image formats.

Capabilities

Formatter Discovery by Name

Get a formatter instance by its alias.

def get_formatter_by_name(_alias: str, **options):
    """
    Get formatter instance by alias with options.
    
    Parameters:
    - _alias: Short identifier for formatter (e.g., 'html', 'latex', 'terminal')
    - **options: Formatter-specific options
    
    Returns:
    Formatter instance configured with the given options
    
    Raises:
    ClassNotFound: If no formatter with that alias is found
    """

Usage example:

from pygments.formatters import get_formatter_by_name

# HTML formatter with custom CSS class
html_formatter = get_formatter_by_name('html', cssclass='highlight')

# LaTeX formatter for documents
latex_formatter = get_formatter_by_name('latex')

# Terminal formatter with 256 colors
terminal_formatter = get_formatter_by_name('terminal256')

# HTML formatter with line numbers
html_with_lines = get_formatter_by_name('html', linenos=True)

Formatter Discovery by Filename

Get a formatter based on output filename patterns.

def get_formatter_for_filename(fn: str, **options):
    """
    Get formatter for output filename with options.
    
    Parameters:
    - fn: Output file name to determine formatter
    - **options: Formatter-specific options
    
    Returns:
    Formatter instance appropriate for the file type
    
    Raises:
    ClassNotFound: If no formatter matches the filename
    """

Usage example:

from pygments.formatters import get_formatter_for_filename

# Automatically choose formatter based on extension
html_formatter = get_formatter_for_filename('output.html')
latex_formatter = get_formatter_for_filename('document.tex')
rtf_formatter = get_formatter_for_filename('document.rtf')

Formatter Enumeration

List all available formatters.

def get_all_formatters() -> Iterator[type]:
    """
    Return generator of all available formatter classes.
    
    Yields:
    Formatter classes (not instances)
    """

Usage example:

from pygments.formatters import get_all_formatters

# List all available formatters
for formatter_class in get_all_formatters():
    print(f"Name: {formatter_class.name}")
    print(f"Aliases: {', '.join(formatter_class.aliases)}")
    if formatter_class.filenames:
        print(f"Files: {', '.join(formatter_class.filenames)}")
    print()

# Find HTML-related formatters
html_formatters = [
    cls for cls in get_all_formatters()
    if 'html' in cls.name.lower() or 'html' in cls.aliases
]

Class-Only Discovery

Find formatter classes without instantiating them.

def find_formatter_class(_alias: str):
    """
    Find formatter class by alias without instantiation.
    
    Parameters:
    - _alias: Formatter alias
    
    Returns:
    Formatter class or None if not found
    """

Custom Formatter Loading

Load custom formatters from files.

def load_formatter_from_file(filename: str, formattername: str = "CustomFormatter", **options):
    """
    Load custom formatter from file.
    
    Parameters:
    - filename: Path to Python file containing formatter class
    - formattername: Name of formatter class in file (default "CustomFormatter")
    - **options: Options passed to formatter constructor
    
    Returns:
    Custom formatter instance
    
    Raises:
    ClassNotFound: If file cannot be loaded or class not found
    """

Common Formatter Types

HTML Formatter

from pygments.formatters import HtmlFormatter

# Basic HTML
formatter = HtmlFormatter()

# HTML with line numbers and CSS class
formatter = HtmlFormatter(linenos=True, cssclass='codehilite')

# Inline styles (no CSS classes)
formatter = HtmlFormatter(noclasses=True)

# Full HTML document
formatter = HtmlFormatter(full=True, title='Code Sample')

Terminal Formatters

from pygments.formatters import TerminalFormatter, Terminal256Formatter, TerminalTrueColorFormatter

# Basic terminal colors (8/16 colors)
terminal_fmt = TerminalFormatter()

# 256-color terminal
terminal256_fmt = Terminal256Formatter()

# True color terminal (24-bit)
truecolor_fmt = TerminalTrueColorFormatter()

LaTeX Formatter

from pygments.formatters import LatexFormatter

# Basic LaTeX
latex_fmt = LatexFormatter()

# LaTeX with line numbers
latex_fmt = LatexFormatter(linenos=True)

# Embedded LaTeX (for inclusion in documents)
latex_fmt = LatexFormatter(verboptions="frame=single")

Image Formatters

from pygments.formatters import ImageFormatter

# PNG image (requires Pillow)
img_fmt = ImageFormatter(format='png')

# GIF with custom font
img_fmt = ImageFormatter(format='gif', font_name='Courier New')

Common Formatter Options

Most formatters support these options:

  • style (str): Color scheme name (default 'default')
  • full (bool): Generate complete document (default False)
  • title (str): Document title when full=True
  • encoding (str): Output encoding
  • outencoding (str): Override encoding option

HTML-Specific Options

  • linenos (bool): Add line numbers
  • cssclass (str): CSS class name (default 'highlight')
  • noclasses (bool): Use inline styles instead of CSS classes
  • prestyles (str): Inline styles for <pre> tag
  • wrapcode (bool): Wrap code in <code> tags

LaTeX-Specific Options

  • linenos (bool): Add line numbers
  • verboptions (str): Options for fancyvrb package
  • commandprefix (str): Command prefix for LaTeX commands

Terminal-Specific Options

  • bg (str): Background color ('light' or 'dark')
  • colorscheme (dict): Custom color mapping

Error Handling

  • ClassNotFound: No formatter found for the given criteria
  • OptionError: Invalid formatter options provided
  • ImportError: Missing dependencies (e.g., Pillow for image formats)

Output Examples

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter, LatexFormatter, Terminal256Formatter

code = "print('Hello, World!')"
lexer = PythonLexer()

# HTML output
html = highlight(code, lexer, HtmlFormatter())
# '<div class="highlight"><pre><span></span><span class="nb">print</span>...'

# LaTeX output  
latex = highlight(code, lexer, LatexFormatter())
# '\\begin{Verbatim}[commandchars=\\\\\\{\\}]...'

# Terminal output with colors
terminal = highlight(code, lexer, Terminal256Formatter())
# ANSI color codes for terminal display

Install with Tessl CLI

npx tessl i tessl/pypi-pygments

docs

command-line.md

custom-components.md

filter-system.md

formatter-management.md

high-level-api.md

index.md

lexer-management.md

style-management.md

tile.json