An mdformat plugin for normalizing YAML, TOML, and JSON front matter in CommonMark documents.
Note
mdformat-frontmatter has additional duplicate key detection, but did not support mdformat v1 (butler54/mdformat-frontmatter #37) nor TOML and JSON at the time (butler54/mdformat-frontmatter#22 (comment))
Along with the 's', the extra dash is intentional to try to prevent typo errors.
- Multi-format support: Handles YAML (
---), TOML (+++), and JSON ({...}) front matter - Automatic normalization: Formats front matter consistently (preserves key order by default, standardized indentation)
- Configurable sorting: Option to sort keys alphabetically with
--sort-front-matter - Error resilient: Preserves original content if parsing fails. Will error only if
strictmode is set - Zero configuration: Works out of the box with mdformat
YAML Front Matter:
---
title: My Document
date: 2024-01-01
tags:
- example
- demo
---
# ContentWith --sort-front-matter, becomes:
---
date: 2024-01-01
tags:
- example
- demo
title: My Document
---
# ContentTOML Front Matter:
+++
title = "My Document"
date = 2024-01-01
tags = ["example", "demo"]
+++
# ContentJSON Front Matter:
{
"title": "My Document",
"date": "2024-01-01",
"tags": ["example", "demo"]
}
# ContentAdd this package wherever you use mdformat and the plugin will be auto-recognized. No additional configuration necessary. See additional information on mdformat plugins here
repos:
- repo: https://github.com/executablebooks/mdformat
rev: 1.0.0
hooks:
- id: mdformat
additional_dependencies:
- mdformat-front-mattersuvx --with mdformat-front-matters mdformatOr with pipx:
pipx install mdformat
pipx inject mdformat mdformat-front-mattersBy default, front matter keys preserve their original order. To sort keys alphabetically for consistency, use the --sort-front-matter flag.
# Default behavior - preserves original key order
mdformat document.md
# Sort keys alphabetically
mdformat document.md --sort-front-matterEnable strict mode to fail on invalid front matter instead of preserving it. Useful for CI/CD pipelines.
mdformat document.md --strict-front-matterIn strict mode:
- Invalid front matter raises an error
- Front matter without valid key-value pairs raises an error
- Ensures your documents have correctly formatted metadata
Example usage in pre-commit:
repos:
- repo: https://github.com/executablebooks/mdformat
rev: 0.7.19
hooks:
- id: mdformat
args: [--strict-front-matter]
additional_dependencies:
- mdformat-front-mattersTo hide Front Matter from generated HTML output, front_matters_plugin can be imported from mdit_plugins. For more guidance on MarkdownIt, see the docs: https://markdown-it-py.readthedocs.io/en/latest/using.html#the-parser
from markdown_it import MarkdownIt
from mdformat_front_matters.mdit_plugins import front_matters_plugin
md = MarkdownIt()
md.use(front_matters_plugin)
text = """
+++
title = "Example"
draft = false
+++
# Example
"""
md.render(text)
# <h1>Example</h1>See CONTRIBUTING.md