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. 03YAML、TOML、JSONのfrontmatter追加
  4. 04コードブロックと空白の整形
  5. 05見出しリンクと相互参照の作成
  6. 06Markdown形式間の変換

活用シーン

  1. 01見出しやリンクの問題を確認
  2. 02静的サイトジェネレーター向けの記事を準備
  3. 03Markdownファイルを一括で整形
  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 コンテンツを整理、検証、整形します。目次の自動生成、フロントマターの追加、構造の検証、Markdown の各種形式間の変換を行います。

ワークフロー

Markdown の整形プロセスは、次の手順で進みます。

  1. 読み込み - Markdown ファイルまたはコンテンツを読み込みます
  2. 検証 - 見出しの階層、リンク切れ、構造上の問題を確認します
  3. 整形 - 整形ルール(空白、コードブロックなど)を適用します
  4. 生成 - 目次、フロントマター、相互参照を追加します
  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. フロントマターの管理

静的サイトジェネレーター向けに YAML/TOML/JSON のフロントマターを追加します。

  • 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)
見出しの重複同じ見出しが複数回出現する「序文」という見出しが2つある
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)
フロントマター
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'
)

戻り値:フロントマターを先頭に追加した 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):フロントマターを保持/追加するかどうか
  • target_flavor (str):変換先の Markdown フレーバー

CLI の使用方法

目次を生成する
python 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

出力:

{
  "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
--frontmatterフロントマター用のキーと値のペア-
--frontmatter-fileフロントマターを含む 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 のフロントマターを追加する
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 %}
  • フロントマターが必須
Hugo
  • ショートコード:{{< shortcode >}}
  • TOML フロントマターを推奨
  • タクソノミー(タグ、カテゴリー)
  • ネストされたセクション

コメント