Python Friday #59: Source Code in MkDocs

A good illustration of source code is a must-have when you want to use MkDocs for your project documentation. Let us find out what we need to display code snippets.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

Your usual way to format code does not work

You may be used to put your code between ` `. This works with some Markdown flavours, but in MkDocs that is converted in something rather unusable:

The whole code is smashed together

If you want multiple lines of code, you need to put it between ```    ``` (3x ` instead of 1 per group):

The code is now indented

This is better, but we can improve it a lot more.

 

Add markdown extensions to the Material theme

If this basic display for code is not enough, you need to add some additional markdown extensions to your mkdocs.yaml. They are bundled in the Material theme and should already be on your computer if you followed along the last post https://improveandrepeat.com/2021/02/python-friday-58-customise-mkdocs#material .
Be aware of the 4 spaces to indent linenums_style instead of the usual two – it will not work without them:

This configuration and the following examples work with the Material theme. Other themes have their own way to display code and you may need to install different extensions.

 

Syntax highlighting

To turn on syntax highlighting we need to specify which programming language we use. There is a long list of supported languages and for Python alone you get multiple options. For my examples I use python3:

Our code now uses syntax highlighting

 

Highlight lines of code

We can highlight lines of code by passing the line numbers to the hl_lines argument (the first line has the number 1):

We now see a few lines marked in yellow

 

Show line numbers

We can show line numbers with the linenums argument, that we need to activate:

We now can see the line numbers of our code sample

 

Put all together

We can use all those source code related features at once:

Line numbers with syntax highlighting and marked lines

 

Conclusion

MkDocs is a great help for me. I can focus on writing the documentation and MkDocs takes care of the rest. I can highly recommend MkDocs because it hits the balance of flexibility and ease of use just right.

1 thought on “Python Friday #59: Source Code in MkDocs”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.