An awesome theme for the Sphinx documentation generator with enhanced features, custom code highlighting, and modern responsive design
Advanced code block functionality that extends Sphinx's standard code highlighting with support for emphasizing added/removed lines, placeholder text highlighting, and custom Pygments formatters with comprehensive dark mode support.
Custom directive that extends Sphinx's built-in code-block directive with additional highlighting options.
class AwesomeCodeBlock(CodeBlock):
"""
Extension of the Sphinx code-block directive with additional highlighting options.
New options:
- :emphasize-added: highlight added lines
- :emphasize-removed: highlight removed lines
- :emphasize-text: highlight placeholder text
"""
new_options = {
"emphasize-added": directives.unchanged_required,
"emphasize-removed": directives.unchanged_required,
"emphasize-text": directives.unchanged_required,
}
def _get_line_numbers(self, option: Literal["emphasize-added", "emphasize-removed"]) -> list[int] | None:
"""Parse the line numbers for the emphasize-added and emphasize-removed options."""
def _extra_args(self, node: Node, hl_added: list[int] | None, hl_removed: list[int] | None) -> None:
"""Set extra attributes for line highlighting."""
def run(self) -> list[Node]:
"""Handle parsing extra options for highlighting."""Enhanced Pygments integration that handles placeholder text highlighting and provides dark mode stylesheet support.
class AwesomePygmentsBridge(PygmentsBridge):
"""Extends PygmentsBridge to handle highlighting placeholder text."""
html_formatter = AwesomeHtmlFormatter
def get_lexer(self, source: str, lang: str, opts: dict[str, Any] | None = None,
force: bool = False, location: Any = None) -> Lexer:
"""
Extends PygmentsBridge.get_lexer method.
Adds a filter to lexers if the hl_text option is present.
"""
def highlight_block(self, source: str, lang: str, opts: dict[str, Any] | None = None,
force: bool = False, location: Any = None, **kwargs: Any) -> str:
"""
Extends PygmentsBridge.highlight_block method.
Called when Sphinx transforms document tree to HTML and encounters code blocks.
"""
def get_stylesheet(self, arg: str | None = None) -> str:
"""
Override PygmentsBridge.get_stylesheet method.
Allows prepending all Pygments classes with a common prefix, such as .dark.
"""Specialized Pygments HTML formatter that handles highlighting of added, removed, and emphasized lines.
class AwesomeHtmlFormatter(HtmlFormatter):
"""Custom Pygments HTML formatter for highlighting added or removed lines."""
def _get_line_numbers(self, options: dict[str, Any], which: Literal["hl_added", "hl_removed"]) -> set[int]:
"""Get the lines to be added or removed."""
def _highlight_lines(self, tokensource: TokenStream) -> TokenStream:
"""
Highlight added, removed, and emphasized lines.
In contrast to Pygments, use <mark>, <ins>, and <del> elements.
"""
def __init__(self, **options: Any) -> None:
"""
Implement hl_added and hl_removed options.
Also sets linespans and wrapcode options to True.
Parameters:
- **options: Formatter options including hl_added, hl_removed lists
"""
def format_unencoded(self, tokensource: TokenStream, outfile: Any) -> None:
"""
Overwrite method to handle emphasized, added, and removed lines.
Uses <mark>, <ins>, and <del> elements for line highlighting.
"""Pygments filter for marking up placeholder text within code blocks.
def _replace_placeholders(ttype: TokenType, value: str, regex: Pattern[str]) -> TokenStream:
"""Replace every occurrence of regex with Generic.Emph token."""
class AwesomePlaceholders(Filter):
"""
A Pygments filter for marking up placeholder text.
Highlights specified text patterns with Generic.Emph token.
"""
def __init__(self, **options: str) -> None:
"""
Create an instance of the AwesomePlaceholders filter.
Parameters:
- **options: Filter options including hl_text list
"""
def filter(self, _lexer: Any, stream: TokenStream) -> TokenStream:
"""Filter on all tokens to replace placeholders with emphasized tokens."""HTML builder that overrides Pygments CSS handling methods for dark mode support.
class AwesomeHTMLBuilder(StandaloneHTMLBuilder):
"""HTML builder that overrides methods related to handling CSS for Pygments."""
def init_highlighter(self) -> None:
"""Initialize Pygments highlighters with dark mode support."""
def create_pygments_style_file(self) -> None:
"""Create CSS file for Pygments with combined light and dark mode styles.""".. code-block:: python
:emphasize-added: 2,4
:emphasize-removed: 6
:emphasize-text: placeholder_value
def process_data(data):
# This line will be highlighted as added
result = transform(data)
# This line will also be highlighted as added
enhanced_result = enhance(result)
# This line will be highlighted as removed
return placeholder_value# In conf.py
pygments_style = "default" # Light mode style
pygments_style_dark = "monokai" # Dark mode style
html_theme_options = {
"awesome_headerlinks": True,
}# The AwesomePlaceholders filter automatically highlights
# text specified in the :emphasize-text: option
lexer.add_filter(AwesomePlaceholders(hl_text=["PLACEHOLDER", "TODO"]))# Configure Pygments styles for light and dark modes
pygments_style = "default" # Style for light mode
pygments_style_dark = "monokai" # Style for dark mode (optional)Available options for the enhanced code-block directive:
:emphasize-added: 1,3,5-7 - Highlight lines as added (uses <ins> elements):emphasize-removed: 2,4 - Highlight lines as removed (uses <del> elements):emphasize-text: placeholder - Highlight specific text patterns (uses Generic.Emph token)The enhanced formatter produces structured HTML output:
<pre><code>
<span id="line-1">def example():</span>
<ins><span id="line-2"> # Added line</span></ins>
<del><span id="line-3"> # Removed line</span></del>
<mark><span id="line-4"> # Emphasized line</span></mark>
</code></pre>from typing import Generator, Tuple, Union, Pattern
from pygments.token import _TokenType
# Type aliases used throughout the highlighting system
TokenType = Union[_TokenType, int] # For Python 3.8 compatibility
TokenStream = Generator[Tuple[TokenType, str], None, None]The code highlighting system includes robust error handling:
Install with Tessl CLI
npx tessl i tessl/pypi-sphinxawesome-theme