Fix Mermaid diagram syntax errors in Obsidian markdown files
This skill fixes Mermaid diagram syntax errors in markdown files. It includes comprehensive fixing logic for 20+ common Mermaid syntax issues including unquoted labels, malformed arrows, nested brackets, and more.
refineMermaidBlocks (mermaidProcessor.ts)
├── split content by lines
├── detect ```mermaid blocks
├── apply fix rules in order:
│ ├── fixSmartQuotes
│ ├── fixMermaidPipes
│ ├── fixMermaidNotes
│ ├── fixNotesToNodes
│ ├── fixMalformedArrows
│ ├── fixInvalidArrows
│ ├── mergeDoubleLabels
│ ├── fixMissingBrackets
│ ├── fixInlineSubgraphs
│ ├── fixMermaidComments
│ ├── fixDoubleSlashComments
│ ├── fixUnquotedNodeLabels
│ ├── fixIntermediateNodes
│ ├── fixDoubledID
│ ├── fixExcessiveBrackets
│ ├── fixSemicolonPositioning
│ ├── fixConcatenatedLabels
│ ├── fixUnquotedLabelsWithSemicolons
│ ├── enhancedNoteAndSemicolonCleanup
│ ├── fixReverseArrows
│ ├── fixSubgraphDirection
│ ├── fixDuplicateLabels
│ ├── fixNestedMermaidQuotes
│ ├── fixQuotedLabelsAfterSemicolon
│ ├── fixDoubleDashToArrow
│ ├── fixTargetedNotes
│ ├── fixDoubleArrowLabels
│ ├── fixUnquotedEdgeLabels
│ ├── fixShapeMismatch
│ ├── fixPlaceholderArtifacts
│ └── fixBlankArrows
├── close unclosed blocks
└── checkMermaidErrors (if errors found, apply deepDebugMermaid)
cleanupLatexDelimiters (mermaidProcessor.ts)
├── protect escaped dollars
├── convert \( \) to $
├── trim whitespace in math
└── restore escaped dollars
The full TypeScript code is available in: mermaidProcessor.ts
This file contains all the fix functions:
refineMermaidBlocks() - Main entry pointcheckMermaidErrors() - Validate syntaxcleanupLatexDelimiters() - Fix LaTeXdeepDebugMermaid() - Apply all fix passesAfter LLM generates content, these functions are automatically called:
cleanupLatexDelimiters(content)refineMermaidBlocks(content)fixMermaidSyntaxInFile(app, file, reporter) - Validates and reports errorsCall refineMermaidBlocks(content) on any markdown content to fix Mermaid syntax.
Input: Investment[Corporate Investment "[企业投资]"]
Output: Investment["Corporate Investment [企业投资]"]
Input: CapRate --["Inverse Relationship["--> PropValue
Output: CapRate -- "Inverse Relationship" --> PropValue
Input: A --|> B
Output: A --> B
Input: A --> B; % Comment
Output: A -- "Comment" --> B;
Input: note right of A: Text
Output: A -- "Text" --> (as label)
Input: A["Text"]]]
Output: A["Text"]
import {
refineMermaidBlocks,
cleanupLatexDelimiters,
} from "./mermaidProcessor";
// Fix Mermaid in content
const content = `...
\`\`\`mermaid
graph LR
A[Node --> B]
\`\`\`
...`;
const fixed = await refineMermaidBlocks(content);
const cleaned = cleanupLatexDelimiters(fixed);
The checkMermaidErrors() function uses mermaid.parse() to validate syntax:
const errorCount = await checkMermaidErrors(content);
// Returns: number of errors found
If errors remain after basic fixes, deepDebugMermaid() is applied.
[!IMPORTANT] Proven Regex Supremacy Based on empirical field testing, the AI Agent must prioritize the 37 manual heuristic regex fixers (like
fixMissingBrackets,fixReverseArrows) over directly asking the LLM to fix the diagram. Current Large Reasoning Models often struggle to repair structural Mermaid hallucinations directly. The regex pipeline has been proven to be the most robust method for correcting diagram flows in production.
LLM-Heal-Mermaid
├── Extract mermaid blocks from content
├── Try mermaid.parse() to validate
├── IF errors found
│ ├── Extract specific error messages
│ ├── Feed errors back to LLM with prompt
│ └── Ask for precise correction
├── Replace original block with LLM-fixed version
└── Validate again
import mermaid from "mermaid";
async function llmHealMermaid(
content: string,
llmCall: Function,
): Promise<string> {
// Extract mermaid blocks
const blockRegex = /```mermaid\n([\s\S]*?)```/g;
let fixedContent = content;
let match;
while ((match = blockRegex.exec(content)) !== null) {
const block = match[1];
// Try to parse
try {
await mermaid.parse(block);
} catch (error) {
// Get specific error
const errorMsg = error.message;
console.log(`Mermaid error: ${errorMsg}`);
// Ask LLM to fix
const fixPrompt = `Fix the following Mermaid diagram syntax.
Error: ${errorMsg}
Diagram:
${block}
Rules:
1. Use proper bracket syntax: nodeId["Label"]
2. Use proper arrow syntax: -->
3. Quote labels with special characters
4. Close all blocks properly
Fixed diagram:`;
const fixed = await llmCall(fixPrompt);
// Replace in content
fixedContent = fixedContent.replace(block, fixed);
}
}
return fixedContent;
}
Fix the following Mermaid diagram syntax error.
Error message from Mermaid parser:
{ERROR_MESSAGE}
Current broken diagram:
{BROKEN_DIAGRAM}
Please fix the syntax and return only the corrected Mermaid code.
Do not include any explanations or markdown code blocks.
Recommended: Always execute the complete battery of regex fixers first. Only escalate to the LLM if mermaid.parse() still fails after the regex cascade.
async function healMermaid(
content: string,
llmCall: Function,
): Promise<string> {
// Stage 1: Exhaustive Regex Heuristics (Primary Engine)
let fixed = refineMermaidBlocks(content);
// Stage 2: Strict Validation
const errors = await checkMermaidErrors(fixed);
// Stage 3: LLM Fallback (Use only when heuristics fail)
if (errors > 0) {
console.log(
`Found ${errors} residual errors after regex cascade, falling back to LLM...`,
);
fixed = await llmHealMermaid(fixed, llmCall);
}
return fixed;
}
npx skills add Jacobinwwey/notemd-mermaid-fix下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer