Trust Your Tools: Stop Reinventing the Wheel in MkDocs
Have you ever spent hours fighting with a code formatter just to get a perfectly indented Table of Contents in your Markdown files? We've all been there.
Recently, I found myself wrestling with Prettier and EditorConfig just to maintain a 2-space indented list for a ## Table of Contents section in a Python documentation file. After configuring .editorconfig, creating a .prettierrc, and tweaking Prettier-ignore blocks to prevent my manual Table of Contents from getting mangled... I had a moment of clarity.
Why was I doing this manually when I'm using MkDocs?
The Problem: Fighting the Formatter
It started as a simple issue: I wanted my Markdown files to use 2-space indentation instead of 4 spaces.
I installed the EditorConfig extension, set up the rules, and it didn't seem to work immediately. Prettier got involved, and suddenly my <!-- prettier-ignore-start --> blocks and Markdown syntax were being reformatted and mangled, leading to broken list indentations and escaped backticks (\*args\*).
I was spending more time fixing the formatting of my manual Table of Contents than actually writing the documentation itself!
The Solution: Use the Tool As Intended
MkDocs (and specifically the Material for MkDocs theme) is a powerful tool designed to automate exactly this kind of busywork.
Instead of manually maintaining a nested Markdown list of links to headers, MkDocs provides two significantly better out-of-the-box solutions:
1. The [TOC] Macro
Python-Markdown has built-in support for generating a Table of Contents. If you absolutely need an inline Table of Contents in the center of your page, you can simply replace your entire nested list with:
MkDocs will automatically parse the headers (##, ###) on the page and generate a perfectly formatted list on the fly when the site builds. No formatting required.
2. Theme Integration (The Best Way)
If you're using the Material for MkDocs theme, you don't even need the [TOC] tag. By adding the toc.integrate feature to your mkdocs.yml:
The theme entirely removes the need for an on-page Table of Contents. It auto-generates a sticky, interactive Table of Contents and integrates it directly into the left navigation sidebar under the current page name.
Key Takeaway
Before spending hours writing custom formatting rules or fighting with linters over boilerplate text, take a step back and check your tool's documentation.
More often than not, the framework you are using already has an automated, elegant solution. Stop reinventing the wheel—trust your tools to do the heavy lifting!