IPython Pygments Lexers

1.1.1 · active · verified Sat Mar 28

The ipython-pygments-lexers library provides specialized Pygments lexers for syntax highlighting IPython code and interactive sessions. These lexers were originally part of the main IPython project but were later extracted into a dedicated package to reduce IPython's core dependencies. The package is actively maintained, with its current version being 1.1.1, and releases occur infrequently as needed for bug fixes or minor enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the recommended `IPyLexer` from `ipython-pygments-lexers` with Pygments' `highlight` function and an `HtmlFormatter` to highlight a typical IPython console session. The `IPyLexer` intelligently adapts to the content, correctly rendering input prompts, outputs, and magic commands.

from pygments import highlight
from pygments.formatters import HtmlFormatter
from ipython_pygments_lexers import IPyLexer

code_to_highlight = (
    """In [1]: import numpy as np
   ...: a = np.array([1, 2, 3])
   ...: print(a * 2)
Out[1]: [2 4 6]

In [2]: %timeit [i**2 for i in range(1000)]
40.7 µs ± 1.15 µs per loop (mean ± Std. dev. of 7 runs, 10000 loops each)
"""
)

lexer = IPyLexer()
formatter = HtmlFormatter()

highlighted_code = highlight(code_to_highlight, lexer, formatter)
print(highlighted_code)

view raw JSON →