Source code and APIs#

1.  Basic block syntax highlighting#

Code blocks contain a language identifier, which is used to determine the language of the code. This language is used to determine the syntax highlighting, using an available pygments lexer.

```python
from a import b
c = "string"
```
from a import b
c = "string"

2.  Inline syntax highlighting#

The attrs_inline extension can be used to apply syntax highlighting to inline code:

Inline Python code `a = "b"`{l=python}

Inline Python code a = "b"

3.  Numbering and highlighting lines#

To set a global default for line numbering, per lexer name, the myst_number_code_blocks configuration option can be used. For example, using:

myst_number_code_blocks = ["typescript"]

Will number all code blocks with the typescript lexer by default.

```typescript
type MyBool = true | false;

interface User {
  name: string;
  id: number;
}
```
1type MyBool = true | false;
2
3interface User {
4  name: string;
5  id: number;
6}

To apply numbering and highlighting to a specific code block, the attrs_block extension can be used:

{lineno-start=1 emphasize-lines="2,3"}
```python
a = 1
b = 2
c = 3
```
1a = 1
2b = 2
3c = 3

4.  Adding a caption#

With the code-block directive, a caption can be added to a code blocks, as well as other options:

```{code-block} python
:caption: This is a caption
:emphasize-lines: 2,3
:lineno-start: 1

a = 1
b = 2
c = 3
```
This is a caption#
1a = 1
2b = 2
3c = 3

The following options are recognized:

5.  Including code from files#

Longer pieces of code can be included from files using the literalinclude directive:

```{literalinclude} examples/example.py
```
"""An example Python file."""


# start example
class MyClass:
    """An example class."""

    def __init__(self, x: int, y: int):
        """An example method."""
        self.x = x
        self.y = y


# end example

a = 1

The file name is usually relative to the current file’s path. However, if it is absolute (starting with /), it is relative to the top source directory.

To select only a sub-section of the file, the lines, pyobject or start-after and end-before options can be used:

```{literalinclude} examples/example.py
:start-after: start example
:end-before: end example
```
class MyClass:
    """An example class."""

    def __init__(self, x: int, y: int):
        """An example method."""
        self.x = x
        self.y = y


See also

The Sphinx documentation

6.  Documenting whole APIs#

Sphinx and MyST provide means to analyse source code and automatically generate documentation and referenceable links for APIs.

sphinx.ext.autodoc can be used (see below), however, it is not inherently compatible with MyST Markdown, and so the sphinx-autodoc2 extension is recommended.

6.1.  sphinx-autodoc2#

sphinx-autodoc2 is an extension for Sphinx that provides an integrated means to document Python APIs.

As opposed to sphinx.ext.autodoc, sphinx-autodoc2 performs static (rather than dynamic) analysis of the source code, integrates full package documenting, and also allows for docstrings to be written in both RestructureText and MyST.

The auto_mode will automatically generate the full API documentation, as shown API Reference.

Alternatively, the autodoc2-object directive can be used to generate documentation for a single object. To embed in a MyST document the MyST render_plugin should be specified, for example:

```{autodoc2-object} myst_parser.sphinx_ext.main.setup_sphinx
render_plugin = "myst"
no_index = true
```
myst_parser.sphinx_ext.main.setup_sphinx(app: sphinx.application.Sphinx, load_parser: bool = False) None[source]

Initialize all settings and transforms in Sphinx.

Parameters:
  • app – The Sphinx application object.

  • load_parser – Whether to load the parser.

This can be referenced elsewhere in the document using the :py:obj: role, or a # link (see cross-referencing).

- {py:obj}`myst_parser.sphinx_ext.main.setup_sphinx`
- [](#myst_parser.sphinx_ext.main.setup_sphinx)

Additionally, summaries of multiple objects can be generated using the autodoc2-summary directive:

```{autodoc2-summary}
:renderer: myst

~myst_parser.sphinx_ext.main.setup_sphinx
~myst_parser.sphinx_ext.main.create_myst_config
```

setup_sphinx

Initialize all settings and transforms in Sphinx.

create_myst_config

Create the myst config object and add it to the sphinx environment.

Using MyST docstrings#

sphinx-autodoc2 can be configured to use MyST docstrings (rather than RestructureText), for the entire project or select objects, by setting the autodoc2_docstring_parser_regexes configuration option:

autodoc2_docstring_parser_regexes = [
    # this will render all docstrings as Markdown
    (r".*", "myst"),
    # this will render select docstrings as Markdown
    (r"mypackage\.mymodule\..*", "myst"),
]

For example:

```{autodoc2-object} myst_parser.setup
render_plugin = "myst"
no_index = true
docstring_parser_regexes = [
    ["myst_parser\\.setup", "myst"],
]
```
myst_parser.setup(app)[source]

Initialize the Sphinx extension.

6.2.  sphinx.ext.autodoc#

Sphinx extension autodoc also can generate documentation for Python objects. However, because it is hard-coded to generate RestructureText, the special eval-rst directive needs to be used:

```{eval-rst}
.. autofunction:: myst_parser.sphinx_ext.main.setup_sphinx
    :noindex:
```
myst_parser.sphinx_ext.main.setup_sphinx(app: Sphinx, load_parser: bool = False) None[source]

Initialize all settings and transforms in Sphinx.

Parameters:
  • app – The Sphinx application object.

  • load_parser – Whether to load the parser.

Summaries can also be generated with autosummary:

```{eval-rst}
.. autosummary::
    :nosignatures:

    myst_parser.sphinx_ext.main.setup_sphinx
    myst_parser.sphinx_ext.main.create_myst_config
```

myst_parser.sphinx_ext.main.setup_sphinx

Initialize all settings and transforms in Sphinx.

myst_parser.sphinx_ext.main.create_myst_config

Create the myst config object and add it to the sphinx environment.