diff --git a/skills/baoyu-format-markdown/SKILL.md b/skills/baoyu-format-markdown/SKILL.md new file mode 100644 index 0000000..90bf1cd --- /dev/null +++ b/skills/baoyu-format-markdown/SKILL.md @@ -0,0 +1,246 @@ +--- +name: baoyu-format-markdown +description: Formats plain text or markdown files with frontmatter, titles, summaries, headings, bold, lists, and code blocks. Use when user asks to "format markdown", "beautify article", "add formatting", or improve article layout. Outputs to {filename}-formatted.md. +--- + +# Markdown Formatter + +Transforms plain text or markdown files into well-structured markdown with proper frontmatter, formatting, and typography. + +## Script Directory + +Scripts in `scripts/` subdirectory. Replace `${SKILL_DIR}` with this SKILL.md's directory path. + +| Script | Purpose | +|--------|---------| +| `scripts/main.ts` | Main entry point with CLI options | +| `scripts/cjk-emphasis.ts` | Fix CJK emphasis/bold punctuation issues | +| `scripts/quotes.ts` | Replace ASCII quotes with fullwidth quotes | +| `scripts/autocorrect.ts` | Add CJK/English spacing via autocorrect | + +## Preferences (EXTEND.md) + +Use Bash to check EXTEND.md existence (priority order): + +```bash +# Check project-level first +test -f .baoyu-skills/baoyu-format-markdown/EXTEND.md && echo "project" + +# Then user-level (cross-platform: $HOME works on macOS/Linux/WSL) +test -f "$HOME/.baoyu-skills/baoyu-format-markdown/EXTEND.md" && echo "user" +``` + +┌──────────────────────────────────────────────────────────┬───────────────────┐ +│ Path │ Location │ +├──────────────────────────────────────────────────────────┼───────────────────┤ +│ .baoyu-skills/baoyu-format-markdown/EXTEND.md │ Project directory │ +├──────────────────────────────────────────────────────────┼───────────────────┤ +│ $HOME/.baoyu-skills/baoyu-format-markdown/EXTEND.md │ User home │ +└──────────────────────────────────────────────────────────┴───────────────────┘ + +┌───────────┬───────────────────────────────────────────────────────────────────────────┐ +│ Result │ Action │ +├───────────┼───────────────────────────────────────────────────────────────────────────┤ +│ Found │ Read, parse, apply settings │ +├───────────┼───────────────────────────────────────────────────────────────────────────┤ +│ Not found │ Use defaults │ +└───────────┴───────────────────────────────────────────────────────────────────────────┘ + +**EXTEND.md Supports**: Default formatting options | Summary length preferences + +## Usage + +Claude performs content analysis and formatting (Steps 1-6), then runs the script for typography fixes (Step 7). + +## Workflow + +### Step 1: Read Source File + +Read the user-specified markdown or plain text file. + +### Step 2: Analyze Content Structure + +Identify: +- Existing title (H1 `#`) +- Paragraph separations +- Keywords suitable for **bold** +- Parallel content convertible to lists +- Code snippets +- Quotations + +### Step 3: Check/Create Frontmatter + +Check for YAML frontmatter (`---` block). Create if missing. + +**Meta field handling:** + +| Field | Processing | +|-------|------------| +| `title` | See Step 4 | +| `slug` | Infer from file path (e.g., `posts/2026/01/10/vibe-coding/` → `vibe-coding`) or generate from title | +| `summary` | Generate engaging summary (100-150 characters) | +| `featureImage` | Check if `imgs/cover.png` exists in same directory; if so, use relative path | + +### Step 4: Title Handling + +**Logic:** +1. If frontmatter already has `title` → use it, no H1 in body +2. If first line is H1 → extract to frontmatter `title`, remove H1 from body +3. If neither exists → generate candidate titles + +**Title generation flow:** + +1. Generate 3 candidate titles based on content +2. Use `AskUserQuestion` tool: + +``` +Select a title: + +1. [Title A] (Recommended) +2. [Title B] +3. [Title C] +``` + +3. If no selection within a few seconds, use recommended (option 1) + +**Title principles:** +- Concise, max 20 characters +- Captures core message +- Engaging, sparks reading interest +- Accurate, avoids clickbait + +**Important:** Once title is in frontmatter, body should NOT have H1 (avoid duplication) + +### Step 5: Format Processing + +**Formatting rules:** + +| Element | Format | +|---------|--------| +| Titles | Use `#`, `##`, `###` hierarchy | +| Key points | Use `**bold**` | +| Parallel items | Convert to `-` unordered or `1.` ordered lists | +| Code/commands | Use `` `inline` `` or ` ```block``` ` | +| Quotes/sayings | Use `>` blockquote | +| Separators | Use `---` where appropriate | + +**Formatting principles:** +- Preserve original content and viewpoints +- Add formatting only, do not modify text +- Formatting serves readability +- Avoid over-formatting + +### Step 6: Save Formatted File + +Save as `{original-filename}-formatted.md` + +Examples: +- `final.md` → `final-formatted.md` +- `draft-v1.md` → `draft-v1-formatted.md` + +**Backup existing file:** + +If `{filename}-formatted.md` already exists, backup before overwriting: + +```bash +# Check if formatted file exists +if [ -f "{filename}-formatted.md" ]; then + # Backup with timestamp + mv "{filename}-formatted.md" "{filename}-formatted.backup-$(date +%Y%m%d-%H%M%S).md" +fi +``` + +Example: +- `final-formatted.md` exists → backup to `final-formatted.backup-20260128-143052.md` + +### Step 7: Execute Text Formatting Script + +After saving, **must** run the formatting script: + +```bash +npx -y bun ${SKILL_DIR}/scripts/main.ts {output-file-path} [options] +``` + +**Script Options:** + +| Option | Short | Description | Default | +|--------|-------|-------------|---------| +| `--quotes` | `-q` | Replace ASCII quotes with fullwidth quotes `"..."` | false | +| `--no-quotes` | | Do not replace quotes | | +| `--spacing` | `-s` | Add CJK/English spacing via autocorrect | true | +| `--no-spacing` | | Do not add CJK/English spacing | | +| `--emphasis` | `-e` | Fix CJK emphasis punctuation issues | true | +| `--no-emphasis` | | Do not fix CJK emphasis issues | | +| `--help` | `-h` | Show help message | | + +**Examples:** + +```bash +# Default: spacing + emphasis enabled, quotes disabled +npx -y bun ${SKILL_DIR}/scripts/main.ts article.md + +# Enable all features including quote replacement +npx -y bun ${SKILL_DIR}/scripts/main.ts article.md --quotes + +# Only fix emphasis issues, skip spacing +npx -y bun ${SKILL_DIR}/scripts/main.ts article.md --no-spacing + +# Disable all processing except frontmatter formatting +npx -y bun ${SKILL_DIR}/scripts/main.ts article.md --no-spacing --no-emphasis +``` + +**Script performs (based on options):** +1. Fix CJK emphasis/bold punctuation issues (default: enabled) +2. Add CJK/English mixed text spacing via autocorrect (default: enabled) +3. Replace ASCII quotes `"..."` with fullwidth quotes `"..."` (default: disabled) +4. Format frontmatter YAML (always enabled) + +### Step 8: Display Results + +``` +**Formatting complete** + +File: posts/2026/01/09/example/final-formatted.md + +Changes: +- Added title: [title content] +- Added X bold markers +- Added X lists +- Added X code blocks +``` + +## Formatting Example + +**Before:** +``` +This is plain text. First point is efficiency improvement. Second point is cost reduction. Third point is experience optimization. Use npm install to install dependencies. +``` + +**After:** +```markdown +--- +title: Three Core Advantages +slug: three-core-advantages +summary: Discover the three key benefits that drive success in modern projects. +--- + +This is plain text. + +**Main advantages:** +- Efficiency improvement +- Cost reduction +- Experience optimization + +Use `npm install` to install dependencies. +``` + +## Notes + +- Preserve original writing style and tone +- Specify correct language for code blocks (e.g., `python`, `javascript`) +- Maintain CJK/English spacing standards +- Do not add content not present in original + +## Extension Support + +Custom configurations via EXTEND.md. See **Preferences** section for paths and supported options. diff --git a/skills/baoyu-format-markdown/scripts/autocorrect.ts b/skills/baoyu-format-markdown/scripts/autocorrect.ts new file mode 100644 index 0000000..9043dab --- /dev/null +++ b/skills/baoyu-format-markdown/scripts/autocorrect.ts @@ -0,0 +1,10 @@ +import { execSync } from "child_process"; + +export function applyAutocorrect(filePath: string): boolean { + try { + execSync(`npx autocorrect-node --fix "${filePath}"`, { stdio: "inherit" }); + return true; + } catch { + return false; + } +} diff --git a/skills/baoyu-format-markdown/scripts/bun.lock b/skills/baoyu-format-markdown/scripts/bun.lock new file mode 100644 index 0000000..4096442 --- /dev/null +++ b/skills/baoyu-format-markdown/scripts/bun.lock @@ -0,0 +1,165 @@ +{ + "lockfileVersion": 1, + "workspaces": { + "": { + "dependencies": { + "remark-frontmatter": "^5.0.0", + "remark-gfm": "^4.0.1", + "remark-parse": "^11.0.0", + "remark-stringify": "^11.0.0", + "unified": "^11.0.5", + "unist-util-visit": "^5.1.0", + "yaml": "^2.8.2", + }, + }, + }, + "packages": { + "@types/debug": ["@types/debug@4.1.12", "", { "dependencies": { "@types/ms": "*" } }, "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ=="], + + "@types/mdast": ["@types/mdast@4.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="], + + "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="], + + "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="], + + "bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="], + + "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], + + "character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "decode-named-character-reference": ["decode-named-character-reference@1.3.0", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="], + + "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], + + "devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="], + + "escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="], + + "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], + + "fault": ["fault@2.0.1", "", { "dependencies": { "format": "^0.2.0" } }, "sha512-WtySTkS4OKev5JtpHXnib4Gxiurzh5NCGvWrFaZ34m6JehfTUhKZvn9njTfw48t6JumVQOmrKqpmGcdwxnhqBQ=="], + + "format": ["format@0.2.2", "", {}, "sha512-wzsgA6WOq+09wrU1tsJ09udeR/YZRaeArL9e1wPbFg3GG2yDnC2ldKpxs4xunpFF9DgqCqOIra3bc1HWrJ37Ww=="], + + "is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="], + + "longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="], + + "markdown-table": ["markdown-table@3.0.4", "", {}, "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw=="], + + "mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg=="], + + "mdast-util-from-markdown": ["mdast-util-from-markdown@2.0.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-uZhTV/8NBuw0WHkPTrCqDOl0zVe1BIng5ZtHoDk49ME1qqcjYmmLmOf0gELgcRMxN4w2iuIeVso5/6QymSrgmA=="], + + "mdast-util-frontmatter": ["mdast-util-frontmatter@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "escape-string-regexp": "^5.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "micromark-extension-frontmatter": "^2.0.0" } }, "sha512-LRqI9+wdgC25P0URIJY9vwocIzCcksduHQ9OF2joxQoyTNVduwLAFUzjoopuRJbJAReaKrNQKAZKL3uCMugWJA=="], + + "mdast-util-gfm": ["mdast-util-gfm@3.1.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-gfm-autolink-literal": "^2.0.0", "mdast-util-gfm-footnote": "^2.0.0", "mdast-util-gfm-strikethrough": "^2.0.0", "mdast-util-gfm-table": "^2.0.0", "mdast-util-gfm-task-list-item": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ=="], + + "mdast-util-gfm-autolink-literal": ["mdast-util-gfm-autolink-literal@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "ccount": "^2.0.0", "devlop": "^1.0.0", "mdast-util-find-and-replace": "^3.0.0", "micromark-util-character": "^2.0.0" } }, "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ=="], + + "mdast-util-gfm-footnote": ["mdast-util-gfm-footnote@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0" } }, "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ=="], + + "mdast-util-gfm-strikethrough": ["mdast-util-gfm-strikethrough@2.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg=="], + + "mdast-util-gfm-table": ["mdast-util-gfm-table@2.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "markdown-table": "^3.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg=="], + + "mdast-util-gfm-task-list-item": ["mdast-util-gfm-task-list-item@2.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ=="], + + "mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="], + + "mdast-util-to-markdown": ["mdast-util-to-markdown@2.1.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA=="], + + "mdast-util-to-string": ["mdast-util-to-string@4.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0" } }, "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg=="], + + "micromark": ["micromark@4.0.2", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA=="], + + "micromark-core-commonmark": ["micromark-core-commonmark@2.0.3", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg=="], + + "micromark-extension-frontmatter": ["micromark-extension-frontmatter@2.0.0", "", { "dependencies": { "fault": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-C4AkuM3dA58cgZha7zVnuVxBhDsbttIMiytjgsM2XbHAB2faRVaHRle40558FBN+DJcrLNCoqG5mlrpdU4cRtg=="], + + "micromark-extension-gfm": ["micromark-extension-gfm@3.0.0", "", { "dependencies": { "micromark-extension-gfm-autolink-literal": "^2.0.0", "micromark-extension-gfm-footnote": "^2.0.0", "micromark-extension-gfm-strikethrough": "^2.0.0", "micromark-extension-gfm-table": "^2.0.0", "micromark-extension-gfm-tagfilter": "^2.0.0", "micromark-extension-gfm-task-list-item": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w=="], + + "micromark-extension-gfm-autolink-literal": ["micromark-extension-gfm-autolink-literal@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw=="], + + "micromark-extension-gfm-footnote": ["micromark-extension-gfm-footnote@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw=="], + + "micromark-extension-gfm-strikethrough": ["micromark-extension-gfm-strikethrough@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw=="], + + "micromark-extension-gfm-table": ["micromark-extension-gfm-table@2.1.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg=="], + + "micromark-extension-gfm-tagfilter": ["micromark-extension-gfm-tagfilter@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg=="], + + "micromark-extension-gfm-task-list-item": ["micromark-extension-gfm-task-list-item@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw=="], + + "micromark-factory-destination": ["micromark-factory-destination@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA=="], + + "micromark-factory-label": ["micromark-factory-label@2.0.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg=="], + + "micromark-factory-space": ["micromark-factory-space@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg=="], + + "micromark-factory-title": ["micromark-factory-title@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw=="], + + "micromark-factory-whitespace": ["micromark-factory-whitespace@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ=="], + + "micromark-util-character": ["micromark-util-character@2.1.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q=="], + + "micromark-util-chunked": ["micromark-util-chunked@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA=="], + + "micromark-util-classify-character": ["micromark-util-classify-character@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q=="], + + "micromark-util-combine-extensions": ["micromark-util-combine-extensions@2.0.1", "", { "dependencies": { "micromark-util-chunked": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg=="], + + "micromark-util-decode-numeric-character-reference": ["micromark-util-decode-numeric-character-reference@2.0.2", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw=="], + + "micromark-util-decode-string": ["micromark-util-decode-string@2.0.1", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ=="], + + "micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="], + + "micromark-util-html-tag-name": ["micromark-util-html-tag-name@2.0.1", "", {}, "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA=="], + + "micromark-util-normalize-identifier": ["micromark-util-normalize-identifier@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q=="], + + "micromark-util-resolve-all": ["micromark-util-resolve-all@2.0.1", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg=="], + + "micromark-util-sanitize-uri": ["micromark-util-sanitize-uri@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ=="], + + "micromark-util-subtokenize": ["micromark-util-subtokenize@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA=="], + + "micromark-util-symbol": ["micromark-util-symbol@2.0.1", "", {}, "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q=="], + + "micromark-util-types": ["micromark-util-types@2.0.2", "", {}, "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "remark-frontmatter": ["remark-frontmatter@5.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-frontmatter": "^2.0.0", "micromark-extension-frontmatter": "^2.0.0", "unified": "^11.0.0" } }, "sha512-XTFYvNASMe5iPN0719nPrdItC9aU0ssC4v14mH1BCi1u0n1gAocqcujWUrByftZTbLhRtiKRyjYTSIOcr69UVQ=="], + + "remark-gfm": ["remark-gfm@4.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="], + + "remark-parse": ["remark-parse@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="], + + "remark-stringify": ["remark-stringify@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-to-markdown": "^2.0.0", "unified": "^11.0.0" } }, "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw=="], + + "trough": ["trough@2.2.0", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="], + + "unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="], + + "unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="], + + "unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="], + + "unist-util-visit": ["unist-util-visit@5.1.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg=="], + + "unist-util-visit-parents": ["unist-util-visit-parents@6.0.2", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="], + + "vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="], + + "vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="], + + "yaml": ["yaml@2.8.2", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A=="], + + "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], + } +} diff --git a/skills/baoyu-format-markdown/scripts/cjk-emphasis.ts b/skills/baoyu-format-markdown/scripts/cjk-emphasis.ts new file mode 100644 index 0000000..f1d618a --- /dev/null +++ b/skills/baoyu-format-markdown/scripts/cjk-emphasis.ts @@ -0,0 +1,187 @@ +const CJK_PUNCT_COMMON = "。.,、?!:;"; +const CJK_OPENING_PUNCT = "(〔〖〘〚「『〈《【\u201C\u2018"; +const CJK_CLOSING_PUNCT = ")〕〗〙〛」』〉》】\u201D\u2019" + CJK_PUNCT_COMMON; +const CJK_SCRIPTS = + "\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}"; + +export const CJK_CLOSING_PUNCT_RE = new RegExp(`[${CJK_CLOSING_PUNCT}]`); +export const CJK_OPENING_PUNCT_RE = new RegExp(`^[${CJK_OPENING_PUNCT}]`); +export const CJK_CHAR_RE = new RegExp(`[${CJK_SCRIPTS}]`, "u"); + +const PUNCT_OR_SYMBOL_RE = /[\p{P}\p{S}]/u; +const WORD_CHAR_RE = /[\p{L}\p{N}]/u; + +function findInlineCodeRanges(text: string): Array<[number, number]> { + const ranges: Array<[number, number]> = []; + let i = 0; + while (i < text.length) { + if (text[i] !== "`") { + i += 1; + continue; + } + + let run = 1; + while (i + run < text.length && text[i + run] === "`") { + run += 1; + } + + const start = i; + let j = i + run; + let found = false; + while (j < text.length) { + if (text[j] !== "`") { + j += 1; + continue; + } + let closeRun = 1; + while (j + closeRun < text.length && text[j + closeRun] === "`") { + closeRun += 1; + } + if (closeRun === run) { + ranges.push([start, j + closeRun - 1]); + i = j + closeRun; + found = true; + break; + } + j += closeRun; + } + + if (!found) { + i = start + run; + } + } + return ranges; +} + +function isEscaped(text: string, pos: number): boolean { + let count = 0; + for (let i = pos - 1; i >= 0 && text[i] === "\\"; i -= 1) { + count += 1; + } + return count % 2 === 1; +} + +function isWhitespaceChar(ch: string | undefined): boolean { + return !ch || /\s/u.test(ch); +} + +function isPunctuationOrSymbol(ch: string | undefined): boolean { + return !!ch && PUNCT_OR_SYMBOL_RE.test(ch); +} + +function fixCjkEmphasisSpacingInBlock(block: string): string { + const codeRanges = findInlineCodeRanges(block); + let rangeIndex = 0; + + const delimiters: Array<{ + pos: number; + canOpen: boolean; + canClose: boolean; + }> = []; + let cursor = 0; + while (cursor < block.length - 1) { + if (rangeIndex < codeRanges.length && cursor >= codeRanges[rangeIndex][0]) { + if (cursor <= codeRanges[rangeIndex][1]) { + cursor = codeRanges[rangeIndex][1] + 1; + continue; + } + rangeIndex += 1; + continue; + } + + if ( + block[cursor] === "*" && + block[cursor + 1] === "*" && + block[cursor - 1] !== "*" && + block[cursor + 2] !== "*" && + !isEscaped(block, cursor) + ) { + const before = block[cursor - 1]; + const after = block[cursor + 2]; + const beforeIsSpace = isWhitespaceChar(before); + const afterIsSpace = isWhitespaceChar(after); + const beforeIsPunct = isPunctuationOrSymbol(before); + const afterIsPunct = isPunctuationOrSymbol(after); + const leftFlanking = + !afterIsSpace && (!afterIsPunct || beforeIsSpace || beforeIsPunct); + const rightFlanking = + !beforeIsSpace && (!beforeIsPunct || afterIsSpace || afterIsPunct); + const cjkPunctBefore = !!before && CJK_CLOSING_PUNCT_RE.test(before); + const wordAfter = !!after && WORD_CHAR_RE.test(after); + + delimiters.push({ + pos: cursor, + canOpen: leftFlanking, + canClose: rightFlanking || (cjkPunctBefore && wordAfter), + }); + cursor += 2; + continue; + } + + cursor += 1; + } + + const stack: Array<{ pos: number }> = []; + const pairs: Array<{ open: number; close: number }> = []; + for (const delimiter of delimiters) { + if (delimiter.canClose) { + let openerIndex = -1; + for (let j = stack.length - 1; j >= 0; j -= 1) { + openerIndex = j; + break; + } + if (openerIndex !== -1) { + const opener = stack.splice(openerIndex, 1)[0]; + pairs.push({ open: opener.pos, close: delimiter.pos }); + } + } + if (delimiter.canOpen) { + stack.push({ pos: delimiter.pos }); + } + } + + if (pairs.length === 0) return block; + + const insertPositions = new Set(); + for (const pair of pairs) { + const insideLast = block[pair.close - 1]; + const afterClose = block[pair.close + 2]; + if (!afterClose) continue; + if ( + CJK_CLOSING_PUNCT_RE.test(insideLast) && + WORD_CHAR_RE.test(afterClose) + ) { + insertPositions.add(pair.close + 2); + } + } + + if (insertPositions.size === 0) return block; + + let result = ""; + for (let idx = 0; idx < block.length; idx += 1) { + if (insertPositions.has(idx)) { + result += " "; + } + result += block[idx]; + } + if (insertPositions.has(block.length)) { + result += " "; + } + return result; +} + +export function fixCjkEmphasisSpacing(content: string): string { + const parts = content.split(/(^```[\s\S]*?^```|^~~~[\s\S]*?^~~~)/m); + return parts + .map((part, i) => { + if (i % 2 === 1) return part; + const blocks = part.split(/(\n\s*\n+)/); + return blocks + .map((block, index) => { + if (index % 2 === 1) return block; + return fixCjkEmphasisSpacingInBlock(block); + }) + .join(""); + }) + .join(""); +} diff --git a/skills/baoyu-format-markdown/scripts/main.ts b/skills/baoyu-format-markdown/scripts/main.ts new file mode 100644 index 0000000..9794bc6 --- /dev/null +++ b/skills/baoyu-format-markdown/scripts/main.ts @@ -0,0 +1,221 @@ +import { readFileSync, writeFileSync } from "fs"; +import { unified } from "unified"; +import remarkParse from "remark-parse"; +import remarkGfm from "remark-gfm"; +import remarkFrontmatter from "remark-frontmatter"; +import remarkStringify from "remark-stringify"; +import { visit } from "unist-util-visit"; +import YAML from "yaml"; +import { + fixCjkEmphasisSpacing, + CJK_CLOSING_PUNCT_RE, + CJK_OPENING_PUNCT_RE, + CJK_CHAR_RE, +} from "./cjk-emphasis"; +import { replaceQuotes } from "./quotes"; +import { applyAutocorrect } from "./autocorrect"; + +export interface FormatOptions { + quotes?: boolean; + spacing?: boolean; + emphasis?: boolean; +} + +export interface FormatResult { + success: boolean; + filePath: string; + quotesFixed: boolean; + spacingApplied: boolean; + emphasisFixed: boolean; + error?: string; +} + +const DEFAULT_OPTIONS: Required = { + quotes: false, + spacing: true, + emphasis: true, +}; + +function formatFrontmatter(value: string): string | null { + try { + const doc = YAML.parseDocument(value); + return doc.toString({ lineWidth: 0 }).trimEnd(); + } catch { + return null; + } +} + +function formatMarkdownContent( + content: string, + options: Required +): string { + if (options.emphasis) { + content = fixCjkEmphasisSpacing(content); + } + + const processor = unified() + .use(remarkParse) + .use(remarkGfm) + .use(remarkFrontmatter, ["yaml"]) + .use(remarkStringify, { + wrap: false, + }); + + const tree = processor.parse(content); + + visit(tree, (node, _index, parent) => { + if (node.type === "text" && options.quotes) { + const textNode = node as { value: string }; + textNode.value = replaceQuotes(textNode.value); + return; + } + if (node.type === "yaml") { + const yamlNode = node as { value: string }; + const formatted = formatFrontmatter(yamlNode.value); + if (formatted !== null) { + yamlNode.value = formatted; + } + return; + } + if ( + options.emphasis && + (node.type === "strong" || + node.type === "emphasis" || + node.type === "delete") && + parent + ) { + const siblings = (parent as { children: typeof node[] }).children; + const idx = siblings.indexOf(node); + const children = (node as { children: typeof node[] }).children; + if (!children || children.length === 0) return; + + const lastChild = children[children.length - 1]; + if (lastChild.type === "text") { + const lastText = (lastChild as { value: string }).value; + if ( + CJK_CLOSING_PUNCT_RE.test(lastText.slice(-1)) && + idx + 1 < siblings.length + ) { + const nextSib = siblings[idx + 1]; + if (nextSib.type === "text") { + const nextText = (nextSib as { value: string }).value; + if (CJK_CHAR_RE.test(nextText.charAt(0))) { + (nextSib as { value: string }).value = " " + nextText; + } + } + } + } + + const firstChild = children[0]; + if (firstChild.type === "text") { + const firstText = (firstChild as { value: string }).value; + if (CJK_OPENING_PUNCT_RE.test(firstText) && idx > 0) { + const prevSib = siblings[idx - 1]; + if (prevSib.type === "text") { + const prevText = (prevSib as { value: string }).value; + if (CJK_CHAR_RE.test(prevText.charAt(prevText.length - 1))) { + (prevSib as { value: string }).value = prevText + " "; + } + } + } + } + } + }); + + let result = processor.stringify(tree); + if (options.emphasis) { + result = fixCjkEmphasisSpacing(result); + } + return result; +} + +export function formatMarkdown( + filePath: string, + options?: FormatOptions +): FormatResult { + const opts: Required = { ...DEFAULT_OPTIONS, ...options }; + + const result: FormatResult = { + success: false, + filePath, + quotesFixed: false, + spacingApplied: false, + emphasisFixed: false, + }; + + try { + const content = readFileSync(filePath, "utf-8"); + const formattedContent = formatMarkdownContent(content, opts); + + result.quotesFixed = opts.quotes; + result.emphasisFixed = opts.emphasis; + + writeFileSync(filePath, formattedContent, "utf-8"); + + if (opts.spacing) { + result.spacingApplied = applyAutocorrect(filePath); + } + + result.success = true; + console.log(`✓ Formatted: ${filePath}`); + } catch (error) { + result.error = error instanceof Error ? error.message : String(error); + console.error(`✗ Format failed: ${result.error}`); + } + + return result; +} + +function parseArgs(args: string[]): { filePath: string; options: FormatOptions } { + const options: FormatOptions = {}; + let filePath = ""; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === "--quotes" || arg === "-q") { + options.quotes = true; + } else if (arg === "--no-quotes") { + options.quotes = false; + } else if (arg === "--spacing" || arg === "-s") { + options.spacing = true; + } else if (arg === "--no-spacing") { + options.spacing = false; + } else if (arg === "--emphasis" || arg === "-e") { + options.emphasis = true; + } else if (arg === "--no-emphasis") { + options.emphasis = false; + } else if (arg === "--help" || arg === "-h") { + console.log(`Usage: npx -y bun scripts/main.ts [options] + +Options: + -q, --quotes Replace ASCII quotes with fullwidth quotes (default: false) + --no-quotes Do not replace quotes + -s, --spacing Add CJK/English spacing via autocorrect (default: true) + --no-spacing Do not add CJK/English spacing + -e, --emphasis Fix CJK emphasis punctuation issues (default: true) + --no-emphasis Do not fix CJK emphasis issues + -h, --help Show this help message`); + process.exit(0); + } else if (!arg.startsWith("-")) { + filePath = arg; + } + } + + return { filePath, options }; +} + +if (import.meta.url === `file://${process.argv[1]}`) { + const { filePath, options } = parseArgs(process.argv.slice(2)); + + if (!filePath) { + console.error("Usage: npx -y bun scripts/main.ts [options]"); + console.error("Use --help for more information."); + process.exit(1); + } + + const result = formatMarkdown(filePath, options); + if (!result.success) { + process.exit(1); + } +} diff --git a/skills/baoyu-format-markdown/scripts/package.json b/skills/baoyu-format-markdown/scripts/package.json new file mode 100644 index 0000000..3841a0b --- /dev/null +++ b/skills/baoyu-format-markdown/scripts/package.json @@ -0,0 +1,11 @@ +{ + "dependencies": { + "remark-frontmatter": "^5.0.0", + "remark-gfm": "^4.0.1", + "remark-parse": "^11.0.0", + "remark-stringify": "^11.0.0", + "unified": "^11.0.5", + "unist-util-visit": "^5.1.0", + "yaml": "^2.8.2" + } +} \ No newline at end of file diff --git a/skills/baoyu-format-markdown/scripts/quotes.ts b/skills/baoyu-format-markdown/scripts/quotes.ts new file mode 100644 index 0000000..7b6837d --- /dev/null +++ b/skills/baoyu-format-markdown/scripts/quotes.ts @@ -0,0 +1,5 @@ +export function replaceQuotes(content: string): string { + return content + .replace(/"([^"]+)"/g, "\u201c$1\u201d") + .replace(/「([^」]+)」/g, "\u201c$1\u201d"); +}