Search code examples
read-the-docsmkdocspython-markdown

Code block in a numbered list messes up numbering python-markdown/mkdocs


I am creating a list of instructions for one of my projects in mkdocs, which I believe uses python-markdown as its markdown engine. But when I try to put a fenced code block in between numbers in the list it renders the numbering wrong.

An example of what is failing me (I also tried to put newlines between each backtick fence and the actual words but it still messes up the numbering):


1. Click this
```
some code
```
2. Click that

which renders something like this:


1. Click this

some code

1. Click that

Then when I try to indent it it just messes up the rendering:


1. Click this
    ```
    some code
    ```
2. Click that

To


1. Click this ``` some code ```
2. Click that

Yes tabbing works, but what if I wanted to do code highlighting with ```language. Is there a way to keep the fenced code blocks, but also maintain the list numbering.


Solution

  • Pyhton-Markdown's documentation specifically states (in a red warning box):

    Warning: Fenced Code Blocks are only supported at the document root level. Therefore, they cannot be nested inside lists or blockquotes.

    Therefore, you must use indented code blocks. Of course, to keep it as a code block, and have it nested, you need to indent it twice:

    1. Click this
    
            some code
    
    2. Click that
    

    If you want to define a language for your code block, you will need to enable the CodeHilite extension using the markdown_extensions config option in your mkdocs.yml config file:

    markdown_extensions:
        codehilite:
            use_pygments: False
    

    By setting the use_pygments option to False, CodeHilite will output the same HTML as fenced code blocks which will then be highlighted by the JS library provided by the MkDocs theme.

    Then you need to use CodeHilite's syntax for defining a language:

    1. Click this
    
            :::language    
            some code
    
    2. Click that