Pygments

2.19.2 · active · verified Sat Mar 28

Pygments is a generic syntax highlighting library written in Python, supporting over 500 languages and text formats with output in HTML, LaTeX, RTF, SVG, image formats, and ANSI terminal sequences. It can be used both as a library and as the `pygmentize` CLI tool. Current version is 2.19.2. Releases are made periodically with new lexers added each minor version; patch releases fix regressions quickly (2.19.1 and 2.19.2 followed 2.19.0 within weeks).

Warnings

Install

Imports

Quickstart

Highlight a Python snippet to HTML and print the required CSS alongside it.

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments.util import ClassNotFound

code = '''
def greet(name: str) -> str:
    return f"Hello, {name}!"

print(greet("World"))
'''

try:
    lexer = get_lexer_by_name('python', stripall=True)
except ClassNotFound as e:
    raise SystemExit(f"Lexer not found: {e}")

# cssclass must match the selector passed to get_style_defs
formatter = HtmlFormatter(linenos=True, cssclass='highlight', style='default')

# highlighted is an HTML snippet — NOT a full document
highlighted = highlight(code, lexer, formatter)

# get_style_defs() must be called to obtain the CSS; it is NOT embedded by default
css = formatter.get_style_defs('.highlight')

print(f'<style>\n{css}\n</style>')
print(highlighted)

view raw JSON →