xiaohongshu
xiaohongshu
markdown-content-formatter
Format and validate markdown documents with auto-generated TOC, frontmatter, structure validation, and cross-reference linking. Export to GitHub/CommonMark/Jekyll/Hugo.
Full skill instructions
Structure, validate, and format long-form markdown content for documentation, blogs, and static site generators. Auto-generate tables of contents, add frontmatter, validate structure, and convert between markdown flavors.
The markdown formatting process follows these steps:
from scripts.markdown_formatter import MarkdownFormatter
# Load and format markdown
formatter = MarkdownFormatter(file_path='document.md')
# Generate table of contents
toc = formatter.generate_toc(max_depth=3)
# Validate structure
validation = formatter.validate_structure()
if not validation['valid']:
print("Issues found:")
for error in validation['errors']:
print(f" - {error['message']}")
# Add frontmatter
formatter.add_frontmatter({
'title': 'My Document',
'author': 'John Doe',
'date': '2024-01-15'
})
# Export formatted version
formatter.export(
output_path='formatted.md',
include_toc=True,
target_flavor='github'
)
Auto-generate TOC from document heading structure:
Add YAML/TOML/JSON frontmatter for static site generators:
---) for Jekyll/Hugo+++) for HugoCheck document structure for common issues:
Enhance code blocks with syntax highlighting markers:
Auto-link headings and create cross-references:
Apply consistent formatting rules:
Convert between markdown flavors:
The validator identifies these common issues:
| Issue Type | Description | Example |
|---|---|---|
| Heading Skip | Level jumps (H2 → H4) | Missing H3 between H2 and H4 |
| Broken Link | Invalid internal/external link | [link](#missing-section) |
| Duplicate Heading | Same heading appears multiple times | Two "Introduction" headings |
| Missing ID | Heading lacks unique identifier | Anchor link fails |
| Invalid Structure | Incorrect nesting or formatting | List inside heading |
Initialization:
formatter = MarkdownFormatter(
file_path='document.md', # OR
content='# Markdown text...'
)
Parameters:
file_path (str): Path to markdown file (optional)content (str): Direct markdown content (optional)One of file_path or content must be provided.
toc = formatter.generate_toc(
max_depth=3, # Max heading level (1-6)
start_level=2, # Start from H2 (skip H1)
style='github' # 'github', 'numbered', 'bullets'
)
Returns: TOC markdown string
Styles:
github - Bulleted list with anchor linksnumbered - Numbered outlinebullets - Simple bullet listExample Output (github style):
## Table of Contents
- [Introduction](#introduction)
- [Getting Started](#getting-started)
- [Installation](#installation)
- [Configuration](#configuration)
- [Advanced Topics](#advanced-topics)
content = formatter.add_frontmatter(
metadata={
'title': 'Document Title',
'author': 'John Doe',
'date': '2024-01-15',
'tags': ['markdown', 'documentation']
},
format='yaml' # 'yaml', 'toml', or 'json'
)
Returns: Markdown content with frontmatter prepended
Example Output (YAML):
---
title: Document Title
author: John Doe
date: 2024-01-15
tags:
- markdown
- documentation
---
result = formatter.validate_structure()
Returns: Dictionary with validation results
{
'valid': bool,
'errors': [
{
'type': 'heading_skip',
'line': 45,
'message': 'Heading level jumps from H2 to H4'
}
],
'warnings': [
{
'type': 'duplicate_heading',
'line': 120,
'message': 'Heading "Introduction" appears multiple times'
}
]
}
content = formatter.format_code_blocks(
add_language_tags=True,
default_language='text'
)
Returns: Markdown with formatted code blocks
Converts:
code here
To:
```text
code here
```
content = formatter.auto_link_headings()
Returns: Markdown with heading IDs and cross-reference links
Generates GitHub-style anchors:
# Getting Started → <a id="getting-started"></a>[Getting Started](#getting-started)content = formatter.fix_spacing()
Returns: Markdown with consistent spacing
Applies rules:
content = formatter.convert_to_flavor(target='jekyll')
Parameters:
target (str): 'github', 'commonmark', 'jekyll', or 'hugo'Returns: Converted markdown string
formatter.export(
output_path='formatted.md',
include_toc=True,
include_frontmatter=True,
target_flavor='github'
)
Parameters:
output_path (str): Output file pathinclude_toc (bool): Add TOC at beginninginclude_frontmatter (bool): Preserve/add frontmattertarget_flavor (str): Target markdown flavorpython scripts/markdown_formatter.py \
--input document.md \
--toc \
--toc-depth 3 \
--toc-style github \
--output formatted.md
# From command line
python scripts/markdown_formatter.py \
--input document.md \
--frontmatter title="My Doc" author="John Doe" date="2024-01-15" \
--output formatted.md
# From file
python scripts/markdown_formatter.py \
--input document.md \
--frontmatter-file metadata.yaml \
--output formatted.md
python scripts/markdown_formatter.py \
--input document.md \
--validate \
--format json
Output:
{
"valid": false,
"errors": [
{
"type": "heading_skip",
"line": 45,
"message": "Heading level jumps from H2 to H4"
}
],
"warnings": []
}
python scripts/markdown_formatter.py \
--input document.md \
--toc \
--frontmatter title="My Doc" \
--auto-link \
--fix-spacing \
--flavor github \
--output formatted.md
# Format all markdown files in directory
for file in docs/*.md; do
python scripts/markdown_formatter.py \
--input "$file" \
--toc \
--fix-spacing \
--output "formatted/$file"
done
| Argument | Description | Default |
|---|---|---|
--input, -i | Input markdown file | Required |
--output, -o | Output file path | stdout |
--toc | Generate table of contents | False |
--toc-depth | Max TOC depth (1-6) | 3 |
--toc-style | TOC style (github/numbered/bullets) | github |
--frontmatter | Key=value pairs for frontmatter | - |
--frontmatter-file | YAML file with frontmatter | - |
--auto-link | Auto-link headings | False |
--fix-spacing | Fix spacing and formatting | False |
--flavor | Target markdown flavor | github |
--validate | Validate structure only | False |
--format | Output format for validation (json/text) | text |
formatter = MarkdownFormatter(file_path='guide.md')
toc = formatter.generate_toc(max_depth=3, style='github')
print(toc)
# ## Table of Contents
# - [Introduction](#introduction)
# - [Setup](#setup)
# - [Installation](#installation)
# - [Configuration](#configuration)
formatter = MarkdownFormatter(file_path='post.md')
formatter.add_frontmatter({
'layout': 'post',
'title': 'Getting Started with Markdown',
'date': '2024-01-15',
'categories': ['tutorial', 'markdown'],
'tags': ['beginner', 'documentation']
}, format='yaml')
formatter.export('_posts/2024-01-15-getting-started.md')
formatter = MarkdownFormatter(file_path='documentation.md')
result = formatter.validate_structure()
if not result['valid']:
print("Errors found:")
for error in result['errors']:
print(f"Line {error['line']}: {error['message']}")
print("\nWarnings:")
for warning in result['warnings']:
print(f"Line {warning['line']}: {warning['message']}")
else:
print("Document structure is valid!")
formatter = MarkdownFormatter(file_path='messy.md')
# Fix spacing issues
formatter.fix_spacing()
# Format code blocks
formatter.format_code_blocks(default_language='python')
# Add heading IDs
formatter.auto_link_headings()
# Export cleaned version
formatter.export('clean.md', target_flavor='github')
formatter = MarkdownFormatter(file_path='article.md')
# Add Hugo frontmatter
formatter.add_frontmatter({
'title': 'My Article',
'date': '2024-01-15T10:00:00Z',
'draft': False,
'tags': ['hugo', 'static-site'],
'categories': ['web-development']
}, format='toml')
# Generate TOC
toc = formatter.generate_toc(max_depth=2)
# Convert to Hugo flavor
formatter.convert_to_flavor('hugo')
# Export
formatter.export(
output_path='content/posts/my-article.md',
include_toc=True,
target_flavor='hugo'
)
# Validate all markdown files
for file in docs/**/*.md; do
echo "Validating $file..."
python scripts/markdown_formatter.py \
--input "$file" \
--validate \
--format json > "${file}.validation.json"
done
# Find files with errors
jq -r 'select(.valid == false) | input_filename' docs/**/*.validation.json
markdown>=3.5.0
pyyaml>=6.0.0
beautifulsoup4>=4.12.0
pandas>=2.0.0
Install dependencies:
pip install -r scripts/requirements.txt
- [ ] Task / - [x] Done~~text~~{{ variable }}{% include file.html %}{{< shortcode >}}xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience