1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
|
# 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/
|