|
| 1 | +// remark-plusplus-ins.ts |
| 2 | +import type { Plugin } from 'unified'; |
| 3 | +import { SKIP, visit } from 'unist-util-visit'; |
| 4 | +import type { Visitor } from 'unist-util-visit'; |
| 5 | +import type { Parent, PhrasingContent, Text } from 'mdast'; |
| 6 | + |
| 7 | +/** |
| 8 | + * \S → first char must be non-whitespace |
| 9 | + * (?:...)?→ optional middle+closing when length > 1 |
| 10 | + * [\s\S]*?→ anything (including newlines), lazy |
| 11 | + * final \S→ last char non-whitespace (only required when there’s more than 1) |
| 12 | + * |
| 13 | + * Matches: |
| 14 | + * ++a++ |
| 15 | + * Does not match: |
| 16 | + * ++++ |
| 17 | + * ++ ++ |
| 18 | + */ |
| 19 | +const INS_REGEX = /\+\+(\S(?:[\s\S]*?\S)?)\+\+/g; |
| 20 | +const IGNORE_NODE_TYPES = new Set([ |
| 21 | + 'code', |
| 22 | + 'inlineCode', |
| 23 | + 'link', |
| 24 | + 'linkReference', |
| 25 | + 'definition', |
| 26 | + 'math', |
| 27 | + 'inlineMath', |
| 28 | +]); |
| 29 | + |
| 30 | +/** |
| 31 | + * Converts MD "++Some text++" to inserted text element rendered in HTML as <ins>Some text</ins> |
| 32 | + * https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/ins |
| 33 | + */ |
| 34 | +export const plusPlusToEmphasis: Plugin<[]> = () => { |
| 35 | + const visitor: Visitor = (node, index, parent) => { |
| 36 | + // 1) Don’t traverse inside ignored nodes |
| 37 | + if (IGNORE_NODE_TYPES.has(node.type)) return SKIP; |
| 38 | + |
| 39 | + // 2) Only transform text nodes with a valid parent + index |
| 40 | + if (node.type !== 'text' || parent == null || typeof index !== 'number') return; |
| 41 | + |
| 42 | + const value = (node as Text).value; |
| 43 | + |
| 44 | + // Reset lastIndex to 0 per node so each node is scanned from the beginning |
| 45 | + INS_REGEX.lastIndex = 0; |
| 46 | + |
| 47 | + let match: RegExpExecArray | null; |
| 48 | + let last = 0; |
| 49 | + const out: PhrasingContent[] = []; |
| 50 | + |
| 51 | + while ((match = INS_REGEX.exec(value))) { |
| 52 | + const [full, inner] = match; |
| 53 | + const start = match.index; |
| 54 | + |
| 55 | + if (start > last) out.push({ type: 'text', value: value.slice(last, start) }); |
| 56 | + |
| 57 | + // Render as <ins>…</ins> (remark-rehype respects data.hName) |
| 58 | + out.push({ |
| 59 | + children: [{ type: 'text', value: inner }], |
| 60 | + data: { hName: 'ins' }, |
| 61 | + type: 'emphasis', |
| 62 | + }); |
| 63 | + |
| 64 | + last = start + full.length; |
| 65 | + } |
| 66 | + |
| 67 | + if (out.length === 0) return; // nothing to change |
| 68 | + if (last < value.length) out.push({ type: 'text', value: value.slice(last) }); |
| 69 | + |
| 70 | + (parent as Parent).children.splice(index, 1, ...out); |
| 71 | + |
| 72 | + // Skip re-visiting the replaced range; continue after inserted nodes |
| 73 | + return [SKIP, index + out.length]; |
| 74 | + }; |
| 75 | + |
| 76 | + return (tree) => visit(tree, visitor); |
| 77 | +}; |
0 commit comments