【お知らせ】お得な情報はこちら

mermaid関連 – HTMLにMermaidノードのリンク強調・詳細表示機能を追加する等

1.Markdown Preview Enhanced のHTMLにMermaidノードのリンク強調・詳細表示機能を追加する

2.Markdown Preview Enhanced などのHTMLに、右側固定の目次(TOC)サイドバー機能を追加する。

task.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Inject Mermaid Highlighter",
            "type": "shell",
            "command": "py",
            "args": [
                "${workspaceFolder}/.vscode/scripts/inject_mermaid_flowchart_highlighter/inject_mermaid_flowchart_highlighter.py",
                "${fileDirname}/${fileBasenameNoExtension}.html",
                "${fileDirname}/${fileBasenameNoExtension}-output.html"
            ],
            "problemMatcher": []
        },
        {
            "label": "Inject Html Heading",
            "type": "shell",
            "command": "py",
            "args": [
                "${workspaceFolder}/.vscode/scripts/inject_html_Heading/inject_html_Heading.py",
                "${fileDirname}/${fileBasenameNoExtension}.html",
                "${fileDirname}/${fileBasenameNoExtension}-output.html"
            ],
            "problemMatcher": []
        }
    ]
}

markdown側

---
# MPEのHTML書き出し設定です。
# offline: true は外部CDNに依存しないHTMLを生成します。
html:
  offline: true
# このMarkdownファイルの保存時にHTMLを書き出します。
export_on_save:
  html: true
---

# 1. 見出し1

見出し1

# 2. 見出し1

見出し1

## 2.1 見出し2

見出し2

 ```mermaid
flowchart LR;

    subgraph Input_Type1
        i1[in1]
        i2[in2]
    end

    subgraph Input_Type2
        i3[in3]
        style i3 fill:#ccc,stroke:#f00,stroke-width:2px,stroke-dasharray:3
    end

    subgraph Task
        t1[main]
    end
    
    subgraph Output_Normal
        o1[out1]
    end

    subgraph Output_Error
        o2[out2]
        o3[out3]
    end

i1 --> t1
t1 --> |OK| o1
t1 --> |NG| o2
i2 -.-> t1
i3 --> t1
t1 --> |NG| o3
linkStyle 4 stroke:#f00,stroke-width:2px

classDef pink fill:#ffb6c1
class i1,t1 pink
 ```

 ## 2.2 見出し2

見出し2

### 2.2.1 見出し3

見出し3

### 2.2.1.1 見出し4

見出し4

### 2.2.1.1.1 見出し5

見出し5

### 2.2.1.1.1.1 見出し6

見出し6

Markdown Preview Enhanced のHTMLにMermaidノードのリンク強調・詳細表示機能を追加する

.vscode\scripts\inject_mermaid_flowchart_highlighter\inject_mermaid_flowchart_highlighter.py

"""Markdown Preview Enhanced のHTMLにMermaidノードのリンク強調・詳細表示機能を追加する。

前提条件:
    * Python 3 がインストールされ、Windowsでは ``py`` または ``python`` コマンドで
      実行できること。
    * Markdown Preview EnhancedでMermaid図を含むMarkdownをHTMLに変換済みであること。
    * 入力HTMLにMermaid図が含まれていること。図がないHTMLも変換できますが、
      ノードのクリック強調機能は動作しません。
    * Python標準ライブラリのみを使用するため、追加パッケージのインストールは不要。

使い方(docs\\works フォルダーで実行する場合):
    py inject_mermaid_highlighter.py mermaid-in-markdown-01.html mermaid-in-markdown-01-output.html

任意の場所から実行する場合は、スクリプト・入力・出力にそれぞれパスを指定してください。
出力先に同名ファイルがすでにある場合、そのファイルは上書きされます。
入力ファイルと出力ファイルには別のパスを指定してください。

強調対象となるMermaid構文:
    * 対象は ``flowchart``(旧形式の ``graph`` を含む)図です。
    * ``A[開始]``、``B(処理)``、``C{判定}`` などのノードをクリックすると、
      そのノードを始点または終点とする接続リンクを強調し、図の下に
      グループ階層・ノードIDと名前・入力リンク・出力リンクを表示します。
      ノード形状は問いません。
    * ``A --> B``、``A -.-> B``、``A ==> B``、``A -->|OK| B`` のような
      矢印・線種・ラベル付きリンクが対象です。subgraph内のノードも個別に対象になります。
    * subgraphの枠や見出し自体はノードではないため、クリックしても強調対象になりません。
      ``class``、``classDef``、``style``、``linkStyle`` で設定した既存の装飾は残りますが、
      選択中のノードや接続リンクの線色・線幅はハイライト表示が優先されます。
    * ``sequenceDiagram``、``classDiagram``、``stateDiagram`` など、
      ``flowchart``以外の図種別は対象外です。

詳しい引数情報:
    py inject_mermaid_highlighter.py --help
"""

import argparse
from pathlib import Path

def inject_mermaid_highlighter(input_html_path, output_html_path):
    # 1. HTMLファイルをロードする
    with open(input_html_path, 'r', encoding='utf-8') as f:
        html_content = f.read()

    # 2. 付与するカスタムCSSとJavaScript
    # MermaidのSVG構造(g.node, g.edgePath)を操作して、接続線をハイライトします
    custom_injection = """
    <style>
        /* ハイライト用のCSSクラス */
        .mermaid svg .node.highlighted rect,
        .mermaid svg .node.highlighted circle,
        .mermaid svg .node.highlighted polygon,
        .mermaid svg .node.highlighted path {
            stroke: #ff3366 !important;
            stroke-width: 3px !important;
        }
        .mermaid svg .edgePath.highlighted path,
        .mermaid svg .flowchart-link.highlighted {
            stroke: #ff3366 !important;
            stroke-width: 3px !important;
        }
        /* 非選択時のフェード(オプション) */
        .mermaid.is-active svg .node:not(.highlighted):not(.selected),
        .mermaid.is-active svg .edgePath:not(.highlighted),
        .mermaid.is-active svg .flowchart-link:not(.highlighted) {
            opacity: 0.3;
        }
    </style>

    <script>
    // Mermaid renders over the source text, so retain each definition before its module script runs.
    const mermaidDefinitions = new Map(
        Array.from(document.querySelectorAll(".mermaid"), container => [container, container.textContent])
    );

    document.addEventListener("DOMContentLoaded", () => {
        // Mermaidの描画が完了するのを少し待つか、監視する
        setTimeout(initMermaidHighlighter, 1000);
    });

    function initMermaidHighlighter() {
        const containers = document.querySelectorAll(".mermaid");
        
        containers.forEach(container => {
            const svg = container.querySelector("svg");
            if (!svg) return;

            const nodes = svg.querySelectorAll(".node");
            const edges = svg.querySelectorAll(".edgePath, .flowchart-link");
            const details = createNodeDetails(container);
            const definition = parseFlowchartDefinition(mermaidDefinitions.get(container) || "");

            nodes.forEach(node => {
                node.style.cursor = "pointer";
                node.addEventListener("click", (e) => {
                    e.stopPropagation();
                    
                    const isAlreadySelected = node.classList.contains("selected");
                    
                    // リセット
                    nodes.forEach(n => n.classList.remove("selected", "highlighted"));
                    edges.forEach(ed => ed.classList.remove("highlighted"));
                    container.classList.remove("is-active");

                    if (!isAlreadySelected) {
                        node.classList.add("selected");
                        container.classList.add("is-active");

                        edges.forEach(edge => {
                            if (checkEdgeConnection(node, edge, nodes)) {
                                edge.classList.add("highlighted");
                            }
                        });
                        updateNodeDetails(details, node, definition);
                    } else {
                        details.hidden = true;
                    }
                });
            });

            // 背景クリックで選択解除
            svg.addEventListener("click", () => {
                nodes.forEach(n => n.classList.remove("selected", "highlighted"));
                edges.forEach(ed => ed.classList.remove("highlighted"));
                container.classList.remove("is-active");
                details.hidden = true;
            });
        });
    }

    function createNodeDetails(container) {
        const panel = document.createElement("section");
        panel.className = "mermaid-node-details";
        panel.hidden = true;
        panel.setAttribute("aria-live", "polite");
        panel.style.cssText = "margin: 1em 0; padding: 1em; border: 1px solid #ccc; border-radius: 4px;";
        panel.innerHTML = `
            <h3>選択ノードの詳細</h3>
            <h4>グループ</h4><pre data-detail="group"></pre>
            <h4>ノード</h4><pre data-detail="node"></pre>
            <h4>入力</h4><pre data-detail="inputs"></pre>
            <h4>出力</h4><pre data-detail="outputs"></pre>
        `;
        container.insertAdjacentElement("afterend", panel);
        return panel;
    }

    function parseFlowchartDefinition(source) {
        const groups = [];
        const nodeGroups = new Map();
        const nodeLabels = new Map();
        const links = [];
        const nodePattern = /^\\s*([A-Za-z][\\w-]*)\\s*(?:\\[([^\\]]*)\\]|\\(([^)]*)\\)|\\{([^}]*)\\})?\\s*;?\\s*$/;
        const edgePattern = /([A-Za-z][\\w-]*)(?:\\s*(\\[[^\\]]*\\]|\\([^)]*\\)|\\{[^}]*\\}))?\\s*(-->|-\\.->|==>)\\s*(?:\\|([^|]*)\\|\\s*)?([A-Za-z][\\w-]*)(?:\\s*(\\[[^\\]]*\\]|\\([^)]*\\)|\\{[^}]*\\}))?/g;

        for (const rawLine of source.split(/\\r?\\n/)) {
            const line = rawLine.trim();
            if (!line || line.startsWith("%%")) continue;

            const subgraphMatch = line.match(/^subgraph\\s+(.+?)\\s*;?$/i);
            if (subgraphMatch) {
                groups.push(subgraphMatch[1].trim());
                continue;
            }
            if (/^end\\s*;?$/i.test(line)) {
                groups.pop();
                continue;
            }
            if (/^(flowchart|graph)\\b/i.test(line)
                || /^(style|classDef|class|linkStyle|click|direction)\\b/i.test(line)) {
                continue;
            }

            edgePattern.lastIndex = 0;
            let edgeMatch;
            let foundEdge = false;
            while ((edgeMatch = edgePattern.exec(line)) !== null) {
                foundEdge = true;
                const [, from, fromShape, arrow, label, to, toShape] = edgeMatch;
                if (fromShape) nodeLabels.set(from, getNodeLabel(fromShape));
                if (toShape) nodeLabels.set(to, getNodeLabel(toShape));
                if (groups.length) {
                    if (!nodeGroups.has(from)) nodeGroups.set(from, [...groups]);
                    if (!nodeGroups.has(to)) nodeGroups.set(to, [...groups]);
                }
                links.push({ from, to, arrow, label });
            }
            if (foundEdge) continue;

            const nodeMatch = line.match(nodePattern);
            if (nodeMatch) {
                const [, id, squareLabel, roundLabel, diamondLabel] = nodeMatch;
                const label = squareLabel ?? roundLabel ?? diamondLabel;
                if (label !== undefined) nodeLabels.set(id, label);
                if (groups.length && !nodeGroups.has(id)) nodeGroups.set(id, [...groups]);
            }
        }

        return { groups: nodeGroups, labels: nodeLabels, links };
    }

    function getNodeLabel(shape) {
        return shape.slice(1, -1);
    }

    function updateNodeDetails(panel, node, definition) {
        const nodeId = getMermaidNodeId(node);
        const nodeLabel = definition.labels.get(nodeId) || node.textContent.trim();
        const formatNode = id => `${id}[${definition.labels.get(id) || id}]`;
        const inputs = definition.links
            .filter(link => link.to === nodeId)
            .map(link => `${formatNode(link.from)} ${link.arrow}${link.label !== undefined ? ` |${link.label}|` : ""} ${formatNode(link.to)}`);
        const outputs = definition.links
            .filter(link => link.from === nodeId)
            .map(link => `${formatNode(link.from)} ${link.arrow}${link.label !== undefined ? ` |${link.label}|` : ""} ${formatNode(link.to)}`);
        const groupPath = definition.groups.get(nodeId);

        panel.querySelector('[data-detail="group"]').textContent = groupPath ? `/${groupPath.join("/")}` : "(なし)";
        panel.querySelector('[data-detail="node"]').textContent = `${nodeId}[${nodeLabel}]`;
        panel.querySelector('[data-detail="inputs"]').textContent = inputs.join("\\n") || "(なし)";
        panel.querySelector('[data-detail="outputs"]').textContent = outputs.join("\\n") || "(なし)";
        panel.hidden = false;
    }

    function checkEdgeConnection(node, edge, nodes) {
        const nodeId = getMermaidNodeId(node);
        const edgeClasses = edge.classList;
        if (edgeClasses.contains(`LS-${nodeId}`) || edgeClasses.contains(`LE-${nodeId}`)) {
            return true;
        }

        const edgeId = edge.getAttribute("data-id") || edge.id;
        const edgeKey = edgeId.match(/(?:^|-)L_(.*)$/)?.[1];
        if (!edgeKey) return false;

        const nodeIds = Array.from(nodes, getMermaidNodeId);
        return nodeIds.some(sourceId => nodeIds.some(targetId => {
            const edgePrefix = `${sourceId}_${targetId}_`;
            return (sourceId === nodeId || targetId === nodeId)
                && edgeKey.startsWith(edgePrefix)
                && /^[0-9]+$/.test(edgeKey.slice(edgePrefix.length));
        }));
    }

    function getMermaidNodeId(node) {
        const match = node.id.match(/(?:^|-)flowchart-(.+)-[0-9]+$/);
        return match ? match[1] : node.id;
    }
    </script>
    """

    # </body>タグの直前にインジェクションを挿入する
    body_close_index = html_content.rfind("</body>")
    if body_close_index != -1:
        new_html = (
            html_content[:body_close_index]
            + custom_injection
            + "\n"
            + html_content[body_close_index:]
        )
    else:
        new_html = html_content + custom_injection

    # 3. 出力ファイルとして保存
    with open(output_html_path, 'w', encoding='utf-8') as f:
        f.write(new_html)
    
    print(f"Successfully generated: {output_html_path}")

def main():
    parser = argparse.ArgumentParser(
        description="変換済みHTMLにMermaidノードのリンク強調と選択ノードの詳細表示を追加します。",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=(
            "例:\n"
            "  py inject_mermaid_highlighter.py mermaid-in-markdown-01.html "
            "mermaid-in-markdown-01-output.html\n"
            "\n"
            "強調対象:\n"
            "  * flowchart(旧形式graphを含む)のノードと接続リンク\n"
            "  * 四角・丸・ひし形など形状を問わないノード。subgraph内のノードも対象\n"
            "  * 矢印・点線・太線・ラベル付きリンク(例: A --> B, A -.-> B,\n"
            "    A ==> B, A -->|OK| B)\n"
            "\n"
            "subgraphの枠・見出しや、sequenceDiagram/classDiagram/stateDiagramなど\n"
            "flowchart以外の図は対象外です。既存のclass/style/linkStyleは残りますが、\n"
            "選択中のノードとリンクはハイライト色・線幅が優先されます。"
        ),
    )
    parser.add_argument(
        "input_html_path",
        help="Markdown Preview Enhancedで変換した入力HTMLファイル",
    )
    parser.add_argument(
        "output_html_path",
        help="ハイライト機能を追加して保存する出力HTMLファイル(既存の場合は上書き)",
    )
    args = parser.parse_args()

    input_path = Path(args.input_html_path)
    output_path = Path(args.output_html_path)

    if not input_path.is_file():
        parser.error(f"入力ファイルが見つからないか、ファイルではありません: {input_path}")
    if input_path.resolve() == output_path.resolve():
        parser.error("入力ファイルと出力ファイルには別のパスを指定してください。")
    if not output_path.parent.is_dir():
        parser.error(f"出力先フォルダーが見つかりません: {output_path.parent}")

    inject_mermaid_highlighter(input_path, output_path)


if __name__ == "__main__":
    main()

Markdown Preview Enhanced などのHTMLに、右側固定の目次(TOC)サイドバー機能を追加する

.vscode\scripts\inject_html_Heading\inject_html_Heading.py

"""Markdown Preview Enhanced などのHTMLに、右側固定の目次(TOC)サイドバー機能を追加する。

前提条件:
    * Python 3 がインストールされ、Windowsでは ``py`` または ``python`` コマンドで
      実行できること。
    * Markdown Preview EnhancedなどでHTMLに変換済みであること。
    * 入力HTMLに見出し(h1〜h6)が含まれていること。
    * Python標準ライブラリのみを使用するため、追加パッケージのインストールは不要。

使い方(スクリプトのあるフォルダーまたは任意の場所で実行する場合):
    py inject_html_Heading.py mermaid-in-markdown-01.html mermaid-in-markdown-01-output.html

任意の場所から実行する場合は、スクリプト・入力・出力にそれぞれパスを指定してください。
出力先に同名ファイルがすでにある場合、そのファイルは上書きされます。
入力ファイルと出力ファイルには別のパスを指定してください。

付与される機能:
    * **目次(TOC)サイドバー**:
      * 画面の右側に、Markdown内の見出し(h1〜h6)を自動収集した入れ子構造の目次を固定表示します。
      * プレビュー本文と目次を縦線で分け、狭い画面では目次を本文の下に配置します。
      * 見出しをクリックすると、該当箇所へスムーズにスクロールします。

詳しい引数情報:
    py inject_html_Heading.py --help
"""

import argparse
from pathlib import Path

def inject_html_heading(input_html_path, output_html_path):
    # 1. HTMLファイルをロードする
    with open(input_html_path, 'r', encoding='utf-8') as f:
        html_content = f.read()

    # 2. 付与するカスタムCSSとJavaScript(目次TOC生成)
    custom_injection = """
    <style>
        /* ==========================================
           目次サイドバーのスタイル
           ========================================== */
        body {
            display: grid;
            grid-template-columns: minmax(0, 1fr) var(--mermaid-toc-width, 200px);
            align-items: start;
        }

        .crossnote.markdown-preview {
            grid-column: 1;
            width: auto !important;
            min-width: 0;
        }

        @media (max-width: 700px) {
            body {
                grid-template-columns: minmax(0, 1fr);
            }
            .crossnote.markdown-preview {
                grid-column: 1;
            }
            .mermaid-toc-sidebar {
                position: static !important;
                grid-column: 1 !important;
                width: auto !important;
                height: auto !important;
                max-height: 40vh;
                border-left: 0 !important;
                border-bottom: 1px solid #e1e4e8;
            }
            .mermaid-toc-resizer {
                display: none !important;
            }
        }

        .mermaid-toc-sidebar {
            position: sticky;
            top: 0;
            grid-column: 2;
            align-self: start;
            box-sizing: border-box;
            width: 100%;
            height: 100vh;
            max-height: 100vh;
            overflow-y: auto;
            background: #ffffff;
            border-left: 1px solid #e1e4e8;
            padding: 20px 12px;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            font-size: 13px;
            z-index: 1000;
        }

        .mermaid-toc-resizer {
            position: fixed;
            top: 0;
            bottom: 0;
            left: calc(100% - var(--mermaid-toc-width, 200px) - 4px);
            width: 8px;
            cursor: col-resize;
            touch-action: none;
            z-index: 1001;
        }

        .mermaid-toc-resizer::after {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 3px;
            width: 1px;
            background: #e1e4e8;
            content: "";
        }

        .mermaid-toc-resizer:hover::after,
        body.mermaid-toc-resizing .mermaid-toc-resizer::after {
            width: 3px;
            left: 2px;
            background: #0366d6;
        }

        body.mermaid-toc-resizing {
            cursor: col-resize;
            user-select: none;
        }

        .mermaid-toc-sidebar .toc-title {
            font-weight: bold;
            font-size: 14px;
            margin-bottom: 10px;
            padding-bottom: 6px;
            border-bottom: 1px solid #eaecef;
            color: #24292e;
        }

        .mermaid-toc-sidebar ul {
            list-style-type: none;
            padding-left: 16px;
            margin: 4px 0;
        }

        .mermaid-toc-sidebar > ul {
            padding-left: 0;
        }

        .mermaid-toc-sidebar li {
            margin: 4px 0;
        }

        .mermaid-toc-sidebar a {
            color: #0366d6;
            text-decoration: none;
            display: block;
            padding: 2px 4px;
            border-radius: 4px;
            transition: background 0.2s;
        }

        .mermaid-toc-sidebar a:hover {
            background: #f1f8ff;
            text-decoration: underline;
        }
    </style>

    <script>
    // ==========================================
    // 目次(TOC)を動的生成する処理
    // ==========================================
    document.addEventListener("DOMContentLoaded", () => {
        generateTableOfContents();
    });

    function generateTableOfContents() {
        const headings = document.querySelectorAll("h1, h2, h3, h4, h5, h6");
        if (headings.length === 0) return;

        const tocContainer = document.createElement("nav");
        tocContainer.className = "mermaid-toc-sidebar";

        const resizer = document.createElement("div");
        resizer.className = "mermaid-toc-resizer";
        resizer.setAttribute("role", "separator");
        resizer.setAttribute("aria-label", "目次幅を変更");
        resizer.setAttribute("aria-orientation", "vertical");
        resizer.setAttribute("tabindex", "0");
        document.body.appendChild(resizer);
        setupTocResizer(resizer);
        
        const title = document.createElement("div");
        title.className = "toc-title";
        title.textContent = "目次 (Table of Contents)";
        tocContainer.appendChild(title);

        const rootUl = document.createElement("ul");
        tocContainer.appendChild(rootUl);

        let stack = [{ level: 0, element: rootUl }];

        headings.forEach((heading, index) => {
            if (!heading.id) {
                heading.id = `heading-${index}`;
            }

            const level = parseInt(heading.tagName.substring(1));
            const text = heading.textContent;

            const li = document.createElement("li");
            const a = document.createElement("a");
            a.href = `#${heading.id}`;
            a.textContent = text;
            li.appendChild(a);

            while (stack.length > 0 && stack[stack.length - 1].level >= level) {
                stack.pop();
            }

            if (stack.length === 0) {
                rootUl.appendChild(li);
                stack.push({ level: level, element: rootUl });
            } else {
                let parentElement = stack[stack.length - 1].element;
                let lastLi = parentElement.lastElementChild;
                let subUl = null;

                if (lastLi && lastLi.tagName === 'LI') {
                    subUl = lastLi.querySelector('ul');
                    if (!subUl) {
                        subUl = document.createElement('ul');
                        lastLi.appendChild(subUl);
                    }
                }

                if (subUl) {
                    subUl.appendChild(li);
                    stack.push({ level: level, element: subUl });
                } else {
                    parentElement.appendChild(li);
                    stack.push({ level: level, element: parentElement });
                }
            }
        });

        document.body.appendChild(tocContainer);
    }

    function setupTocResizer(resizer) {
        const minimumWidth = 140;
        const maximumWidth = 480;
        const root = document.documentElement;
        let pointerId = null;

        function setTocWidth(width) {
            const clampedWidth = Math.max(
                minimumWidth,
                Math.min(maximumWidth, width, window.innerWidth - 240)
            );
            root.style.setProperty("--mermaid-toc-width", `${clampedWidth}px`);
            resizer.setAttribute("aria-valuenow", String(Math.round(clampedWidth)));
        }

        resizer.addEventListener("pointerdown", event => {
            if (event.button !== 0 || window.matchMedia("(max-width: 700px)").matches) return;
            pointerId = event.pointerId;
            resizer.setPointerCapture(pointerId);
            document.body.classList.add("mermaid-toc-resizing");
            event.preventDefault();
        });

        resizer.addEventListener("pointermove", event => {
            if (event.pointerId !== pointerId) return;
            setTocWidth(window.innerWidth - event.clientX);
        });

        function stopResizing(event) {
            if (event.pointerId !== pointerId) return;
            pointerId = null;
            document.body.classList.remove("mermaid-toc-resizing");
        }

        resizer.addEventListener("pointerup", stopResizing);
        resizer.addEventListener("pointercancel", stopResizing);

        resizer.addEventListener("keydown", event => {
            if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
            const currentWidth = parseFloat(
                getComputedStyle(root).getPropertyValue("--mermaid-toc-width")
            ) || 200;
            setTocWidth(currentWidth + (event.key === "ArrowLeft" ? 16 : -16));
            event.preventDefault();
        });

        resizer.setAttribute("aria-valuemin", String(minimumWidth));
        resizer.setAttribute("aria-valuemax", String(maximumWidth));
        resizer.setAttribute("aria-valuenow", "200");
    }
    </script>
    """

    # 3. </body>タグの直前にインジェクションを挿入する
    body_close_index = html_content.rfind("</body>")
    if body_close_index != -1:
        new_html = (
            html_content[:body_close_index]
            + custom_injection
            + "\n"
            + html_content[body_close_index:]
        )
    else:
        new_html = html_content + custom_injection

    # 4. 出力ファイルとして保存
    with open(output_html_path, 'w', encoding='utf-8') as f:
        f.write(new_html)
    
    print(f"Successfully generated: {output_html_path}")

def main():
    parser = argparse.ArgumentParser(
        description="変換済みHTMLに見出しの目次(TOC)サイドバーを追加します。",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=(
            "例:\n"
            "  py inject_html_Heading.py mermaid-in-markdown-01.html "
            "mermaid-in-markdown-01-output.html\n"
            "\n"
            "付与される機能:\n"
            "  * 右側固定の目次(TOC)サイドバー(h1〜h6の見出しツリー構造化)\n"
        ),
    )
    parser.add_argument(
        "input_html_path",
        help="変換した入力HTMLファイル",
    )
    parser.add_argument(
        "output_html_path",
        help="目次機能を追加して保存する出力HTMLファイル(既存の場合は上書き)",
    )
    args = parser.parse_args()

    input_path = Path(args.input_html_path)
    output_path = Path(args.output_html_path)

    if not input_path.is_file():
        parser.error(f"入力ファイルが見つからないか、ファイルではありません: {input_path}")
    if input_path.resolve() == output_path.resolve():
        parser.error("入力ファイルと出力ファイルには別のパスを指定してください。")
    if not output_path.parent.is_dir():
        parser.error(f"出力先フォルダーが見つかりません: {output_path.parent}")

    inject_html_heading(input_path, output_path)


if __name__ == "__main__":
    main()
タイトルとURLをコピーしました