Skip to content

Add langclass option to HtmlFormatter - #3305

Open
BiswasNehaa wants to merge 1 commit into
pygments:masterfrom
BiswasNehaa:add-language-class-option
Open

BiswasNehaa wants to merge 1 commit into
pygments:masterfrom
BiswasNehaa:add-language-class-option

Conversation

@BiswasNehaa

Copy link
Copy Markdown

Fixes #1844

HtmlFormatter had no way to indicate the source language in its output. The core reason: Formatter is never told which Lexer produced its token stream (they're decoupled by design — you can already do highlight(code, PythonLexer(), HtmlFormatter()) and the formatter never sees PythonLexer), so this can't be auto-detected.

This adds a langclass option: when set (e.g. HtmlFormatter(langclass='python')), the wrapping <div> gets an additional CSS class of language-python, following the language-xxx convention used by highlight.js, Prism, and CommonMark. The caller supplies the language explicitly, same pattern as the existing cssclass option — e.g. HtmlFormatter(langclass=lexer.aliases[0]).

Changes

  • pygments/formatters/html.py: new langclass option, documented with a usage example
  • tests/test_html_formatter.py: new-value emission, interaction with an empty cssclass, default-empty behavior, and HTML-escaping/None handling alongside the other string options
  • CHANGES: entry under the unreleased 2.22.0 section

Test plan

  • pytest tests/test_html_formatter.py — 26 passed
  • pytest tests/ (excluding the unrelated contrast module, which fails to collect on master too due to a missing optional dependency) — 5340 passed, 8 skipped
  • ruff check — clean
  • Manually verified output: highlight(code, PythonLexer(), HtmlFormatter(langclass='python'))<div class="highlight language-python">...

🤖 Generated with Claude Code

Fixes pygments#1844. HtmlFormatter previously had no way to signal the
source language in its HTML output. Since Formatter is never told
which Lexer produced its token stream, this requires the caller to
supply the language explicitly.

Adds a langclass option: when set (e.g. langclass='python'), the
wrapping <div> gets an additional CSS class of language-python,
matching the language-xxx convention used by highlight.js, Prism,
and CommonMark.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Actually return and display language in first line

1 participant