sphinx-inlinecode

sphinx-inlinecode PyPI Version sphinx-inlinecode GitHub Repository https://static.pepy.tech/personalized-badge/sphinx-inlinecode?period=total&units=none&left_color=grey&right_color=blue&left_text=Downloads sphinx-inlinecode Documentation Status

sphinx-inlinecode is a Sphinx extension that embeds source code blocks directly into your documentation as a dropdown.

Example

sphinx_inlinecode.get_code_block(qualname, obj, highlighter)View on GitHub
View Source Code
def get_code_block(qualname: str, obj: Any, highlighter: PythonLexer) -> BeautifulSoup: """Parses and highlights the source code lines of the provided object :param qualname: the fully qualified name of the object :param obj: the actual object to retrieve the source code lines from :param highlighter: the Pygments lexer to highlight the code block with :return: the highlighted and fully formatted HTML codeblock to insert """ sourcelines, _ = inspect.getsourcelines(obj) initial_indent = len(sourcelines[0]) - len(sourcelines[0].lstrip()) if initial_indent: # Remove common leading whitespace pattern = fr"[ ]{{{initial_indent}}}(.*)" sourcelines = ( re.sub(pattern, r"\1", line) for line in sourcelines ) # Convert to HTML code block with syntax highlighting highlighted = highlighter.highlight_block( source=''.join(sourcelines), lang='python', linenos=False ) lines = highlighted.splitlines() before, after = re.split(r"<pre>(?:<span></span>)?", lines[0]) lines[0] = f'{before}<pre><div class="viewcode-block" id="{qualname}">{after}' code_block = '\n'.join(lines) return wrap_code_block(code_block)

Parses and highlights the source code lines of the provided object

Parameters:
  • qualname (str) – the fully qualified name of the object

  • obj (Any) – the actual object to retrieve the source code lines from

  • highlighter (PythonLexer) – the Pygments lexer to highlight the code block with

Returns:

the highlighted and fully formatted HTML codeblock to insert

Return type:

BeautifulSoup

Unlike sphinx.ext.viewcode, source code blocks will also be added for property and cached_property entries

Installation

To install sphinx-inlinecode via pip:

pip install sphinx-inlinecode

Configuration

Add the extension to your conf.py

extensions = [
    "sphinx_inlinecode",
]