Skip to article content

You can include code in your documents using the standard markup syntax of ```language, where language is the programming language for highlighting.

Code blocks

The above code is not a directive, it is just standard markdown syntax, which cannot add a caption or label. To caption or label blocks of code use the code directive.

Numbering and Highlighting

To add numbers and emphasis to lines use the code directive. You can use linenos which is a flag, with no value, and emphasize-lines with a comma-separated list of line numbers to emphasize.

1
2
3
4
```{code}
:linenos:
:emphasize-lines: 2,3
...

Emphasize lines inside of a code block.

You can also set the start number using the lineno-start directive, and all emphasized lines will be relative to that number.

Showing a Filename

Adding a filename option will show the name of the file at the top of the code block. For example, myst.yml in the following example:

Including Files

If your code is in a separate file you can use the literalinclude directive (or the include directive with the literal flag). This directive is helpful for showing code snippets without duplicating your content.

For example, a literalinclude of a snippet of the myst.yml such as:

```{literalinclude} myst.yml
:start-at: project
:end-before: references
:lineno-match:
```

creates a snippet that has matching line numbers, and starts at a line including "project" and ends before the line including "references".

myst.yml
2
3
4
5
6
7
8
project:
  title: MyST Markdown
  github: https://github.com/executablebooks/mystmd
  license:
    code: MIT
    content: CC-BY-4.0
  subject: MyST Markdown

The argument of an include directive is the file path (docs), which is relative to the file from which it was referenced. By default the file will be parsed using MyST, you can also set the file to be literal, which will show as a code-block; this is the same as using the literalinclude directive.

If in literal mode, the directive also accepts all of the options from the code-block (e.g. linenos). To select a portion of the file to be shown using the start-at/start-after selectors with the end-before/end-at, which use a snippet of included text.

Alternatively, you can explicitly select the lines (e.g. 1,3,5-10,20-) or the start-line/end-line (which is zero based for compatibility with Sphinx).

The include directive is based on RST and Sphinx.

MyST MarkdownMyST Markdown
Community-driven tools for the future of technical communication and publication