mcpField
M
markdown-content-formatter

markdown-content-formatter

github.com/dkyazzentwatwa文档处理12461 次安装29 周前更新
代码仓库

关于 markdown-content-formatter

markdown-content-formatter 是面向文档作者和团队的 Python 工具,可检查并整理长篇 Markdown 内容。它结合结构验证、目录与 frontmatter 生成,以及多种 Markdown 风格转换。

主要功能

  1. 01检查标题、链接和文档结构
  2. 02生成目录
  3. 03添加 YAML、TOML 或 JSON frontmatter
  4. 04整理代码块和间距
  5. 05创建标题链接和交叉引用
  6. 06转换不同 Markdown 风格

适用场景

  1. 01检查文档中的标题和链接问题
  2. 02为静态站点生成器准备文章
  3. 03批量统一 Markdown 文件格式
  4. 04在支持的 Markdown 风格间转换内容

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/dkyazzentwatwa/chatgpt-skills --skill markdown-content-formatter

安装后在 Claude Code 中输入/markdown-content-formatter确认已加载。

附带文件scripts/markdown_formatter.pyscripts/requirements.txt

详细介绍

Markdown 内容格式化工具

为文档、博客和静态站点生成器整理、验证和格式化长篇 Markdown 内容。自动生成目录、添加 frontmatter、验证结构,并在不同 Markdown 方言之间转换。

工作流

Markdown 格式化流程包含以下步骤:

  1. 加载 - 读取 Markdown 文件或内容
  2. 验证 - 检查标题层级、失效链接和结构问题
  3. 格式化 - 应用格式规则(空格、代码块等)
  4. 生成 - 添加目录、frontmatter 和交叉引用
  5. 导出 - 以目标 Markdown 方言保存

快速开始

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'
)

格式化操作

1. 生成目录

根据文档标题结构自动生成目录:

  • 可自定义深度(H2、H3 等)
  • GitHub 风格的锚点链接
  • 编号或项目符号格式
  • 根据标题层级智能缩进
2. Frontmatter 管理

为静态站点生成器添加 YAML/TOML/JSON frontmatter:

  • 用于 Jekyll/Hugo 的 YAML(---)
  • 用于 Hugo 的 TOML(+++)
  • 用于自定义解析器的 JSON
  • 结构化元数据(标题、作者、日期、标签等)
3. 结构验证

检查文档结构中的常见问题:

  • 标题层级 - 检测跳级(H2 → H4)
  • 失效链接 - 查找无效的内部(#锚点)和外部链接
  • 重复标题 - 检查标题 ID 冲突
  • 缺少元素 - 检查必需章节是否缺失
4. 代码块格式化

为代码块添加语法高亮标记:

  • 为围栏代码块添加语言标签
  • 将缩进代码转换为围栏代码块
  • 指定默认语言
  • 统一格式
5. 交叉引用链接

自动链接标题并创建交叉引用:

  • 生成唯一的标题 ID
  • 链接对章节的提及(例如“参见简介”)
  • 为内部导航创建锚点链接
  • 处理重复的标题名称
6. 空格与一致性

应用统一的格式规则:

  • 标题周围的换行
  • 列表格式(项目符号、编号)
  • 代码块间距
  • 段落换行
  • 水平分隔线
7. 方言转换

在不同 Markdown 方言之间转换:

  • GitHub Flavored Markdown - 任务列表、表格、语法高亮
  • CommonMark - 标准规范
  • Jekyll - Liquid 模板、包含文件
  • Hugo - 短代码、分类法

验证检查

验证器可识别以下常见问题:

问题类型描述示例
标题跳级层级跳跃(H2 → H4)H2 和 H4 之间缺少 H3
失效链接无效的内部/外部链接[link](#missing-section)
重复标题同一标题出现多次两个“简介”标题
缺少 ID标题没有唯一标识符锚点链接失效
结构无效嵌套或格式错误标题内包含列表

API 参考

MarkdownFormatter

初始化:

formatter = MarkdownFormatter(
    file_path='document.md',  # OR
    content='# Markdown text...'
)

参数:

  • file_path (str):Markdown 文件的路径(可选)
  • content (str):直接提供的 Markdown 内容(可选)

必须提供 file_path 或 content 其中之一。

目录
generate_toc()
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'
)

返回值:目录 Markdown 字符串

样式:

  • github - 带锚点链接的项目符号列表
  • numbered - 编号大纲
  • bullets - 简单项目符号列表

输出示例(github 样式):

## Table of Contents

- [Introduction](#introduction)
- [Getting Started](#getting-started)
  - [Installation](#installation)
  - [Configuration](#configuration)
- [Advanced Topics](#advanced-topics)
Frontmatter
add_frontmatter()
content = formatter.add_frontmatter(
    metadata={
        'title': 'Document Title',
        'author': 'John Doe',
        'date': '2024-01-15',
        'tags': ['markdown', 'documentation']
    },
    format='yaml'  # 'yaml', 'toml', or 'json'
)

返回值:前置了 frontmatter 的 Markdown 内容

输出示例(YAML):

---
title: Document Title
author: John Doe
date: 2024-01-15
tags:
  - markdown
  - documentation
---
验证
validate_structure()
result = formatter.validate_structure()

返回值:包含验证结果的字典

{
    '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'
        }
    ]
}
代码块
format_code_blocks()
content = formatter.format_code_blocks(
    add_language_tags=True,
    default_language='text'
)

返回值:格式化后的 Markdown 代码块

转换为:

    code here

结果:

```text
code here
```
交叉引用
auto_link_headings()
content = formatter.auto_link_headings()

返回:带标题 ID 和交叉引用链接的 Markdown

生成 GitHub 风格的锚点:

  • # Getting Started → <a id="getting-started"></a>
  • “see Getting Started” 链接 → [Getting Started](#getting-started)
间距
fix_spacing()
content = formatter.fix_spacing()

返回:间距统一的 Markdown

应用以下规则:

  • H1 前空 2 行
  • H2-H6 前空 1 行
  • 代码块前后各空 1 行
  • 列表前后各空 1 行
风格转换
convert_to_flavor()
content = formatter.convert_to_flavor(target='jekyll')

参数:

  • target (str):'github'、'commonmark'、'jekyll' 或 'hugo'

返回:转换后的 Markdown 字符串

导出
export()
formatter.export(
    output_path='formatted.md',
    include_toc=True,
    include_frontmatter=True,
    target_flavor='github'
)

参数:

  • output_path (str):输出文件路径
  • include_toc (bool):在开头添加目录
  • include_frontmatter (bool):保留或添加 frontmatter
  • target_flavor (str):目标 Markdown 风格

CLI 用法

生成目录
python scripts/markdown_formatter.py \
    --input document.md \
    --toc \
    --toc-depth 3 \
    --toc-style github \
    --output formatted.md
添加 Frontmatter
# 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

输出:

{
  "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
CLI 参数
参数描述默认值
--input, -i输入 Markdown 文件必填
--output, -o输出文件路径stdout
--toc生成目录False
--toc-depth目录最大深度(1-6)3
--toc-style目录样式(github/numbered/bullets)github
--frontmatterfrontmatter 的键值对-
--frontmatter-file包含 frontmatter 的 YAML 文件-
--auto-link自动链接标题False
--fix-spacing修复间距和格式False
--flavor目标 Markdown 风格github
--validate仅验证结构False
--format验证结果的输出格式(json/text)text

示例

示例 1:自动生成目录
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)
示例 2:添加 Jekyll Frontmatter
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')
示例 3:验证文档结构
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!")
示例 4:修复常见问题
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')
示例 5:转换为 Hugo 静态网站格式
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'
)
示例 6:批量验证
# 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

安装依赖项:

pip install -r scripts/requirements.txt

限制

  • 链接验证:检查外部链接需要发送网络请求(默认不执行)
  • Markdown 解析:使用 Python-Markdown 库;某些边缘情况可能与其他解析器有所不同
  • 风格差异:并非所有特定于风格的功能都会转换(例如 Hugo 短代码)
  • 标题锚点:锚点生成遵循 GitHub 算法,但可能与其他平台不同
  • 代码语言检测:自动语言检测能力有限;建议手动添加标签
  • 大文件:超大文件(>10MB)处理可能较慢
  • Unicode:标题锚点中的某些 Unicode 字符可能导致问题
  • 嵌套列表:复杂的嵌套列表结构可能无法完美格式化
  • Markdown 中的 HTML:保留原始 HTML 块,但不进行验证
  • 数学公式:不会解析或验证 LaTeX 数学公式

Markdown 风格说明

GitHub Flavored Markdown (GFM)
  • 任务列表:- [ ] Task / - [x] Done
  • 支持对齐方式的表格
  • 删除线:~~text~~
  • 自动检测链接
CommonMark
  • 严格遵循规范
  • 无扩展(不支持任务列表和表格)
  • 解析结果可预测
Jekyll
  • Liquid 模板:{{ variable }}
  • 包含文件:{% include file.html %}
  • 必须提供 Frontmatter
Hugo
  • 短代码:{{< shortcode >}}
  • 首选 TOML frontmatter
  • 分类法(标签、类别)
  • 嵌套分区

评论

支持 Markdown