Accessible Pygments Styles
A collection of accessible Pygments styles, currently at version 0.0.5. It provides themes that meet WCAG 2.1 color contrast requirements, aiming to make syntax highlighting more inclusive for users with low vision or color blindness. The library is actively maintained with regular minor releases adding new themes and improvements.
Warnings
- breaking Version 0.0.3 included critical fixes to the highlighting colors across all themes. Users upgrading from versions prior to 0.0.3 should expect visual changes in their highlighted code, as older versions may have had incorrect or less accessible color contrasts.
- gotcha When using `accessible-pygments` styles in Sphinx documentation, the style is specified as a string in `conf.py` (e.g., `pygments_style = "a11y-light"`). Do not attempt to import a Python class for the style directly into `conf.py`. The `accessible-pygments` package must be installed in the Sphinx environment.
- gotcha Pygments styles are referenced by their string names (e.g., `'a11y-light'`) in `HtmlFormatter(style='...')`. Do not attempt to directly import and pass a style class from `accessible_pygments` to the formatter (e.g., `HtmlFormatter(style=A11yLight)`). The package automatically registers these names upon import.
Install
-
pip install accessible-pygments
Imports
- accessible_pygments
import accessible_pygments
Quickstart
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import accessible_pygments # This registers the styles
code_to_highlight = """
def greet(name):
print(f"Hello, {name}!")
greet("World")
"""
# Choose an accessible style, e.g., 'a11y-light', 'github-dark-colorblind'
style_name = 'a11y-light'
# Create an HTML formatter with the chosen accessible style
formatter = HtmlFormatter(style=style_name, full=True, encoding='utf-8')
# Highlight the code
highlighted_code = highlight(
code_to_highlight,
PythonLexer(),
formatter
)
# The highlighted_code is now a bytes object (due to encoding='utf-8' in full=True mode)
# Decode to string if you want to print or save to a text file
print(highlighted_code.decode('utf-8'))
# To save to an HTML file (example)
# with open("highlighted_code.html", "wb") as f:
# f.write(highlighted_code)