Skip to main content

Pygments HTML Template -- pygments.formatter plugin

You can write a template for pygments HtmlFormatter with this package.

Template Example

<Pygmentshtmltemplate>  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(1)-->
  <h1>${title}</h1> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(2)-->
  <ol class="${cssclass}">  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(3)-->
    <Line>  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(4)-->
      <li _="${highlighted}" id="line-${lineno}" class="hll"><Tokens/></li> <!-- - - - - - - - - - - -(5)-->
      <li id="line-${lineno}"><Tokens/></li>  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - -(6)-->
    </Line>
    <Tokens>  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(7)-->
      <code class="${token_class} init"><Token type="Name.Function" fullmatch="__init__"/></code> <!--(8)-->
      <code class="${token_class}" title="${token_type}"><Token/></code>  <!-- - - - - - - - - - - - -(9)-->
    </Tokens>
  </ol> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (10)-->
  <p>${filename}</p>  <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (11)-->
</Pygmentshtmltemplate>
  • (1): Must have a root node Pygmentshtmltemplate
    • The .parsers.parse function uses parser xml.sax.make_parser() in the Python standard library. So the template must be able to read by the the SAX parser. You should not parse untrusted data.
  • (2), (3), (10), (11): Wrapping html parts
    • <Line> (4) and <Tokens> (7) block represent line formats and each token format in each code line.
    • In (2), ${title} represents title option which is set to the formatter class. And that is replaced with its value.
  • (5), (6): Select a line wrapper
    • Each of <Line> (4) children represents a line format. Html elements can have options value for testing. If all values non-nil, then that line will be rendered.
      • highlight and lineno are not the formatter class options, but implicitly generated from linenostart and hl_lines option.
      • False, None, and empty Sequence are failed, but 0 (zero) is success.
      • Properties which name starts with _ are only used for testing, but they are not rendered.
      • The formatter tries the tests in textual order. The last line of the <Line> block should be always successful.
  • (8), (9): Select a token wrapper
    • Html properties are the same as line’s.
      • token_class and token_type are not the formatter options.
      • token_class is generated by formatter._get_css_classes(ttype: pygments.token._TokenType).
      • token_type is generated by '.'.join(ttype: pygments.token._TokenType)
    • <Token> (8) element can have type, match, and fullmatch properties for testing.
      • When Pygments gives the formatter a ‘tokentype’ and a ‘tokenvalue’, the formatter will test follows:
        • pygments.token.is_token_subtype(tokentype, pytments.token.string_to_tokentype(${type}))
        • re.fullmatch(${fullmatch}, tokenvalue) or re.match(${match}, tokenvalue)
    • When all tests are failed, a ‘tokenvalue’ is rendered as it is.

Install

% pip install pygmentshtmltemplate

You can confirm pygments.formatters plugins:

>>> import importlib
>>> importlib.metadata.entry_points().select(group='pygments.formatters')
[EntryPoint(name='pygmentshtmltemplate', value='pygmentshtmltemplate:FormatterWithTemplate', group='pygments.formatters')]

Usage

FormatterWithTemplate is the subclass of pygments.formatters.HtmlFormatter. FormatterWithTemplate.name is FormatterWithTemplate, and FormatterWithTemplate.aliases is ['fmtr_tmpl']

Formatter options

The options filename, cssclass, linenostart, hl_lines, classprefix, and title are in common spec with the HtmlFormatter. Other options of the HtmlFormatter are suppressed by the FormatterWithTemplate. Almost other options may get alternatives by wrapping parts of a template.

There is the original option template which is set to the path of a template file. If the template isn’t set, the default template (the following code) is used.

<Pygmentshtmltemplate>
  <ol class="${cssclass}">
    <Line>
      <li _="${highlighted}" class="hll"><Tokens/></li>
      <li><Tokens/></li>
    </Line>
    <Tokens>
      <code class="${token_class}"><Token/></code>
    </Tokens>
  </ol>
</Pygmentshtmltemplate>

Command line

The command line interface is provided by the Pygments. For example:

$ pygmentize -f fmtr_tmpl -O template=template.xml -o output.html want_to_highlight.py

$ pygmentize -f fmtr_tmpl -S default -a .highlight

In reStructuredText

You can use this formatter in the reStructuredText with docutils.

First, register the reST directive pygmentshtmltemplate.docutis.PygHtmlTmplRstDirective. The target source code can be provided at that directive content block. Or using :file: option, you can provide the source file.

from docutils.core import publish_string
from docutils.writers import html4css1
from docutils.parsers.rst import directives

from pygmentshtmltemplate.docutils import PygHtmlTmplRstDirective

directives.register_directive('fmtr-tmpl', PygHtmlTmplRstDirective)

ReST = f'''\
PygHtmlTmplRstDirective test
============================

pygmentize a file

.. fmtr-tmpl:: python :file: {__file__}

pygmentize a content block

.. fmtr-tmpl:: python
   :hl_lines: 1

   """highlight this line"""
   def hello(foo):
       print(f'hello, {{foo}}!')
'''

if __name__ == '__main__':
    formatted = publish_string(ReST, writer=html4css1.Writer())
    with open(output, 'wb') as out:
        out.write(formatted)

Future considered

  • Template for the full option
  • Now, the formatter.get_style_defs() method corresponds to the only default template.

Metadata

Release files for pygmentshtmltemplate 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pygmentshtmltemplate 0.1.0
File Size Uploaded Provenance Actions
pygmentshtmltemplate-0.1.0.tar.gz 13.4 kB Without provenance Details for pygmentshtmltemplate-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pygmentshtmltemplate 0.1.0
File Interpreter ABI Platform Actions
pygmentshtmltemplate-0.1.0-py3-none-any.whl Python 3 none any Details for pygmentshtmltemplate-0.1.0-py3-none-any.whl

Total release size: 26.4 kB

Release files / pygmentshtmltemplate-0.1.0.tar.gz

Download URL pygmentshtmltemplate-0.1.0.tar.gz
Size 13.4 kB
Tags Source
SHA-256 checksum
How to use checksums
cfce8d2d279432924ee8dc60536828f469d45afa5475af5d5280f53b058ef132
BLAKE2b-256 checksum
How to use checksums
7480f31dd85e00c01726a0e0aef8c603287870d33ef03a6082e42e9582369db1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.6

Release files / pygmentshtmltemplate-0.1.0-py3-none-any.whl

Download URL pygmentshtmltemplate-0.1.0-py3-none-any.whl
Size 13.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5eb214b883c6b1f3582a7c9044f117d23502b9919d589b4a27f1733c981551c6
BLAKE2b-256 checksum
How to use checksums
d4c292c466ebe6a72d56fb6445aef04056fff772b2b6adec129171e6542d9361
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.6

Security for pygmentshtmltemplate 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page