# Usage

Once the extension is configured (see README/Overview),
you can execute code blocks by enabling the `exec` option:

````md
```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:

```bash
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`](#usage): The mother of all other options, enabling code execution.
- [`html`](#html-vs-markdown): Whether the output is alredady HTML, or needs to be converted from Markdown to HTML.
- [`id`](#handling-errors): Give an identifier to your code blocks to help
    [debugging errors](#handling-errors), or to [prefix HTML ids](#html-ids).
- [`idprefix`](#html-ids): Change or remove the prefix in front of HTML ids/hrefs.
- [`result`](#wrap-result-in-a-code-block): Choose the syntax highlight of your code block output.
- [`returncode`](shell.md#expecting-a-non-zero-exit-code): Tell what return code is expected (shell code).
- [`session`](#sessions): Execute code blocks within a named session, reusing previously defined variables, etc..
- [`source`](#render-the-source-code-as-well): Render the source as well as the output.
- [`tabs`](#change-the-titles-of-tabs): When rendering the source using tabs, choose the tabs titles.
- [`width`](#change-the-console-width): Change the console width through the `COLUMNS` environment variable.
- [`workdir`](#change-the-working-directory): Change the working directory.
- [`title`](#additional-options): Title is a [Material for MkDocs][material] option.
- [`updatetoc`](#generated-headings-in-table-of-contents): 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:

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
System information:

```python exec="true" html="true"
--8<-- "usage/platform_html.py"
```
````

Markdown Example:

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
System information:

```python exec="true"
--8<-- "usage/platform_md.py"
```
````

## 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:

````md
```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:

````md exec="1" source="material-block"
```python exec="1" idprefix="" updatetoc="no"
print("#### Commands")
print("\n[link to commands](#commands)")
```
````

The following ids are prefixed with `cli-`:

````md exec="1" source="material-block"
```python exec="1" idprefix="cli-" updatetoc="no"
print("#### Commands")
print("\n[link to 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-`:

````md exec="1" source="material-block"
```python exec="1" id="super-cli" updatetoc="no"
print("#### Commands")
print("\n[link to 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][material],
    and requires the [`md_in_html`][md_in_html] extension)
- `tabbed-left`: The source code and result will be rendered in tabs, in that order
    (requires the [`pymdownx.tabbed`][pymdownx.tabbed] extension).
- `tabbed-right`: The result and source code will be rendered in tabs, in that order
    (requires the [`pymdownx.tabbed`][pymdownx.tabbed] extension).
- `console`: The source and result are concatenated in a single code block, like an interactive console session.

**Source above:**

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
```python exec="true" source="above"
--8<-- "usage/source.py"
```
````

---

**Source below:**

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
```python exec="true" source="below"
--8<-- "usage/source.py"
```
````

---

**Material block:**

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
```python exec="true" source="material-block"
--8<-- "usage/source.py"
```
````

NOTE: **Important**  
The `material-block` source option requires that you enable the [`md_in_html`][md_in_html] Markdown extension.

---

**Tabbed on the left:**

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
```python exec="true" source="tabbed-left"
--8<-- "usage/source.py"
```
````

NOTE: **Important**  
The `tabbed-left` source option requires that you enable the [`pymdownx.tabbed`][pymdownx.tabbed] Markdown extension.

---

**Tabbed on the right:**

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
```python exec="true" source="tabbed-right"
--8<-- "usage/source.py"
```
````

NOTE: **Important**  
The `tabbed-left` source option requires that you enable the [`pymdownx.tabbed`][pymdownx.tabbed] Markdown extension.

---

**Console** <small>(best used with actual session syntax like
[`pycon`](python.md#python-console-code) or [`console`](shell.md#console))</small>:

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
```pycon exec="true" source="console"
--8<-- "usage/source.pycon"
```
````

[md_in_html]: https://python-markdown.github.io/extensions/md_in_html/
[pymdownx.tabbed]: https://facelessuser.github.io/pymdown-extensions/extensions/tabbed/

## Hiding lines from the source

Every line that contains the string `markdown-exec: hide` will be hidden from the
displayed source.

=== "Markdown"
    ````md
    ```python exec="true" source="above"
    --8<-- "usage/hide.py"
    ```
    ````

=== "Rendered"
    ```python exec="true" source="above"
    --8<-- "usage/hide.py"
    ```

## 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:

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
```python exec="1" source="tabbed-left" tabs="Source code|Output"
--8<-- "usage/source.py"
```
````

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 `\|`:

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
```python exec="1" source="tabbed-left" tabs="OR operator: a \|\| b | Boolean matrix"
--8<-- "usage/boolean_matrix.py"
```
````

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.


WARNING: **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:

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
```console exec="1" result="ini"
$ cat .git/config
```
````

WARNING: **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).

````md exec="1" source="tabbed-left"
```bash exec="1" width="10"
echo $COLUMNS
```

```bash exec="1" width="1000"
echo $COLUMNS
```
````

## Change the working directory

To change the working directory for the execution of a code block, use the `workdir` option.

````md exec="1" source="tabbed-left"
```bash exec="1"
pwd
```

```bash exec="1" workdir=".."
pwd
```
````

## Additional options

If you are using [Material for MkDocs][material],
you are probably familiar with the `title` option on code blocks:

````md
```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:

````md exec="1" source="tabbed-left" tabs="Markdown|Rendered"
```python exec="1" source="above" title="source.py"
--8<-- "usage/source.py"
```
````

## 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](shell.md#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:

````md
```python exec="true"
print("hello")
assert 1 + 1 == 11
```
````

```text title="MkDocs output"
WARNING  -  markdown_exec: Execution of python code block exited with errors
```

```python title="Rendered traceback"
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:

````md
```python exec="true" id="print hello"
print("hello")
assert 1 + 1 == 11
```
````

```text title="MkDocs output"
WARNING  -  markdown_exec: Execution of python code block 'print hello' exited with errors
```

> TIP: **Titles act as IDs as well!**  
> You *don't need* to provide an ID
> if you already set a (Material for MkDocs) title:
>
> ````md
> ```python exec="true" title="print world"
> print("world")
> assert 1 + 1 == 11
> ```
> ````
>
> ```text title="MkDocs output"
> 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:

````md exec="1" source="material-block" title="Sessions"
```python exec="1" session="greet"
def greet(name):
    print(f"Hello {name}!")
```

Hello Mushu!

```python exec="1" session="greet"
greet("Ping")
```
````

WARNING: **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](https://en.wikipedia.org/wiki/Literate_programming):

> 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="tabbed-left"
```md exec="1" source="material-block" title="Markdown link"
[Link to example.com](https://example.com)
```
````

> TIP: **So power, such meta**  
> The above example (both tabs) was entirely generated using *a literate code block in a literate code block* 🤯:
> 
> `````md
> ````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](../index.md#configuration),
Markdown Exec can be configured directly as a MkDocs plugin:

```yaml
# 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:

```python exec="1" source="material-block"
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}`")
```

The environment variable will be restored to its previous value, if any,
at the end of the build.

[material]: https://squidfunk.github.io/mkdocs-material/