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 {code.caption}
or {code.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 {code.linenos}
which is a flag, with no value, and {code.emphasize-lines}
with a comma-separated list of line numbers to emphasize.
You can also set the start number using the {code.lineno-start}
directive, and all emphasized lines will be relative to that number.
Docutils and Sphinx Compatibility
For full compatibility with Sphinx we suggest using {code-block}
directive, which is an alias of the {code}
directive. The MyST implementation supports both the Sphinx {code-block} directive
as well as the docutils
{code} directive implementation, which only supports the number-lines
option.
You can use either code
or code-block
directive documented above or even a normal markdown code block.
All implementations in MyST are resolved to the same code
type in the abstract syntax tree.
Showing a Filename¶
Adding a {code.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 Code Files¶
If your code is in a separate file you can use the {literalinclude}
directive (or the {include}
directive with the {include.literal}
flag).
This directive is helpful for showing code snippets without duplicating your content.
For parsing the file, see the documentation in The {include}
directive.
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"
.
2 3 4 5 6 7 8
project: title: MyST Markdown github: https://github.com/jupyter-book/mystmd license: code: MIT content: CC-BY-4.0 subject: MyST Markdown
In {include.literal}
mode, the include directive also accepts all of the options from the code-block
(e.g. {include.linenos}
).
To select a portion of the file to be shown using the {include.start-at}
/{include.start-after}
selectors with the {include.end-before}
/{include.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 {include.start-line}
/{include.end-line}
(which is zero based for compatibility with Sphinx).
The include directive is based on RST and Sphinx.