Skip to content

Prevent MkDocs from replacing tabs with spaces in code blocks

This article describes MkDocs' default processing of tabs in code samples, explains why it can be a problem, and shows how to fix it.

MkDocs is a documentation-focused static site generator.

The problem: automatic replacement of tabs with spaces

When writing code examples, you can choose either spaces or tabs to indent your code. MkDocs' default behaviour is to replace tabs with spaces when building the site. This is due to the underlying Markdown parser: MkDocs uses Python Markdown's markdown implementation, and this conversion is the default behaviour of the parser.

This recently became a problem in my current docs work: it means that users copying my code examples will copy them with spaces, and we have a code linter that is very keen to enforce tabs. This is likely to trip up external users, or at least cause frustration, as our linter will error when users try to run our own code examples.

The solution: SuperFences with preserve_tabs

There's a large collection of Python Markdown extensions. This should always be your first stop when looking for workarounds or additional functionality for MkDocs.

The SuperFences extension provides various improvements for working with fenced blocks. A fenced block is a code block, like this:

// some code here
// some more code here

The other type of code formatting is inline code, which appears like this.

Using the preserve_tabs feature, you can prevent MkDocs from converting spaces to tabs in fenced blocks.

MkDocs automatically includes the SuperFences extension, so there are no additional installation steps, but you do need to enable it. In your mkdocs.yml file, enable the SuperFences extension and set preserve_tabs to true:

1
2
3
markdown_extensions:
  - pymdownx.superfences:
      preserve_tabs: true

This should work, but you may find the tabs add too much indentation visually. You can control the tab size from your CSS using the tab-size property. For example:

1
2
3
code {
    tab-size: 2
}

Limitations of preserve_tabs

  • Only works on code blocks, but it's unlikely you have spaces or tabs in inline code anyway.
  • The feature is experimental.
  • It's not officially supported by the Material theme (a popular MkDocs theme), but doesn't seem to cause any problems.

Wrap up

Thanks for joining me as I set a new personal best for most niche blog post topic.