File size: 15,293 Bytes
f462b1c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 | // ══════════════════════════════════════════════════════════════════════════════
// Markdown Syntax Dictionary
// Complete Markdown syntax patterns and recognition rules
// ══════════════════════════════════════════════════════════════════════════════
/**
* Markdown Syntax Dictionary
* Based on CommonMark + GitHub Flavored Markdown (GFM)
*/
export const MarkdownSyntax = {
// ════════════════════════════════════════════════════════════════════════════
// Block-level Elements
// ════════════════════════════════════════════════════════════════════════════
blocks: {
// Headings: # H1, ## H2, ### H3, #### H4, ##### H5, ###### H6
heading: {
patterns: [
/^(#{1,6})\s+(.+)$/, // ATX style: # Heading
/^(.+)\n={3,}\s*$/, // Setext H1: underline with ===
/^(.+)\n-{3,}\s*$/ // Setext H2: underline with ---
],
detect: (line, nextLine) => {
// ATX headings
const atx = line.match(/^(#{1,6})\s+(.+)$/);
if (atx) {
return {
type: 'heading',
level: atx[1].length,
content: atx[2].trim(),
style: 'atx'
};
}
// Setext headings (require next line)
if (nextLine) {
if (nextLine.match(/^={3,}\s*$/)) {
return { type: 'heading', level: 1, content: line.trim(), style: 'setext' };
}
if (nextLine.match(/^-{3,}\s*$/) && !line.match(/^\s*$/)) {
return { type: 'heading', level: 2, content: line.trim(), style: 'setext' };
}
}
return null;
}
},
// Horizontal Rules: ---, ***, ___
hr: {
patterns: [
/^-{3,}\s*$/,
/^\*{3,}\s*$/,
/^_{3,}\s*$/,
/^- {0,2}- {0,2}-/,
/^\* {0,2}\* {0,2}\*/,
/^_ {0,2}_ {0,2}_/
],
detect: (line) => {
for (const pattern of MarkdownSyntax.blocks.hr.patterns) {
if (pattern.test(line.trim())) {
return { type: 'hr' };
}
}
return null;
}
},
// Code Blocks: ```lang or indented 4 spaces
codeBlock: {
patterns: [
/^```(\w*)\s*$/, // Fenced code block start
/^~~~(\w*)\s*$/, // Alternative fence
/^ (.+)$/, // Indented code (4 spaces)
/^\t(.+)$/ // Indented code (tab)
],
detect: (line) => {
// Fenced code block
const fenced = line.match(/^```(\w*)\s*$/);
if (fenced) {
return { type: 'code-fence-start', language: fenced[1] || 'text' };
}
const tilde = line.match(/^~~~(\w*)\s*$/);
if (tilde) {
return { type: 'code-fence-start', language: tilde[1] || 'text', fence: '~~~' };
}
// Indented code
if (line.match(/^ (.+)$/) || line.match(/^\t(.+)$/)) {
return { type: 'code-indented', content: line.replace(/^ |\t/, '') };
}
return null;
}
},
// Blockquotes: > Quote
blockquote: {
patterns: [
/^>\s?(.*)$/, // > Quote
/^> ?> ?(.*)$/ // Nested: >> Quote
],
detect: (line) => {
const match = line.match(/^(>+)\s?(.*)$/);
if (match) {
return {
type: 'blockquote',
level: match[1].length,
content: match[2]
};
}
return null;
}
},
// Lists: Unordered (-, *, +) and Ordered (1., 2.)
list: {
patterns: [
/^(\s*)([-*+])\s+(.+)$/, // Unordered: -, *, +
/^(\s*)(\d{1,9})[.)]\s+(.+)$/ // Ordered: 1., 2), etc.
],
detect: (line) => {
// Unordered list
const unordered = line.match(/^(\s*)([-*+])\s+(.+)$/);
if (unordered) {
return {
type: 'list',
ordered: false,
indent: unordered[1].length,
marker: unordered[2],
content: unordered[3]
};
}
// Ordered list
const ordered = line.match(/^(\s*)(\d{1,9})[.)]\s+(.+)$/);
if (ordered) {
return {
type: 'list',
ordered: true,
indent: ordered[1].length,
number: parseInt(ordered[2]),
content: ordered[3]
};
}
return null;
}
},
// Task Lists (GFM): - [ ] Task or - [x] Done
taskList: {
patterns: [
/^(\s*)([-*+])\s+\[([ xX])\]\s+(.+)$/
],
detect: (line) => {
const match = line.match(/^(\s*)([-*+])\s+\[([ xX])\]\s+(.+)$/);
if (match) {
return {
type: 'task-list',
indent: match[1].length,
checked: match[3].toLowerCase() === 'x',
content: match[4]
};
}
return null;
}
},
// Tables (GFM): | Header | Header |
table: {
patterns: [
/^\|(.+)\|$/, // Table row
/^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?$/ // Separator
],
detect: (line) => {
if (line.match(/^\|(.+)\|$/)) {
return { type: 'table-row', cells: line.split('|').filter(c => c.trim()) };
}
if (line.match(/^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?$/)) {
return { type: 'table-separator' };
}
return null;
}
},
// HTML Blocks: <div>, <!-- comment -->
html: {
patterns: [
/^<([a-z][a-z0-9-]*)\b[^>]*>/i, // Opening tag
/^<\/([a-z][a-z0-9-]*)\s*>/i, // Closing tag
/^<!--/, // Comment start
/^<\?/, // Processing instruction
/^<![A-Z]/, // Declaration
/^<!\[CDATA\[/ // CDATA section
],
detect: (line) => {
for (const pattern of MarkdownSyntax.blocks.html.patterns) {
if (pattern.test(line.trim())) {
return { type: 'html', content: line };
}
}
return null;
}
},
// Metadata blocks (YAML frontmatter, TOML, JSON)
metadata: {
patterns: [
/^---\s*$/, // YAML
/^\+\+\+\s*$/, // TOML
/^;;;\s*$/ // JSON (some parsers)
],
detect: (line) => {
if (line.trim() === '---') return { type: 'metadata', format: 'yaml' };
if (line.trim() === '+++') return { type: 'metadata', format: 'toml' };
if (line.trim() === ';;;') return { type: 'metadata', format: 'json' };
return null;
}
}
},
// ════════════════════════════════════════════════════════════════════════════
// Inline Elements
// ════════════════════════════════════════════════════════════════════════════
inline: {
// Emphasis: *italic*, _italic_, **bold**, __bold__, ***bold italic***
emphasis: {
patterns: [
{ regex: /\*\*\*(.+?)\*\*\*/g, type: 'bold-italic', tag: 'strong-em' },
{ regex: /___(.+?)___/g, type: 'bold-italic', tag: 'strong-em' },
{ regex: /\*\*(.+?)\*\*/g, type: 'bold', tag: 'strong' },
{ regex: /__(.+?)__/g, type: 'bold', tag: 'strong' },
{ regex: /\*(.+?)\*/g, type: 'italic', tag: 'em' },
{ regex: /_(.+?)_/g, type: 'italic', tag: 'em' }
]
},
// Strikethrough (GFM): ~~deleted~~
strikethrough: {
patterns: [
{ regex: /~~(.+?)~~/g, type: 'strikethrough', tag: 'del' }
]
},
// Code: `inline code`
code: {
patterns: [
{ regex: /``(.+?)``/g, type: 'code', tag: 'code' }, // Double backtick
{ regex: /`(.+?)`/g, type: 'code', tag: 'code' } // Single backtick
]
},
// Links: [text](url "title"), [text][ref], <url>
link: {
patterns: [
{ regex: /\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, type: 'link' }, // Inline
{ regex: /\[([^\]]+)\]\[([^\]]+)\]/g, type: 'link-ref' }, // Reference
{ regex: /\[([^\]]+)\]/g, type: 'link-shortcut' }, // Shortcut
{ regex: /<(https?:\/\/[^>]+)>/g, type: 'autolink' }, // Autolink
{ regex: /<([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})>/g, type: 'email' } // Email
]
},
// Images: , ![alt][ref]
image: {
patterns: [
{ regex: /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, type: 'image' }, // Inline
{ regex: /!\[([^\]]*)\]\[([^\]]+)\]/g, type: 'image-ref' } // Reference
]
},
// Line breaks: two spaces + newline, backslash + newline, <br>
lineBreak: {
patterns: [
{ regex: / \n/g, type: 'soft-break' },
{ regex: /\\\n/g, type: 'hard-break' },
{ regex: /<br\s*\/?>/gi, type: 'html-break' }
]
},
// Escape sequences: \*, \[, etc.
escape: {
characters: ['\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '#', '+', '-', '.', '!', '|']
},
// Emoji (GFM): :smile:, :heart:
emoji: {
pattern: /:([a-z0-9_+-]+):/g
},
// Mentions (GFM): @username
mention: {
pattern: /@([a-zA-Z0-9_-]+)/g
},
// Hashtags: #tag
hashtag: {
pattern: /#([a-zA-Z0-9_-]+)/g
}
},
// ════════════════════════════════════════════════════════════════════════════
// Special Constructs
// ════════════════════════════════════════════════════════════════════════════
special: {
// Footnotes: [^1], [^note]
footnote: {
definition: /^\[\^([^\]]+)\]:\s+(.+)$/,
reference: /\[\^([^\]]+)\]/g
},
// Abbreviations: *[HTML]: Hyper Text Markup Language
abbreviation: {
pattern: /^\*\[([^\]]+)\]:\s+(.+)$/
},
// Definition lists:
// Term
// : Definition
definitionList: {
term: /^([^\n:]+)\s*$/,
definition: /^:\s+(.+)$/
},
// Math (KaTeX/MathJax): $inline$, $$block$$
math: {
inline: /\$([^$]+)\$/g,
block: /\$\$([^$]+)\$\$/g
}
}
};
/**
* Check if a line matches any block-level syntax
*/
export function detectBlockType(line, nextLine = null) {
// Check each block type
for (const [blockName, block] of Object.entries(MarkdownSyntax.blocks)) {
const result = block.detect(line, nextLine);
if (result) {
return result;
}
}
return { type: 'paragraph' };
}
/**
* Parse inline markdown syntax
*/
function escapeHtml(str) {
if (str == null) return '';
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
export function parseInline(text) {
if (!text) return '';
let result = escapeHtml(text);
// Images (handle before links so the leading ! is preserved)
result = result.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, (match, alt, url, title) => {
const altAttr = escapeHtml(alt || '');
const srcAttr = escapeHtml(url || '');
const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
return `<img src="${srcAttr}" alt="${altAttr}"${titleAttr}>`;
});
// Inline links [text](url "title")
result = result.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, (match, label, url, title) => {
const textContent = escapeHtml(label || '');
const hrefAttr = escapeHtml(url || '#');
const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
return `<a href="${hrefAttr}"${titleAttr}>${textContent}</a>`;
});
// Autolinks <https://example.com>
result = result.replace(/<(https?:\/\/[^&]+)>/g, (match, url) => {
const hrefAttr = escapeHtml(url);
return `<a href="${hrefAttr}">${hrefAttr}</a>`;
});
// Email autolinks <user@example.com>
result = result.replace(/<([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})>/g, (match, email) => {
const mailto = `mailto:${email}`;
return `<a href="${escapeHtml(mailto)}">${escapeHtml(email)}</a>`;
});
// Emphasis and code (process complex patterns first)
const replacements = [
{ regex: /\*\*\*(.+?)\*\*\*/g, wrap: content => `<strong><em>${content}</em></strong>` },
{ regex: /___(.+?)___/g, wrap: content => `<strong><em>${content}</em></strong>` },
{ regex: /\*\*(.+?)\*\*/g, wrap: content => `<strong>${content}</strong>` },
{ regex: /__(.+?)__/g, wrap: content => `<strong>${content}</strong>` },
{ regex: /\*(.+?)\*/g, wrap: content => `<em>${content}</em>` },
{ regex: /_(.+?)_/g, wrap: content => `<em>${content}</em>` },
{ regex: /~~(.+?)~~/g, wrap: content => `<del>${content}</del>` },
{ regex: /``(.+?)``/g, wrap: content => `<code>${content}</code>` },
{ regex: /`(.+?)`/g, wrap: content => `<code>${content}</code>` }
];
replacements.forEach(({ regex, wrap }) => {
result = result.replace(regex, (match, content) => wrap(content));
});
// Line breaks
result = result.replace(/ \n/g, '<br>');
result = result.replace(/\\\n/g, '<br>');
result = result.replace(/<br\s*\/?>/gi, '<br>');
return result;
}
/**
* Get syntax info for documentation
*/
export function getSyntaxInfo(category) {
const info = {
blocks: 'Block-level elements (headings, lists, code blocks, etc.)',
inline: 'Inline elements (emphasis, links, images, etc.)',
special: 'Special constructs (footnotes, math, definitions, etc.)'
};
return info[category] || 'Unknown category';
}
|