#!/usr/bin/env node 'use strict'; const fs = require('fs'); const { loadStyleWhitelist, styleSpans } = require('./style-whitelist.js'); const path = require('path'); const USAGE = `Usage: node normalize-punctuation.js [--check] [--quote-mode keep|curly|ascii|yan] Normalize正文 punctuation deterministically: - keep standard ellipses (……) in dialogue, 【…】 panels, and narration; unify non-standard ellipses (..., single …, ………+, 。。。+, .……..) to …… - keep em dashes inside dialogue quotes (“”「」『』 and paired ASCII "), unified as —— - replace unquoted em dashes and double hyphens in narration with Chinese punctuation - remove markdown divider lines (---) from正文 - preserve pause punctuation covered by book-local .deslop-whitelist literals - keep quote style by default; convert quotes only when explicitly requested (curly|ascii|yan) `; const options = { check: false, quoteMode: 'keep', files: [], }; for (let i = 2; i < process.argv.length; i += 1) { const arg = process.argv[i]; if (arg === '--check') { options.check = true; } else if (arg === '--quote-mode') { const value = process.argv[i + 1]; if (!value) die('--quote-mode requires keep, curly, ascii, or yan'); options.quoteMode = value; i += 1; } else if (arg.startsWith('--quote-mode=')) { options.quoteMode = arg.slice('--quote-mode='.length); } else if (arg === '-h' || arg === '--help') { process.stdout.write(USAGE); process.exit(0); } else if (arg.startsWith('-')) { die(`Unknown option: ${arg}`); } else { options.files.push(arg); } } if (!['keep', 'curly', 'ascii', 'yan'].includes(options.quoteMode)) { die(`Invalid --quote-mode: ${options.quoteMode}`); } if (options.files.length === 0) { die('No files provided'); } let totalFindings = 0; let changedFiles = 0; let failed = false; for (const file of options.files) { const fullPath = path.resolve(file); let input; try { input = fs.readFileSync(fullPath, 'utf8'); } catch (error) { failed = true; console.error(`${file}: unable to read (${error.message})`); continue; } let whitelist; try { whitelist = loadStyleWhitelist(fullPath); } catch (error) { die(`${file}: unable to read .deslop-whitelist (${error.message})`); } const result = normalizeDocument(input, options.quoteMode, whitelist); totalFindings += result.findings.length; if (options.check) { for (const finding of result.findings) { console.log(`${file}:${finding.line}:${finding.column}: ${finding.type}: ${finding.message}`); } continue; } if (result.output !== input) { fs.writeFileSync(fullPath, result.output, 'utf8'); changedFiles += 1; console.log(`${file}: normalized (${result.findings.length} issue${result.findings.length === 1 ? '' : 's'})`); } } if (failed) { process.exit(2); } if (options.check && totalFindings > 0) { process.exit(1); } if (!options.check) { console.log(`Done. Changed files: ${changedFiles}`); } function die(message) { console.error(message); console.error(USAGE.trimEnd()); process.exit(2); } function normalizeDocument(input, quoteMode, whitelist) { const { lines, endings } = splitLinesKeepingEndings(input); const findings = []; const outputLines = []; let fence = null; let inFrontMatter = hasYamlFrontMatter(lines); let quoteOpen = false; let commentOpen = false; let commentStart = null; const commentCloseAhead = new Array(lines.length + 1).fill(false); for (let index = lines.length - 1; index >= 0; index -= 1) { commentCloseAhead[index] = lines[index].includes('-->') || commentCloseAhead[index + 1]; } for (let index = 0; index < lines.length; index += 1) { const lineNo = index + 1; const ending = endings[index]; let line = lines[index]; const trimmed = line.trim(); // 未闭合的 `` 时, // 在起始位置具名报错,并从当前行恢复正文扫描;起始符所在行仍原样保护。 if (commentOpen && !commentCloseAhead[index]) { findings.push({ line: commentStart?.line || lineNo, column: commentStart?.column || 1, type: 'html-comment-unclosed', message: 'HTML 注释未闭合;后续内容仍按正文检查。', }); commentOpen = false; commentStart = null; } if (inFrontMatter) { outputLines.push(line + ending); if (index > 0 && trimmed === '---') inFrontMatter = false; continue; } if (fence) { outputLines.push(line + ending); if (isClosingFence(line, fence)) fence = null; continue; } const openingFence = parseOpeningFence(line); if (openingFence) { fence = openingFence; outputLines.push(line + ending); continue; } // 跨行 HTML 注释里的 `---` 是注释内容,不是正文分隔线。 if (trimmed === '---' && !commentOpen) { findings.push({ line: lineNo, column: line.indexOf('-') + 1, type: 'markdown-divider', message: '正文中不要使用 markdown 分隔线;建议移除该行。', }); continue; } const commentOpenBefore = commentOpen; const punctuationResult = normalizePausePunctuation(line, lineNo, commentOpen, whitelist); findings.push(...punctuationResult.findings); line = punctuationResult.line; commentOpen = punctuationResult.commentOpen; if (!commentOpenBefore && commentOpen) { commentStart = { line: lineNo, column: Math.max(1, line.lastIndexOf('` 豁免标记):`` 里的 // `--` 不是停顿标点,改掉它注释就散了,标记会变成读者看得见的正文。 if (insideSpans(match.index, match.index + token.length, commentSpans)) continue; const inDialogueQuote = insideSpans(match.index, match.index + token.length, quotes); const hasEllipsis = /[…。]|\.{3,}/.test(token); const hasDash = /[—-]/.test(token); // 破折号与省略号紧挨粘连(如 `“等等——....……”`):引号内收束为 `……`;引号外走常规替换或收束为 `……`。 if (hasEllipsis && hasDash) { const merged = lastIndex === match.index && output.endsWith('……'); const replacement = merged ? '' : '……'; output += original.slice(lastIndex, match.index) + replacement; lastIndex = match.index + token.length; findings.push({ line: lineNo, column: match.index + 1, type: token.startsWith('-') ? 'double-hyphen' : 'em-dash', message: '粘连的破折号与省略号统一为「……」。', }); continue; } // 省略号(对话引号内、系统面板【…】内、叙述旁白):标准 `……` 原样保留,非标形态统一规整为 `……` // (旁白省略号刷屏由 check-ai-patterns.js 的 ellipsis-density-tic 按密度提示,不在标点层一刀切改逗号)。 if (hasEllipsis) { const merged = lastIndex === match.index && output.endsWith('……'); const replacement = merged ? '' : '……'; output += original.slice(lastIndex, match.index) + replacement; lastIndex = match.index + token.length; if (replacement !== token) { findings.push({ line: lineNo, column: match.index + 1, type: 'ellipsis', message: '省略号统一为「……」。' }); } continue; } // 对话引号内的破折号(话被打断或拖音,真人网文约 13% 章节使用):`——` 原样保留,单 `—` / 多 `———` / `--` 统一为 `——`。 if (inDialogueQuote && hasDash) { const merged = lastIndex === match.index && output.endsWith('——'); const replacement = merged ? '' : '——'; output += original.slice(lastIndex, match.index) + replacement; lastIndex = match.index + token.length; if (replacement !== token) { findings.push({ line: lineNo, column: match.index + 1, type: getPauseType(token), message: '引号内的破折号统一为「——」。', }); } continue; } output += original.slice(lastIndex, match.index); const replacement = choosePauseReplacement(original, match.index, token.length); output += replacement; findings.push({ line: lineNo, column: match.index + 1, type: getPauseType(token), message: replacement ? `替换为「${replacement}」。` : '移除重复标点。', }); lastIndex = match.index + token.length; } output += original.slice(lastIndex); return { line: output, findings }; } // 行内 HTML 注释区间(含 `` 本身);注释可跨行,未闭合时把状态交给下一行。 function htmlCommentSpans(line, openBefore) { const spans = []; let open = openBefore; let cursor = 0; while (cursor < line.length) { if (open) { const close = line.indexOf('-->', cursor); if (close === -1) { spans.push([cursor, line.length]); return { spans, open: true }; } spans.push([cursor, close + 3]); cursor = close + 3; open = false; continue; } const start = line.indexOf('