Skip to main content

Pre-commit hook to keep code snippets in Markdown and RST files in sync with source code

Project description

code_snippet_to_doc

PyPI - Version CI Python

code_snippet_to_doc keeps code snippets in documentation files in sync with source code. It replaces the content between special comments with the corresponding lines from source files, ensuring that code examples in documentation never go stale. It can be invoked as a pre-commit hook or as a standalone script. Documentation in Markdown and RestructuredText formats is supported.

How it works

Markdown

Add HTML comments to your Markdown file indicating which source file and line range to include:

Using line numbers:

<!-- code_snippet_start:path/to/file.c:10:20 -->

<!-- code_snippet_end -->

Using search patterns (glob-style):

<!-- code_snippet_start:path/to/file.c:/int main/:/return/ -->

<!-- code_snippet_end -->

Using regular expressions (prefix with r):

<!-- code_snippet_start:path/to/file.c:r/^int main/:r/^\}/ -->

<!-- code_snippet_end -->

Regex patterns support the full Python re syntax, including anchors like ^ (start of line) and $ (end of line).

Including or excluding the end line — by default, the end line is excluded from the snippet. Add a + suffix to include it:

<!-- code_snippet_start:path/to/file.c:r/^int main/:r/^\}/+ -->

<!-- code_snippet_end -->

The + suffix works with all end line specification types: line numbers, glob patterns, and regular expressions. It is convenient for extracting complete blocks like C function bodies, where the closing } should be included.

Colons inside search patterns must be escaped with \:.

File paths are resolved relative to the document file.

RestructuredText

Add RST comments to your .rst file using the same colon-separated syntax:

Using line numbers:

.. code_snippet_start:path/to/file.c:10:20

.. code_snippet_end

Using search patterns and regular expressions:

.. code_snippet_start:path/to/file.c:r/^int main/:r/^\}/+

.. code_snippet_end

The generated output uses RST's code-block directive with proper indentation:

.. code_snippet_start:path/to/file.c:r/^int main/:r/^\}/+

.. code-block:: c

   int main(int argc, char *argv[]) {
       printf("Hello, World!\n");
       return 0;
   }

.. code_snippet_end

All line specification types (line numbers, glob patterns, regex, + suffix) work the same way in both Markdown and RST files. The format is auto-detected from the file extension.

Then run code_snippet_to_doc — the area between the comments will be populated with a code block containing the specified source lines. The language for syntax highlighting is detected automatically from the file extension.

Usage as a pre-commit hook

Add to your .pre-commit-config.yaml:

repos:
-   repo: https://github.com/igrr/code_snippet_to_doc.git
    rev: v0.1.0
    hooks:
    -   id: code_snippet_to_doc

To update additional files beyond README.md, specify them in args::

repos:
-   repo: https://github.com/igrr/code_snippet_to_doc.git
    rev: v0.1.0
    hooks:
    -   id: code_snippet_to_doc
        args: [--input=README.md, --input=docs/GUIDE.md, --input=docs/api.rst]

Command-line usage

def get_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="code_snippet_to_doc")
    parser.add_argument(
        "-i",
        "--input",
        nargs="+",
        type=argparse.FileType("r+"),
        help="Documentation file to update (can be specified multiple times).",
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Check if the files need to be updated, but don't modify them. "
        "Non-zero exit code is returned if any file needs to be updated.",
    )
    parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
    return parser

Options:

  • -i, --input: Documentation files to update.
  • --check: Check if files need updating without modifying them. Returns exit code 2 if changes are needed.
  • --version: Show version.

Example

Given a source file example.c:

#include <stdio.h>

// Main function
int main(int argc, char *argv[]) {
    printf("Hello, World!\n");
    return 0;
}

And a Markdown file containing:

<!-- code_snippet_start:example.c:r/^int main/:r/^\}/+ -->

<!-- code_snippet_end -->

Running code_snippet_to_doc -i README.md will populate the snippet block with the main function body from example.c.

License

This tool is Copyright (c) 2026 Ivan Grokhotkov and distributed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

code_snippet_to_doc-0.1.0.tar.gz (14.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

code_snippet_to_doc-0.1.0-py3-none-any.whl (9.7 kB view details)

Uploaded Python 3

File details

Details for the file code_snippet_to_doc-0.1.0.tar.gz.

File metadata

  • Download URL: code_snippet_to_doc-0.1.0.tar.gz
  • Upload date:
  • Size: 14.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for code_snippet_to_doc-0.1.0.tar.gz
Algorithm Hash digest
SHA256 4b5027868cec205ec71975b13fe392c8906c53d3f5c25ee8472b194ee59d2df0
MD5 a3a8367ccea2aa6795523b55be4f85f2
BLAKE2b-256 2822a24821f8bd4b1db7fb7e2ddcfc71d21aebcb61ba43b14b4b3382b66cf706

See more details on using hashes here.

Provenance

The following attestation bundles were made for code_snippet_to_doc-0.1.0.tar.gz:

Publisher: main.yml on igrr/code_snippet_to_doc

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file code_snippet_to_doc-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for code_snippet_to_doc-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5bebcd943e613046bb00a2005c75b158e2e885213e488e5dd4571cd15dffc050
MD5 09b1f8ed0696d5fa676e4b515bf9788e
BLAKE2b-256 eb5344266dbd9e75ed42eed6716805bcfdc13055b3e737c429e006d9764d51d8

See more details on using hashes here.

Provenance

The following attestation bundles were made for code_snippet_to_doc-0.1.0-py3-none-any.whl:

Publisher: main.yml on igrr/code_snippet_to_doc

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page