|
| 1 | +import type { MarkupOptions } from '@md/shared' |
| 2 | +import type { MarkedExtension } from 'marked' |
| 3 | +import { getStyleString } from '../utils' |
| 4 | + |
| 5 | +/** |
| 6 | + * 扩展标记语法: |
| 7 | + * - 高亮: ==文本== |
| 8 | + * - 下划线: ++文本++ |
| 9 | + * - 波浪线: ~文本~ |
| 10 | + */ |
| 11 | +export function markedMarkup(options: MarkupOptions = {}): MarkedExtension { |
| 12 | + const { styles } = options |
| 13 | + |
| 14 | + return { |
| 15 | + extensions: [ |
| 16 | + // 高亮语法 ==文本== |
| 17 | + { |
| 18 | + name: `markup_highlight`, |
| 19 | + level: `inline`, |
| 20 | + start(src: string) { |
| 21 | + return src.match(/==(?!=)/)?.index |
| 22 | + }, |
| 23 | + tokenizer(src: string) { |
| 24 | + const rule = /^==((?:[^=]|=(?!=))+)==/ |
| 25 | + const match = rule.exec(src) |
| 26 | + if (match) { |
| 27 | + return { |
| 28 | + type: `markup_highlight`, |
| 29 | + raw: match[0], |
| 30 | + text: match[1], |
| 31 | + } |
| 32 | + } |
| 33 | + }, |
| 34 | + renderer(token: any) { |
| 35 | + const style = getStyleString(styles?.markup_highlight ?? {}) |
| 36 | + return `<span class="markup-highlight" style="${style}">${token.text}</span>` |
| 37 | + }, |
| 38 | + }, |
| 39 | + |
| 40 | + // 下划线语法 ++文本++ |
| 41 | + { |
| 42 | + name: `markup_underline`, |
| 43 | + level: `inline`, |
| 44 | + start(src: string) { |
| 45 | + return src.match(/\+\+(?!\+)/)?.index |
| 46 | + }, |
| 47 | + tokenizer(src: string) { |
| 48 | + const rule = /^\+\+((?:[^+]|\+(?!\+))+)\+\+/ |
| 49 | + const match = rule.exec(src) |
| 50 | + if (match) { |
| 51 | + return { |
| 52 | + type: `markup_underline`, |
| 53 | + raw: match[0], |
| 54 | + text: match[1], |
| 55 | + } |
| 56 | + } |
| 57 | + }, |
| 58 | + renderer(token: any) { |
| 59 | + const style = getStyleString(styles?.markup_underline ?? {}) |
| 60 | + return `<span class="markup-underline" style="${style}">${token.text}</span>` |
| 61 | + }, |
| 62 | + }, |
| 63 | + |
| 64 | + // 波浪线语法 ~文本~ |
| 65 | + { |
| 66 | + name: `markup_wavyline`, |
| 67 | + level: `inline`, |
| 68 | + start(src: string) { |
| 69 | + // 查找单个 ~ 但不是连续的 ~~ |
| 70 | + return src.match(/~(?!~)/)?.index |
| 71 | + }, |
| 72 | + tokenizer(src: string) { |
| 73 | + // 匹配 ~文本~ 但确保不是 ~~文本~~ |
| 74 | + const rule = /^~([^~\n]+)~(?!~)/ |
| 75 | + const match = rule.exec(src) |
| 76 | + if (match) { |
| 77 | + return { |
| 78 | + type: `markup_wavyline`, |
| 79 | + raw: match[0], |
| 80 | + text: match[1], |
| 81 | + } |
| 82 | + } |
| 83 | + }, |
| 84 | + renderer(token: any) { |
| 85 | + const style = getStyleString(styles?.markup_wavyline ?? {}) |
| 86 | + return `<span class="markup-wavyline" style="${style}">${token.text}</span>` |
| 87 | + }, |
| 88 | + }, |
| 89 | + ], |
| 90 | + } |
| 91 | +} |
0 commit comments