A syntax highlighting package that supports over 500 programming languages and text formats with extensive output format options
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Functions for working with output formatters that convert highlighted tokens into various formats including HTML, LaTeX, RTF, SVG, terminal colors, and image formats.
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)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')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
]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
"""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
"""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')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()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")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')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=Trueencoding (str): Output encodingoutencoding (str): Override encoding optionlinenos (bool): Add line numberscssclass (str): CSS class name (default 'highlight')noclasses (bool): Use inline styles instead of CSS classesprestyles (str): Inline styles for <pre> tagwrapcode (bool): Wrap code in <code> tagslinenos (bool): Add line numbersverboptions (str): Options for fancyvrb packagecommandprefix (str): Command prefix for LaTeX commandsbg (str): Background color ('light' or 'dark')colorscheme (dict): Custom color mappingfrom 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 displayInstall with Tessl CLI
npx tessl i tessl/pypi-pygments