Formatting Markdown files with mdformat¶
At some point I was looking at the .pre-commit-config.yaml that the ruff project uses.
Looking at how other projects do things, what tools they use, how they work, etc. is a great way to learn.
I noticed several pre-commit hooks that were interesting, one of which was mdformat.
mdformat is "an opionionated Markdown formatter".
It has a specific formatting style that cannot be configured.
There are a few configuration options though.
The nice thing is that it has a plugin system giving you the ability to add support for syntax other than what is defined by CommonMark. In addition, there is also support for code formatter plugins to format code in fenced code blocks.
For example, for a project that uses mkdocs with the fantastic mkdocs-material theme (like this website uses), the mdformat-mkdocs plugin offers the necessary support.
You can find the see the setup that this website uses in the corresponding .pre-commit-config.yaml.
Compatibility with markdownlint
I have been using markdownlint for a while.
Since both tools support CommonMark they are basically compatible.
I run both tools via pre-commit hooks.
First, mdformat, and then markdownlint-cli2 so that the linting is done on an already formatted file.
The one thing that does not work, unfortunately, is when you use a comment to disable a certain markdownlint rule for the next line.
mdformat adds an empty line in between the comment and the next line invalidating disabling the rule.
And now come my few seconds of fame
On episode 425 of the Python Bytes podcast the hosts were talking about formatting Python code in fenced code blocks in Markdown files. One of the hosts mentioned that it would be great to have a formatter for Markdown files as well.
Since I had just come across mdformat I sent it in and it was covered in the next episode.
The episode was even titled "Committing to Formatted Markdown".
I mentioned it'd be nice to have an autoformatter for Markdown files...
Matthias delivered with suggestingmdformat.— Brian on Python Bytes #426