Back to skills
SkillHub ClubShip Full StackFull Stack

baoyu-format-markdown

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.

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
9,533
Hot score
99
Updated
March 20, 2026
Overall rating
C5.0
Composite score
5.0
Best-practice grade
B73.6

Install command

npx @skill-hub/cli install jimliu-baoyu-skills-baoyu-format-markdown

Repository

JimLiu/baoyu-skills

Skill path: skills/baoyu-format-markdown

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.

Open repository

Best for

Primary workflow: Ship Full Stack.

Technical facets: Full Stack.

Target audience: everyone.

License: Unknown.

Original source

Catalog source: SkillHub Club.

Repository owner: JimLiu.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install baoyu-format-markdown into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/JimLiu/baoyu-skills before adding baoyu-format-markdown to shared team environments
  • Use baoyu-format-markdown for development workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 0.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
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 1.5: Detect Content Type & Confirm

**Content Type Detection:**

| Indicator | Classification |
|-----------|----------------|
| Has `---` YAML frontmatter | Markdown |
| Has `#`, `##`, `###` headings | Markdown |
| Has `**bold**`, `*italic*` | Markdown |
| Has `- ` or `1. ` lists | Markdown |
| Has ``` code blocks | Markdown |
| Has `> ` blockquotes | Markdown |
| None of above | Plain text |

**Decision Flow:**

┌─────────────────┬────────────────────────────────────────────────┐
│  Content Type   │                     Action                     │
├─────────────────┼────────────────────────────────────────────────┤
│ Plain text      │ Proceed to Step 2 (format to markdown)         │
├─────────────────┼────────────────────────────────────────────────┤
│ Markdown        │ Use AskUserQuestion to confirm optimization    │
└─────────────────┴────────────────────────────────────────────────┘

**If Markdown detected, ask user:**

```
Detected existing markdown formatting. What would you like to do?

1. Optimize formatting (Recommended)
   - Add/improve frontmatter, headings, bold, lists
   - Run typography script (spacing, emphasis fixes)
   - Output: {filename}-formatted.md

2. Keep original formatting
   - Preserve existing markdown structure
   - Run typography script (spacing, emphasis fixes)
   - Output: {filename}-formatted.md

3. Typography fixes only
   - Run typography script on original file in-place
   - No copy created, modifies original file directly
```

**Based on user choice:**
- **Optimize**: Continue to Step 2-8 (full workflow)
- **Keep original**: Skip Steps 2-5, copy file → Step 6-8 (run script on copy)
- **Typography only**: Skip Steps 2-6, run Step 7 on original file directly

### 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`

**If user chose "Keep original formatting" (from Step 1.5):**
- Copy original file to `{filename}-formatted.md` without modifications
- Proceed to Step 7 for typography fixes only

**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.


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### scripts/main.ts

```typescript
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<FormatOptions> = {
  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<FormatOptions>
): 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<FormatOptions> = { ...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 <file.md> [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 <file.md> [options]");
    console.error("Use --help for more information.");
    process.exit(1);
  }

  const result = formatMarkdown(filePath, options);
  if (!result.success) {
    process.exit(1);
  }
}

```

### scripts/cjk-emphasis.ts

```typescript
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;

const CJK_PUNCT_PAIRS: Record<string, string> = {
  "“": "”",
  "‘": "’",
  "(": ")",
  "〔": "〕",
  "〖": "〗",
  "〘": "〙",
  "〚": "〛",
  "「": "」",
  "『": "』",
  "〈": "〉",
  "《": "》",
  "【": "】",
};

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 isMatchingCjkPunct(open: string, close: string): boolean {
  return CJK_PUNCT_PAIRS[open] === close;
}

function mapNonCodeSegments(
  block: string,
  mapper: (segment: string) => string
): string {
  const codeRanges = findInlineCodeRanges(block);
  if (codeRanges.length === 0) {
    return mapper(block);
  }

  let result = "";
  let lastIndex = 0;
  for (const [start, end] of codeRanges) {
    if (start > lastIndex) {
      result += mapper(block.slice(lastIndex, start));
    }
    result += block.slice(start, end + 1);
    lastIndex = end + 1;
  }
  if (lastIndex < block.length) {
    result += mapper(block.slice(lastIndex));
  }
  return result;
}

function moveCjkPunctuationOutsideEmphasis(block: string): string {
  return mapNonCodeSegments(block, (segment) => {
    const delimiterPositions: number[] = [];
    let cursor = 0;
    while (cursor < segment.length - 1) {
      if (
        segment[cursor] === "*" &&
        segment[cursor + 1] === "*" &&
        segment[cursor - 1] !== "*" &&
        segment[cursor + 2] !== "*" &&
        !isEscaped(segment, cursor)
      ) {
        delimiterPositions.push(cursor);
        cursor += 2;
        continue;
      }
      cursor += 1;
    }

    if (delimiterPositions.length < 2) return segment;

    const stack: number[] = [];
    const pairs: Array<{ open: number; close: number }> = [];
    for (const pos of delimiterPositions) {
      if (stack.length === 0) {
        stack.push(pos);
      } else {
        const open = stack.pop() as number;
        pairs.push({ open, close: pos });
      }
    }

    const skip = new Set<number>();
    const insertBefore = new Map<number, string>();

    for (const pair of pairs) {
      const openPunctPos = pair.open + 2;
      const closePunctPos = pair.close - 1;
      if (openPunctPos >= closePunctPos) continue;

      const openPunct = segment[openPunctPos];
      const closePunct = segment[closePunctPos];
      if (!openPunct || !closePunct) continue;
      if (!CJK_OPENING_PUNCT_RE.test(openPunct)) continue;
      if (!CJK_CLOSING_PUNCT_RE.test(closePunct)) continue;
      if (!isMatchingCjkPunct(openPunct, closePunct)) continue;
      if (openPunctPos + 1 >= closePunctPos) continue;

      const inner = segment.slice(openPunctPos + 1, closePunctPos);
      if (inner.length === 0) continue;

      skip.add(openPunctPos);
      skip.add(closePunctPos);

      insertBefore.set(pair.open, (insertBefore.get(pair.open) ?? "") + openPunct);
      const afterClose = pair.close + 2;
      insertBefore.set(
        afterClose,
        (insertBefore.get(afterClose) ?? "") + closePunct
      );
    }

    if (skip.size === 0) return segment;

    let result = "";
    for (let idx = 0; idx < segment.length; idx += 1) {
      const insert = insertBefore.get(idx);
      if (insert) {
        result += insert;
      }
      if (skip.has(idx)) {
        continue;
      }
      result += segment[idx];
    }
    const tailInsert = insertBefore.get(segment.length);
    if (tailInsert) {
      result += tailInsert;
    }
    return result;
  });
}

function fixCjkEmphasisSpacingInBlock(block: string): string {
  const normalized = moveCjkPunctuationOutsideEmphasis(block);
  const codeRanges = findInlineCodeRanges(normalized);
  let rangeIndex = 0;

  const delimiters: Array<{
    pos: number;
    canOpen: boolean;
    canClose: boolean;
  }> = [];
  let cursor = 0;
  while (cursor < normalized.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 (
      normalized[cursor] === "*" &&
      normalized[cursor + 1] === "*" &&
      normalized[cursor - 1] !== "*" &&
      normalized[cursor + 2] !== "*" &&
      !isEscaped(normalized, cursor)
    ) {
      const before = normalized[cursor - 1];
      const after = normalized[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 normalized;

  const insertPositions = new Set<number>();
  for (const pair of pairs) {
    const insideLast = normalized[pair.close - 1];
    const afterClose = normalized[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 normalized;

  let result = "";
  for (let idx = 0; idx < normalized.length; idx += 1) {
    if (insertPositions.has(idx)) {
      result += " ";
    }
    result += normalized[idx];
  }
  if (insertPositions.has(normalized.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("");
}

```

### scripts/quotes.ts

```typescript
export function replaceQuotes(content: string): string {
  return content
    .replace(/"([^"]+)"/g, "\u201c$1\u201d")
    .replace(/「([^」]+)」/g, "\u201c$1\u201d");
}

```

### scripts/autocorrect.ts

```typescript
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;
  }
}

```

baoyu-format-markdown | SkillHub