markdown_snippet_injector/README.md
2026-02-04 14:09:41 +01:00

2.3 KiB

Code snippet markdown insertion tool

This tool allows the definition of tags within any code base to be referred to in a markdown documentation file.

The specific XML tags present in the markdown file are replaced by the corresponding code snippet, pulled directly from the linked source code file.

This allows the documentation to evolve automatically when the source files are modified, thus reducing the maintenance effort of such documentation, especially in cases where minor changes in the code do not necesitate updating the documentation, but that the snippets must be kept up-to-date with the actual code.

Usage

python markdown_snippet_injector.py source_markdown.md processed_markdown.md

Example

Here are links to examples of an unprocessed and the corresponding processed markdown files.

Markdown XML tags

The source markdown file has specific XML tags <include_snippet/> embedded that will be replaced by the actual code contained within the corresponding tags in the related source files.

Two parameters must be specified :

  • name : unique name of the snippet
  • file : file path in which to find the snippet
<include_snippet name="snippet_name" file="source_code_file.cpp"/>

Here is a simple example of a markdown file containing a tag :

    ## The includes

    The includes are important to tell the compiler what to expect later. In the example file, the includes are :

    ```cpp
    <include_snippet name="includes" file="example_code.cpp"/>
    ```

Code file tags

In the code files, the tags must be under the following form :

BEGIN CODE SNIPPET snippet_name
Some code that will be included in the snippet
END CODE SNIPPET

Note that the entire line where BEGIN CODE SNIPPET and END CODE SNIPPET is removed from the output markdown file. It is recommended to put the tags in separate lines around the snippet you want to capture.

Depending on the language of the source file, the appropriate comment format must be used, so that the tag's presence does not change the behavior of the program.

Example in python :

# BEGIN CODE SNIPPET snippet_name
v1 = np.array([1.0, 2.0, 3.0])
# END CODE SNIPPET

Example in C++ :

// BEGIN CODE SNIPPET snippet_name
const auto v1 = {1.0, 2.0, 3.0};
// END CODE SNIPPET