Usage¤
Once the extension is configured (see README/Overview), you can execute code blocks by enabling the exec
option:
```python exec="on"
print("Hello Markdown!")
```
The exec
option will be true for every possible value except 0
, no
, off
and false
(case insensitive).
To enable automatic execution of code blocks for specific languages (without having to add the exec="on"
option to your code blocks), set the MARKDOWN_EXEC_AUTO
environment variable:
MARKDOWN_EXEC_AUTO=python,bash
Options summary¤
As the number of options grew over time, we now provide this summary listing every option, linking to their related documentation:
exec
: The mother of all other options, enabling code execution.html
: Whether the output is alredady HTML, or needs to be converted from Markdown to HTML.id
: Give an identifier to your code blocks to help debugging errors, or to prefix HTML ids.idprefix
: Change or remove the prefix in front of HTML ids/hrefs.result
: Choose the syntax highlight of your code block output.returncode
: Tell what return code is expected (shell code).session
: Execute code blocks within a named session, reusing previously defined variables, etc..source
: Render the source as well as the output.tabs
: When rendering the source using tabs, choose the tabs titles.width
: Change the console width through theCOLUMNS
environment variable.workdir
: Change the working directory.title
: Title is a Material for MkDocs option.updatetoc
: Whether to update the Table of Contents with generated headings.
HTML vs. Markdown¤
By default, Markdown Exec will render what you print as Markdown. If you want to skip rendering, to inject HTML directly, you can set the html
option to true.
HTML Example:
System information:
```python exec="true" html="true"
import platform
print(
f"""
<ul>
<li>machine: <code>{platform.machine()}</code></li>
<li>version: <code>{platform.version()}</code></li>
<li>platform: <code>{platform.platform()}</code></li>
<li>system: <code>{platform.system()}</code></li>
</ul>
"""
)
```
System information:
- machine:
x86_64
- version:
#1 SMP PREEMPT_DYNAMIC Fri, 28 Jun 2024 04:32:50 +0000
- platform:
Linux-6.9.7-arch1-1-x86_64-with-glibc2.39
- system:
Linux
Markdown Example:
System information:
```python exec="true"
import platform
from textwrap import dedent
print(
# we must dedent, otherwise Markdown
# will render it as a code block!
dedent(
f"""
- machine: `{platform.machine()}`
- version: `{platform.version()}`
- platform: `{platform.platform()}`
- system: `{platform.system()}`
"""
)
)
```
System information:
- machine:
x86_64
- version:
#1 SMP PREEMPT_DYNAMIC Fri, 28 Jun 2024 04:32:50 +0000
- platform:
Linux-6.9.7-arch1-1-x86_64-with-glibc2.39
- system:
Linux
Generated headings in Table of Contents¤
If you are using Python Markdown's toc
extension, or writing docs with MkDocs, you will notice that the headings you generated by executing a code block appear in the table of contents. If you don't want those headings to appear in the ToC, you can use the updatetoc="no"
boolean option:
```python exec="1" updatetoc="no"
print("# XL heading\n")
print("## L heading\n")
print("### M heading\n")
print("#### S heading\n")
```
HTML ids¤
When your executed code blocks output Markdown, this Markdown is rendered to HTML, and every HTML id is automatically prefixed with exec-N--
, where N is an integer incremented with each code block. To avoid breaking links, every href
attribute is also updated when relevant.
You can change this prefix, or completely remove it with the idprefix
option.
The following ids are not prefixed:
```python exec="1" idprefix="" updatetoc="no"
print("#### Commands")
print("\n[link to commands](#commands)")
```
Commands¤
The following ids are prefixed with cli-
:
```python exec="1" idprefix="cli-" updatetoc="no"
print("#### Commands")
print("\n[link to commands](#commands)")
```
Commands¤
If idprefix
is not specified, and id
is specified, then the id is used as prefix:
The following ids are prefixed with super-cli-
:
```python exec="1" id="super-cli" updatetoc="no"
print("#### Commands")
print("\n[link to commands](#commands)")
```
Commands¤
Render the source code as well¤
It's possible to render both the result of the executed code block and the code block itself. For this, use the source
option with one of the following values:
above
: The source code will be rendered above the result.below
: The source code will be rendered below the result.material-block
: The source code and result will be wrapped in a nice-looking block (only works with Material for MkDocs, and requires themd_in_html
extension)tabbed-left
: The source code and result will be rendered in tabs, in that order (requires thepymdownx.tabbed
extension).tabbed-right
: The result and source code will be rendered in tabs, in that order (requires thepymdownx.tabbed
extension).console
: The source and result are concatenated in a single code block, like an interactive console session.
Source above:
```python exec="true" source="above"
print("I'm the result!")
```
print("I'm the result!")
I'm the result!
Source below:
```python exec="true" source="below"
print("I'm the result!")
```
I'm the result!
print("I'm the result!")
Material block:
```python exec="true" source="material-block"
print("I'm the result!")
```
print("I'm the result!")
I'm the result!
Important
The material-block
source option requires that you enable the md_in_html
Markdown extension.
Tabbed on the left:
```python exec="true" source="tabbed-left"
print("I'm the result!")
```
print("I'm the result!")
I'm the result!
Important
The tabbed-left
source option requires that you enable the pymdownx.tabbed
Markdown extension.
Tabbed on the right:
```python exec="true" source="tabbed-right"
print("I'm the result!")
```
I'm the result!
print("I'm the result!")
Important
The tabbed-left
source option requires that you enable the pymdownx.tabbed
Markdown extension.
Console (best used with actual session syntax like pycon
or console
):
```pycon exec="true" source="console"
>>> print("I'm the result!")
I'm not the result...
```
>>> print("I'm the result!")
I'm the result!
Hiding lines from the source¤
Every line that contains the string markdown-exec: hide
will be hidden from the displayed source.
```python exec="true" source="above"
print("Hello World!")
print("<hr>") # markdown-exec: hide
```
print("Hello World!")
Hello World!
Change the titles of tabs¤
In the previous example, we didn't specify any title for tabs, so Markdown Exec used "Source" and "Result" by default. You can customize the titles with the tabs
option:
```python exec="1" source="tabbed-left" tabs="Source code|Output"
print("I'm the result!")
```
print("I'm the result!")
I'm the result!
As you can see, titles are separated with a pipe |
. Both titles are stripped so you can add space around the pipe. If you need to use that character in a title, simply escape it with \|
:
```python exec="1" source="tabbed-left" tabs="OR operator: a \|\| b | Boolean matrix"
print()
print("a | b | a \\|\\| b")
print("--- | --- | ---")
for a in (True, False):
for b in (True, False):
print(f"{a} | {b} | {a or b}")
print()
```
print()
print("a | b | a \\|\\| b")
print("--- | --- | ---")
for a in (True, False):
for b in (True, False):
print(f"{a} | {b} | {a or b}")
print()
a | b | a || b |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Important
The tabs
option always expects the "Source" tab title first, and the "Result" tab title second. It allows to switch from tabbed-left to tabbed-right and inversely without having to switch the titles as well.
Limitation
Changing the title for only one tab is not supported.
Wrap result in a code block¤
You can wrap the result in a code block by specifying a code block language:
```console exec="1" result="ini"
$ cat .git/config
```
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = git@github.com:pawamoy-insiders/markdown-exec
fetch = +refs/heads/*:refs/remotes/origin/*
[remote "upstream"]
url = git@github.com:pawamoy/markdown-exec
fetch = +refs/heads/*:refs/remotes/upstream/*
[branch "main"]
remote = origin
merge = refs/heads/main
Limitation
Wrapping the result is not possible when HTML output is enabled.
Change the console width¤
To change the console width for the execution of a code block, use the width
option. Internally, Markdown Exec will set the COLUMNS
environment variable accordingly, and restore its previous value after execution.
If the executed code doesn't support this environment variable, the default console width will be used (it could be the current width or some arbitrary value).
```bash exec="1" width="10"
echo $COLUMNS
```
```bash exec="1" width="1000"
echo $COLUMNS
```
10
1000
Change the working directory¤
To change the working directory for the execution of a code block, use the workdir
option.
```bash exec="1"
pwd
```
```bash exec="1" workdir=".."
pwd
```
/home/pawamoy/data/dev/insiders/markdown-exec
/media/data/dev/insiders
Additional options¤
If you are using Material for MkDocs, you are probably familiar with the title
option on code blocks:
```python title="setup.py"
from setuptools import setup
setup(...)
```
Markdown Exec will add back these unrecognized options when rendering the source, so you can keep using them normally.
Example:
```python exec="1" source="above" title="source.py"
print("I'm the result!")
```
print("I'm the result!")
I'm the result!
Handling errors¤
Code blocks execution can fail. For example, your Python code may raise exceptions, or your shell code may return a non-zero exit code (for shell commands that are expected to return non-zero, see Expecting a non-zero exit code).
In these cases, the exception and traceback (Python), or the current output (shell) will be rendered instead of the result, and a warning will be logged.
Example of failing code:
```python exec="true"
print("hello")
assert 1 + 1 == 11
```
WARNING - markdown_exec: Execution of python code block exited with errors
Traceback (most recent call last):
File "/path/to/markdown_exec/formatters/python.py", line 23, in _run_python
exec(code, exec_globals) # noqa: S102
File "<executed code block>", line 2, in <module>
assert 1 + 1 == 11
AssertionError
With many executed code blocks in your docs, it will be hard to know which code block failed exactly. To make it easier, you can set an ID on each code block with the id
option, and this ID will be shown in the logs:
```python exec="true" id="print hello"
print("hello")
assert 1 + 1 == 11
```
WARNING - markdown_exec: Execution of python code block 'print hello' exited with errors
Titles act as IDs as well!
You don't need to provide an ID if you already set a (Material for MkDocs) title:
```python exec="true" title="print world"
print("world")
assert 1 + 1 == 11
```
WARNING - markdown_exec: Execution of python code block 'print world' exited with errors
Sessions¤
Markdown Exec makes it possible to persist state between executed code blocks. To persist state and reuse it in other code blocks, give a session name to your blocks:
```python exec="1" session="greet"
def greet(name):
print(f"Hello {name}!")
```
Hello Mushu!
```python exec="1" session="greet"
greet("Ping")
```
Hello Mushu!
Hello Ping!
Limitation
Sessions only work with Python and Pycon syntax for now.
Literate Markdown¤
With this extension, it is also possible to write "literate programming" Markdown.
From Wikipedia:
Literate programming (LP) tools are used to obtain two representations from a source file: one understandable by a compiler or interpreter, the "tangled" code, and another for viewing as formatted documentation, which is said to be "woven" from the literate source.
We effectively support executing multiple nested code blocks to generate complex output. That makes for a very meta-markdown markup:
```md exec="1" source="material-block" title="Markdown link"
[Link to example.com](https://example.com)
```
[Link to example.com](https://example.com)
So power, such meta
The above example (both tabs) was entirely generated using a literate code block in a literate code block 🤯:
````md exec="1" source="tabbed-left"
```md exec="1" source="material-block" title="Markdown link"
[Link to example.com](https://example.com)
```
````
In fact, all the examples on this page were generated using this method! Check out the source here: https://github.com/pawamoy/markdown-exec/blob/master/docs/usage/index.md (click on "Raw" to see the code blocks execution options).
Of course "executing" Markdown (or rather, making it "literate") only makes sense when the source is shown as well.
MkDocs integration¤
As seen in the Configuration section, Markdown Exec can be configured directly as a MkDocs plugin:
# mkdocs.yml
plugins:
- search
- markdown-exec
When configured this way, it will set a MKDOCS_CONFIG_DIR
environment variable that you can use in your code snippets to compute file paths as relative to the MkDocs configuration file directory, instead of relative to the current working directory. This will make it possible to use the -f
option of MkDocs, to build the documentation from a different directory than the repository root.
Example:
import os
config_dir = os.environ['MKDOCS_CONFIG_DIR']
# This will show my local path since I deploy docs from my machine:
print(f"Configuration file directory: `{config_dir}`")
Configuration file directory: /media/data/dev/insiders/markdown-exec
The environment variable will be restored to its previous value, if any, at the end of the build.