2 * marked v14.1.3 - a markdown parser
3 * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed)
4 * https://github.com/markedjs/marked
8 * DO NOT EDIT THIS FILE
9 * The code in this file is generated from files in ./src/
12(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
14 typeof define === 'function' && define.amd ? define(['exports'], factory) :
15 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.marked = {}));
16})(this, (function (exports) { 'use strict';
19 * Gets the original marked default options.
21 function _getDefaults() {
35 exports.defaults = _getDefaults();
36 function changeDefaults(newDefaults) {
37 exports.defaults = newDefaults;
43 const escapeTest = /[&<>"']/;
44 const escapeReplace = new RegExp(escapeTest.source, 'g');
45 const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
46 const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');
47 const escapeReplacements = {
54 const getEscapeReplacement = (ch) => escapeReplacements[ch];
55 function escape$1(html, encode) {
57 if (escapeTest.test(html)) {
58 return html.replace(escapeReplace, getEscapeReplacement);
62 if (escapeTestNoEncode.test(html)) {
63 return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
68 const caret = /(^|[^\[])\^/g;
69 function edit(regex, opt) {
70 let source = typeof regex === 'string' ? regex : regex.source;
73 replace: (name, val) => {
74 let valSource = typeof val === 'string' ? val : val.source;
75 valSource = valSource.replace(caret, '$1');
76 source = source.replace(name, valSource);
80 return new RegExp(source, opt);
85 function cleanUrl(href) {
87 href = encodeURI(href).replace(/%25/g, '%');
94 const noopTest = { exec: () => null };
95 function splitCells(tableRow, count) {
96 // ensure that every cell-delimiting pipe has a space
97 // before it to distinguish it from an escaped pipe
98 const row = tableRow.replace(/\|/g, (match, offset, str) => {
101 while (--curr >= 0 && str[curr] === '\\')
104 // odd number of slashes means | is escaped
105 // so we leave it alone
109 // add space before unescaped |
112 }), cells = row.split(/ \|/);
114 // First/last cell in a row cannot be empty if it has no leading/trailing pipe
115 if (!cells[0].trim()) {
118 if (cells.length > 0 && !cells[cells.length - 1].trim()) {
122 if (cells.length > count) {
126 while (cells.length < count)
130 for (; i < cells.length; i++) {
131 // leading or trailing whitespace is ignored per the gfm spec
132 cells[i] = cells[i].trim().replace(/\\\|/g, '|');
137 * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
138 * /c*$/ is vulnerable to REDOS.
142 * @param invert Remove suffix of non-c chars instead. Default falsey.
144 function rtrim(str, c, invert) {
145 const l = str.length;
149 // Length of suffix matching the invert condition.
151 // Step left until we fail to match the invert condition.
152 while (suffLen < l) {
153 const currChar = str.charAt(l - suffLen - 1);
154 if (currChar === c && !invert) {
157 else if (currChar !== c && invert) {
164 return str.slice(0, l - suffLen);
166 function findClosingBracket(str, b) {
167 if (str.indexOf(b[1]) === -1) {
171 for (let i = 0; i < str.length; i++) {
172 if (str[i] === '\\') {
175 else if (str[i] === b[0]) {
178 else if (str[i] === b[1]) {
188 function outputLink(cap, link, raw, lexer) {
189 const href = link.href;
190 const title = link.title ? escape$1(link.title) : null;
191 const text = cap[1].replace(/\\([\[\]])/g, '$1');
192 if (cap[0].charAt(0) !== '!') {
193 lexer.state.inLink = true;
200 tokens: lexer.inlineTokens(text),
202 lexer.state.inLink = false;
210 text: escape$1(text),
213 function indentCodeCompensation(raw, text) {
214 const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
215 if (matchIndentToCode === null) {
218 const indentToCode = matchIndentToCode[1];
222 const matchIndentInNode = node.match(/^\s+/);
223 if (matchIndentInNode === null) {
226 const [indentInNode] = matchIndentInNode;
227 if (indentInNode.length >= indentToCode.length) {
228 return node.slice(indentToCode.length);
239 rules; // set by the lexer
240 lexer; // set by the lexer
241 constructor(options) {
242 this.options = options || exports.defaults;
245 const cap = this.rules.block.newline.exec(src);
246 if (cap && cap[0].length > 0) {
254 const cap = this.rules.block.code.exec(src);
256 const text = cap[0].replace(/^(?: {1,4}| {0,3}\t)/gm, '');
260 codeBlockStyle: 'indented',
261 text: !this.options.pedantic
268 const cap = this.rules.block.fences.exec(src);
271 const text = indentCodeCompensation(raw, cap[3] || '');
275 lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],
281 const cap = this.rules.block.heading.exec(src);
283 let text = cap[2].trim();
284 // remove trailing #s
285 if (/#$/.test(text)) {
286 const trimmed = rtrim(text, '#');
287 if (this.options.pedantic) {
288 text = trimmed.trim();
290 else if (!trimmed || / $/.test(trimmed)) {
291 // CommonMark requires space before trailing #s
292 text = trimmed.trim();
298 depth: cap[1].length,
300 tokens: this.lexer.inline(text),
305 const cap = this.rules.block.hr.exec(src);
309 raw: rtrim(cap[0], '\n'),
314 const cap = this.rules.block.blockquote.exec(src);
316 let lines = rtrim(cap[0], '\n').split('\n');
320 while (lines.length > 0) {
321 let inBlockquote = false;
322 const currentLines = [];
324 for (i = 0; i < lines.length; i++) {
325 // get lines up to a continuation
326 if (/^ {0,3}>/.test(lines[i])) {
327 currentLines.push(lines[i]);
330 else if (!inBlockquote) {
331 currentLines.push(lines[i]);
337 lines = lines.slice(i);
338 const currentRaw = currentLines.join('\n');
339 const currentText = currentRaw
340 // precede setext continuation with 4 spaces so it isn't a setext
341 .replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, '\n $1')
342 .replace(/^ {0,3}>[ \t]?/gm, '');
343 raw = raw ? `${raw}\n${currentRaw}` : currentRaw;
344 text = text ? `${text}\n${currentText}` : currentText;
345 // parse blockquote lines as top level tokens
346 // merge paragraphs if this is a continuation
347 const top = this.lexer.state.top;
348 this.lexer.state.top = true;
349 this.lexer.blockTokens(currentText, tokens, true);
350 this.lexer.state.top = top;
351 // if there is no continuation then we are done
352 if (lines.length === 0) {
355 const lastToken = tokens[tokens.length - 1];
356 if (lastToken?.type === 'code') {
357 // blockquote continuation cannot be preceded by a code block
360 else if (lastToken?.type === 'blockquote') {
361 // include continuation in nested blockquote
362 const oldToken = lastToken;
363 const newText = oldToken.raw + '\n' + lines.join('\n');
364 const newToken = this.blockquote(newText);
365 tokens[tokens.length - 1] = newToken;
366 raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
367 text = text.substring(0, text.length - oldToken.text.length) + newToken.text;
370 else if (lastToken?.type === 'list') {
371 // include continuation in nested list
372 const oldToken = lastToken;
373 const newText = oldToken.raw + '\n' + lines.join('\n');
374 const newToken = this.list(newText);
375 tokens[tokens.length - 1] = newToken;
376 raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
377 text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;
378 lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\n');
391 let cap = this.rules.block.list.exec(src);
393 let bull = cap[1].trim();
394 const isordered = bull.length > 1;
399 start: isordered ? +bull.slice(0, -1) : '',
403 bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
404 if (this.options.pedantic) {
405 bull = isordered ? bull : '[*+-]';
407 // Get next list item
408 const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`);
409 let endsWithBlankLine = false;
410 // Check if current bullet point can start a new List Item
412 let endEarly = false;
414 let itemContents = '';
415 if (!(cap = itemRegex.exec(src))) {
418 if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)
422 src = src.substring(raw.length);
423 let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t) => ' '.repeat(3 * t.length));
424 let nextLine = src.split('\n', 1)[0];
425 let blankLine = !line.trim();
427 if (this.options.pedantic) {
429 itemContents = line.trimStart();
431 else if (blankLine) {
432 indent = cap[1].length + 1;
435 indent = cap[2].search(/[^ ]/); // Find first non-space char
436 indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent
437 itemContents = line.slice(indent);
438 indent += cap[1].length;
440 if (blankLine && /^[ \t]*$/.test(nextLine)) { // Items begin with at most one blank line
441 raw += nextLine + '\n';
442 src = src.substring(nextLine.length + 1);
446 const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`);
447 const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
448 const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
449 const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
450 const htmlBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}<[a-z].*>`, 'i');
451 // Check if following lines should be included in List Item
453 const rawLine = src.split('\n', 1)[0];
454 let nextLineWithoutTabs;
456 // Re-align to follow commonmark nesting rules
457 if (this.options.pedantic) {
458 nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' ');
459 nextLineWithoutTabs = nextLine;
462 nextLineWithoutTabs = nextLine.replace(/\t/g, ' ');
464 // End list item if found code fences
465 if (fencesBeginRegex.test(nextLine)) {
468 // End list item if found start of new heading
469 if (headingBeginRegex.test(nextLine)) {
472 // End list item if found start of html block
473 if (htmlBeginRegex.test(nextLine)) {
476 // End list item if found start of new bullet
477 if (nextBulletRegex.test(nextLine)) {
480 // Horizontal rule found
481 if (hrRegex.test(nextLine)) {
484 if (nextLineWithoutTabs.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible
485 itemContents += '\n' + nextLineWithoutTabs.slice(indent);
488 // not enough indentation
492 // paragraph continuation unless last line was a different block level element
493 if (line.replace(/\t/g, ' ').search(/[^ ]/) >= 4) { // indented code block
496 if (fencesBeginRegex.test(line)) {
499 if (headingBeginRegex.test(line)) {
502 if (hrRegex.test(line)) {
505 itemContents += '\n' + nextLine;
507 if (!blankLine && !nextLine.trim()) { // Check if current line is blank
510 raw += rawLine + '\n';
511 src = src.substring(rawLine.length + 1);
512 line = nextLineWithoutTabs.slice(indent);
516 // If the previous item ended with a blank line, the list is loose
517 if (endsWithBlankLine) {
520 else if (/\n[ \t]*\n[ \t]*$/.test(raw)) {
521 endsWithBlankLine = true;
526 // Check for task list items
527 if (this.options.gfm) {
528 istask = /^\[[ xX]\] /.exec(itemContents);
530 ischecked = istask[0] !== '[ ] ';
531 itemContents = itemContents.replace(/^\[[ xX]\] +/, '');
545 // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic
546 list.items[list.items.length - 1].raw = list.items[list.items.length - 1].raw.trimEnd();
547 list.items[list.items.length - 1].text = list.items[list.items.length - 1].text.trimEnd();
548 list.raw = list.raw.trimEnd();
549 // Item child tokens handled here at end because we needed to have the final item to trim it first
550 for (let i = 0; i < list.items.length; i++) {
551 this.lexer.state.top = false;
552 list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);
554 // Check if list should be loose
555 const spacers = list.items[i].tokens.filter(t => t.type === 'space');
556 const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\n.*\n/.test(t.raw));
557 list.loose = hasMultipleLineBreaks;
560 // Set all items to loose if list is loose
562 for (let i = 0; i < list.items.length; i++) {
563 list.items[i].loose = true;
570 const cap = this.rules.block.html.exec(src);
576 pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',
583 const cap = this.rules.block.def.exec(src);
585 const tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
586 const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';
587 const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];
598 const cap = this.rules.block.table.exec(src);
602 if (!/[:|]/.test(cap[2])) {
603 // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading
606 const headers = splitCells(cap[1]);
607 const aligns = cap[2].replace(/^\||\| *$/g, '').split('|');
608 const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : [];
616 if (headers.length !== aligns.length) {
617 // header and align columns must be equal, rows can be different.
620 for (const align of aligns) {
621 if (/^ *-+: *$/.test(align)) {
622 item.align.push('right');
624 else if (/^ *:-+: *$/.test(align)) {
625 item.align.push('center');
627 else if (/^ *:-+ *$/.test(align)) {
628 item.align.push('left');
631 item.align.push(null);
634 for (let i = 0; i < headers.length; i++) {
637 tokens: this.lexer.inline(headers[i]),
639 align: item.align[i],
642 for (const row of rows) {
643 item.rows.push(splitCells(row, item.header.length).map((cell, i) => {
646 tokens: this.lexer.inline(cell),
648 align: item.align[i],
655 const cap = this.rules.block.lheading.exec(src);
660 depth: cap[2].charAt(0) === '=' ? 1 : 2,
662 tokens: this.lexer.inline(cap[1]),
667 const cap = this.rules.block.paragraph.exec(src);
669 const text = cap[1].charAt(cap[1].length - 1) === '\n'
670 ? cap[1].slice(0, -1)
676 tokens: this.lexer.inline(text),
681 const cap = this.rules.block.text.exec(src);
687 tokens: this.lexer.inline(cap[0]),
692 const cap = this.rules.inline.escape.exec(src);
697 text: escape$1(cap[1]),
702 const cap = this.rules.inline.tag.exec(src);
704 if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
705 this.lexer.state.inLink = true;
707 else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
708 this.lexer.state.inLink = false;
710 if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
711 this.lexer.state.inRawBlock = true;
713 else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
714 this.lexer.state.inRawBlock = false;
719 inLink: this.lexer.state.inLink,
720 inRawBlock: this.lexer.state.inRawBlock,
727 const cap = this.rules.inline.link.exec(src);
729 const trimmedUrl = cap[2].trim();
730 if (!this.options.pedantic && /^</.test(trimmedUrl)) {
731 // commonmark requires matching angle brackets
732 if (!(/>$/.test(trimmedUrl))) {
735 // ending angle bracket cannot be escaped
736 const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\');
737 if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
742 // find closing parenthesis
743 const lastParenIndex = findClosingBracket(cap[2], '()');
744 if (lastParenIndex > -1) {
745 const start = cap[0].indexOf('!') === 0 ? 5 : 4;
746 const linkLen = start + cap[1].length + lastParenIndex;
747 cap[2] = cap[2].substring(0, lastParenIndex);
748 cap[0] = cap[0].substring(0, linkLen).trim();
754 if (this.options.pedantic) {
755 // split pedantic href and title
756 const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
763 title = cap[3] ? cap[3].slice(1, -1) : '';
766 if (/^</.test(href)) {
767 if (this.options.pedantic && !(/>$/.test(trimmedUrl))) {
768 // pedantic allows starting angle bracket without ending angle bracket
769 href = href.slice(1);
772 href = href.slice(1, -1);
775 return outputLink(cap, {
776 href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,
777 title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,
778 }, cap[0], this.lexer);
781 reflink(src, links) {
783 if ((cap = this.rules.inline.reflink.exec(src))
784 || (cap = this.rules.inline.nolink.exec(src))) {
785 const linkString = (cap[2] || cap[1]).replace(/\s+/g, ' ');
786 const link = links[linkString.toLowerCase()];
788 const text = cap[0].charAt(0);
795 return outputLink(cap, link, cap[0], this.lexer);
798 emStrong(src, maskedSrc, prevChar = '') {
799 let match = this.rules.inline.emStrongLDelim.exec(src);
802 // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well
803 if (match[3] && prevChar.match(/[\p{L}\p{N}]/u))
805 const nextChar = match[1] || match[2] || '';
806 if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
807 // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)
808 const lLength = [...match[0]].length - 1;
809 let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
810 const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
811 endReg.lastIndex = 0;
812 // Clip maskedSrc to same section of string as src (move to lexer?)
813 maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
814 while ((match = endReg.exec(maskedSrc)) != null) {
815 rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
817 continue; // skip single * in __abc*abc__
818 rLength = [...rDelim].length;
819 if (match[3] || match[4]) { // found another Left Delim
820 delimTotal += rLength;
823 else if (match[5] || match[6]) { // either Left or Right Delim
824 if (lLength % 3 && !((lLength + rLength) % 3)) {
825 midDelimTotal += rLength;
826 continue; // CommonMark Emphasis Rules 9-10
829 delimTotal -= rLength;
831 continue; // Haven't found enough closing delimiters
832 // Remove extra characters. *a*** -> *a*
833 rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
834 // char length can be >1 for unicode characters;
835 const lastCharLength = [...match[0]][0].length;
836 const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);
837 // Create `em` if smallest delimiter has odd char count. *a***
838 if (Math.min(lLength, rLength) % 2) {
839 const text = raw.slice(1, -1);
844 tokens: this.lexer.inlineTokens(text),
847 // Create 'strong' if smallest delimiter has even char count. **a***
848 const text = raw.slice(2, -2);
853 tokens: this.lexer.inlineTokens(text),
859 const cap = this.rules.inline.code.exec(src);
861 let text = cap[2].replace(/\n/g, ' ');
862 const hasNonSpaceChars = /[^ ]/.test(text);
863 const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);
864 if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
865 text = text.substring(1, text.length - 1);
867 text = escape$1(text, true);
876 const cap = this.rules.inline.br.exec(src);
885 const cap = this.rules.inline.del.exec(src);
891 tokens: this.lexer.inlineTokens(cap[2]),
896 const cap = this.rules.inline.autolink.exec(src);
899 if (cap[2] === '@') {
900 text = escape$1(cap[1]);
901 href = 'mailto:' + text;
904 text = escape$1(cap[1]);
924 if (cap = this.rules.inline.url.exec(src)) {
926 if (cap[2] === '@') {
927 text = escape$1(cap[0]);
928 href = 'mailto:' + text;
931 // do extended autolink path validation
934 prevCapZero = cap[0];
935 cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';
936 } while (prevCapZero !== cap[0]);
937 text = escape$1(cap[0]);
938 if (cap[1] === 'www.') {
939 href = 'http://' + cap[0];
961 const cap = this.rules.inline.text.exec(src);
964 if (this.lexer.state.inRawBlock) {
968 text = escape$1(cap[0]);
980 * Block-Level Grammar
982 const newline = /^(?:[ \t]*(?:\n|$))+/;
983 const blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
984 const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
985 const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
986 const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
987 const bullet = /(?:[*+-]|\d{1,9}[.)])/;
988 const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/)
989 .replace(/bull/g, bullet) // lists can interrupt
990 .replace(/blockCode/g, /(?: {4}| {0,3}\t)/) // indented code blocks can interrupt
991 .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt
992 .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt
993 .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt
994 .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt
996 const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
997 const blockText = /^[^\n]+/;
998 const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
999 const def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/)
1000 .replace('label', _blockLabel)
1001 .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/)
1003 const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/)
1004 .replace(/bull/g, bullet)
1006 const _tag = 'address|article|aside|base|basefont|blockquote|body|caption'
1007 + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
1008 + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
1009 + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
1010 + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'
1012 const _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
1013 const html = edit('^ {0,3}(?:' // optional indentation
1014 + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
1015 + '|comment[^\\n]*(\\n+|$)' // (2)
1016 + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3)
1017 + '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4)
1018 + '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5)
1019 + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (6)
1020 + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) open tag
1021 + '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) closing tag
1023 .replace('comment', _comment)
1024 .replace('tag', _tag)
1025 .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
1027 const paragraph = edit(_paragraph)
1029 .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
1030 .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs
1031 .replace('|table', '')
1032 .replace('blockquote', ' {0,3}>')
1033 .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
1034 .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
1035 .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
1036 .replace('tag', _tag) // pars can be interrupted by type (6) html blocks
1038 const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/)
1039 .replace('paragraph', paragraph)
1042 * Normal Block Grammar
1044 const blockNormal = {
1062 const gfmTable = edit('^ *([^\\n ].*)\\n' // Header
1063 + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align
1064 + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells
1066 .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
1067 .replace('blockquote', ' {0,3}>')
1068 .replace('code', '(?: {4}| {0,3}\t)[^\\n]')
1069 .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
1070 .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
1071 .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
1072 .replace('tag', _tag) // tables can be interrupted by type (6) html blocks
1077 paragraph: edit(_paragraph)
1079 .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
1080 .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs
1081 .replace('table', gfmTable) // interrupt paragraphs with table
1082 .replace('blockquote', ' {0,3}>')
1083 .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
1084 .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
1085 .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
1086 .replace('tag', _tag) // pars can be interrupted by type (6) html blocks
1090 * Pedantic grammar (original John Gruber's loose markdown specification)
1092 const blockPedantic = {
1094 html: edit('^ *(?:comment *(?:\\n|\\s*$)'
1095 + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
1096 + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
1097 .replace('comment', _comment)
1098 .replace(/tag/g, '(?!(?:'
1099 + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
1100 + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
1101 + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b')
1103 def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
1104 heading: /^(#{1,6})(.*)(?:\n+|$)/,
1105 fences: noopTest, // fences not supported
1106 lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
1107 paragraph: edit(_paragraph)
1109 .replace('heading', ' *#{1,6} *[^\n]')
1110 .replace('lheading', lheading)
1111 .replace('|table', '')
1112 .replace('blockquote', ' {0,3}>')
1113 .replace('|fences', '')
1114 .replace('|list', '')
1115 .replace('|html', '')
1116 .replace('|tag', '')
1120 * Inline-Level Grammar
1122 const escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
1123 const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
1124 const br = /^( {2,}|\\)\n(?!\s*$)/;
1125 const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
1126 // list of unicode punctuation marks, plus any missing characters from CommonMark spec
1127 const _punctuation = '\\p{P}\\p{S}';
1128 const punctuation = edit(/^((?![*_])[\spunctuation])/, 'u')
1129 .replace(/punctuation/g, _punctuation).getRegex();
1130 // sequences em should skip over [title](link), `code`, <html>
1131 const blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g;
1132 const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, 'u')
1133 .replace(/punct/g, _punctuation)
1135 const emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong
1136 + '|[^*]+(?=[^*])' // Consume to delim
1137 + '|(?!\\*)[punct](\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter
1138 + '|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter
1139 + '|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])' // (3) #***a, ***a can only be Left Delimiter
1140 + '|[\\s](\\*+)(?!\\*)(?=[punct])' // (4) ***# can only be Left Delimiter
1141 + '|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter
1142 + '|[^punct\\s](\\*+)(?=[^punct\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter
1143 .replace(/punct/g, _punctuation)
1145 // (6) Not allowed for _
1146 const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong
1147 + '|[^_]+(?=[^_])' // Consume to delim
1148 + '|(?!_)[punct](_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter
1149 + '|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter
1150 + '|(?!_)[punct\\s](_+)(?=[^punct\\s])' // (3) #___a, ___a can only be Left Delimiter
1151 + '|[\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter
1152 + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter
1153 .replace(/punct/g, _punctuation)
1155 const anyPunctuation = edit(/\\([punct])/, 'gu')
1156 .replace(/punct/g, _punctuation)
1158 const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/)
1159 .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)
1160 .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)
1162 const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();
1163 const tag = edit('^comment'
1164 + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
1165 + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
1166 + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
1167 + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
1168 + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>') // CDATA section
1169 .replace('comment', _inlineComment)
1170 .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/)
1172 const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
1173 const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/)
1174 .replace('label', _inlineLabel)
1175 .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/)
1176 .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/)
1178 const reflink = edit(/^!?\[(label)\]\[(ref)\]/)
1179 .replace('label', _inlineLabel)
1180 .replace('ref', _blockLabel)
1182 const nolink = edit(/^!?\[(ref)\](?:\[\])?/)
1183 .replace('ref', _blockLabel)
1185 const reflinkSearch = edit('reflink|nolink(?!\\()', 'g')
1186 .replace('reflink', reflink)
1187 .replace('nolink', nolink)
1190 * Normal Inline Grammar
1192 const inlineNormal = {
1193 _backpedal: noopTest, // only used for GFM url
1214 * Pedantic Inline Grammar
1216 const inlinePedantic = {
1218 link: edit(/^!?\[(label)\]\((.*?)\)/)
1219 .replace('label', _inlineLabel)
1221 reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
1222 .replace('label', _inlineLabel)
1226 * GFM Inline Grammar
1230 escape: edit(escape).replace('])', '~|])').getRegex(),
1231 url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i')
1232 .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)
1234 _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
1235 del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
1236 text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/,
1239 * GFM + Line Breaks Inline Grammar
1241 const inlineBreaks = {
1243 br: edit(br).replace('{2,}', '*').getRegex(),
1244 text: edit(inlineGfm.text)
1245 .replace('\\b_', '\\b_| {2,}\\n')
1246 .replace(/\{2,\}/g, '*')
1253 normal: blockNormal,
1255 pedantic: blockPedantic,
1258 normal: inlineNormal,
1260 breaks: inlineBreaks,
1261 pedantic: inlinePedantic,
1273 constructor(options) {
1274 // TokenList cannot be created in one go
1276 this.tokens.links = Object.create(null);
1277 this.options = options || exports.defaults;
1278 this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
1279 this.tokenizer = this.options.tokenizer;
1280 this.tokenizer.options = this.options;
1281 this.tokenizer.lexer = this;
1282 this.inlineQueue = [];
1289 block: block.normal,
1290 inline: inline.normal,
1292 if (this.options.pedantic) {
1293 rules.block = block.pedantic;
1294 rules.inline = inline.pedantic;
1296 else if (this.options.gfm) {
1297 rules.block = block.gfm;
1298 if (this.options.breaks) {
1299 rules.inline = inline.breaks;
1302 rules.inline = inline.gfm;
1305 this.tokenizer.rules = rules;
1310 static get rules() {
1319 static lex(src, options) {
1320 const lexer = new _Lexer(options);
1321 return lexer.lex(src);
1324 * Static Lex Inline Method
1326 static lexInline(src, options) {
1327 const lexer = new _Lexer(options);
1328 return lexer.inlineTokens(src);
1335 .replace(/\r\n|\r/g, '\n');
1336 this.blockTokens(src, this.tokens);
1337 for (let i = 0; i < this.inlineQueue.length; i++) {
1338 const next = this.inlineQueue[i];
1339 this.inlineTokens(next.src, next.tokens);
1341 this.inlineQueue = [];
1344 blockTokens(src, tokens = [], lastParagraphClipped = false) {
1345 if (this.options.pedantic) {
1346 src = src.replace(/\t/g, ' ').replace(/^ +$/gm, '');
1352 if (this.options.extensions
1353 && this.options.extensions.block
1354 && this.options.extensions.block.some((extTokenizer) => {
1355 if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
1356 src = src.substring(token.raw.length);
1365 if (token = this.tokenizer.space(src)) {
1366 src = src.substring(token.raw.length);
1367 if (token.raw.length === 1 && tokens.length > 0) {
1368 // if there's a single \n as a spacer, it's terminating the last line,
1369 // so move it there so that we don't get unnecessary paragraph tags
1370 tokens[tokens.length - 1].raw += '\n';
1378 if (token = this.tokenizer.code(src)) {
1379 src = src.substring(token.raw.length);
1380 lastToken = tokens[tokens.length - 1];
1381 // An indented code block cannot interrupt a paragraph.
1382 if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
1383 lastToken.raw += '\n' + token.raw;
1384 lastToken.text += '\n' + token.text;
1385 this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
1393 if (token = this.tokenizer.fences(src)) {
1394 src = src.substring(token.raw.length);
1399 if (token = this.tokenizer.heading(src)) {
1400 src = src.substring(token.raw.length);
1405 if (token = this.tokenizer.hr(src)) {
1406 src = src.substring(token.raw.length);
1411 if (token = this.tokenizer.blockquote(src)) {
1412 src = src.substring(token.raw.length);
1417 if (token = this.tokenizer.list(src)) {
1418 src = src.substring(token.raw.length);
1423 if (token = this.tokenizer.html(src)) {
1424 src = src.substring(token.raw.length);
1429 if (token = this.tokenizer.def(src)) {
1430 src = src.substring(token.raw.length);
1431 lastToken = tokens[tokens.length - 1];
1432 if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
1433 lastToken.raw += '\n' + token.raw;
1434 lastToken.text += '\n' + token.raw;
1435 this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
1437 else if (!this.tokens.links[token.tag]) {
1438 this.tokens.links[token.tag] = {
1446 if (token = this.tokenizer.table(src)) {
1447 src = src.substring(token.raw.length);
1452 if (token = this.tokenizer.lheading(src)) {
1453 src = src.substring(token.raw.length);
1457 // top-level paragraph
1458 // prevent paragraph consuming extensions by clipping 'src' to extension start
1460 if (this.options.extensions && this.options.extensions.startBlock) {
1461 let startIndex = Infinity;
1462 const tempSrc = src.slice(1);
1464 this.options.extensions.startBlock.forEach((getStartIndex) => {
1465 tempStart = getStartIndex.call({ lexer: this }, tempSrc);
1466 if (typeof tempStart === 'number' && tempStart >= 0) {
1467 startIndex = Math.min(startIndex, tempStart);
1470 if (startIndex < Infinity && startIndex >= 0) {
1471 cutSrc = src.substring(0, startIndex + 1);
1474 if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
1475 lastToken = tokens[tokens.length - 1];
1476 if (lastParagraphClipped && lastToken?.type === 'paragraph') {
1477 lastToken.raw += '\n' + token.raw;
1478 lastToken.text += '\n' + token.text;
1479 this.inlineQueue.pop();
1480 this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
1485 lastParagraphClipped = (cutSrc.length !== src.length);
1486 src = src.substring(token.raw.length);
1490 if (token = this.tokenizer.text(src)) {
1491 src = src.substring(token.raw.length);
1492 lastToken = tokens[tokens.length - 1];
1493 if (lastToken && lastToken.type === 'text') {
1494 lastToken.raw += '\n' + token.raw;
1495 lastToken.text += '\n' + token.text;
1496 this.inlineQueue.pop();
1497 this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
1505 const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
1506 if (this.options.silent) {
1507 console.error(errMsg);
1511 throw new Error(errMsg);
1515 this.state.top = true;
1518 inline(src, tokens = []) {
1519 this.inlineQueue.push({ src, tokens });
1525 inlineTokens(src, tokens = []) {
1526 let token, lastToken, cutSrc;
1527 // String with links masked to avoid interference with em and strong
1528 let maskedSrc = src;
1530 let keepPrevChar, prevChar;
1531 // Mask out reflinks
1532 if (this.tokens.links) {
1533 const links = Object.keys(this.tokens.links);
1534 if (links.length > 0) {
1535 while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
1536 if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
1537 maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
1542 // Mask out other blocks
1543 while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
1544 maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
1546 // Mask out escaped characters
1547 while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
1548 maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
1551 if (!keepPrevChar) {
1554 keepPrevChar = false;
1556 if (this.options.extensions
1557 && this.options.extensions.inline
1558 && this.options.extensions.inline.some((extTokenizer) => {
1559 if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
1560 src = src.substring(token.raw.length);
1569 if (token = this.tokenizer.escape(src)) {
1570 src = src.substring(token.raw.length);
1575 if (token = this.tokenizer.tag(src)) {
1576 src = src.substring(token.raw.length);
1577 lastToken = tokens[tokens.length - 1];
1578 if (lastToken && token.type === 'text' && lastToken.type === 'text') {
1579 lastToken.raw += token.raw;
1580 lastToken.text += token.text;
1588 if (token = this.tokenizer.link(src)) {
1589 src = src.substring(token.raw.length);
1594 if (token = this.tokenizer.reflink(src, this.tokens.links)) {
1595 src = src.substring(token.raw.length);
1596 lastToken = tokens[tokens.length - 1];
1597 if (lastToken && token.type === 'text' && lastToken.type === 'text') {
1598 lastToken.raw += token.raw;
1599 lastToken.text += token.text;
1607 if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
1608 src = src.substring(token.raw.length);
1613 if (token = this.tokenizer.codespan(src)) {
1614 src = src.substring(token.raw.length);
1619 if (token = this.tokenizer.br(src)) {
1620 src = src.substring(token.raw.length);
1625 if (token = this.tokenizer.del(src)) {
1626 src = src.substring(token.raw.length);
1631 if (token = this.tokenizer.autolink(src)) {
1632 src = src.substring(token.raw.length);
1637 if (!this.state.inLink && (token = this.tokenizer.url(src))) {
1638 src = src.substring(token.raw.length);
1643 // prevent inlineText consuming extensions by clipping 'src' to extension start
1645 if (this.options.extensions && this.options.extensions.startInline) {
1646 let startIndex = Infinity;
1647 const tempSrc = src.slice(1);
1649 this.options.extensions.startInline.forEach((getStartIndex) => {
1650 tempStart = getStartIndex.call({ lexer: this }, tempSrc);
1651 if (typeof tempStart === 'number' && tempStart >= 0) {
1652 startIndex = Math.min(startIndex, tempStart);
1655 if (startIndex < Infinity && startIndex >= 0) {
1656 cutSrc = src.substring(0, startIndex + 1);
1659 if (token = this.tokenizer.inlineText(cutSrc)) {
1660 src = src.substring(token.raw.length);
1661 if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started
1662 prevChar = token.raw.slice(-1);
1664 keepPrevChar = true;
1665 lastToken = tokens[tokens.length - 1];
1666 if (lastToken && lastToken.type === 'text') {
1667 lastToken.raw += token.raw;
1668 lastToken.text += token.text;
1676 const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
1677 if (this.options.silent) {
1678 console.error(errMsg);
1682 throw new Error(errMsg);
1695 parser; // set by the parser
1696 constructor(options) {
1697 this.options = options || exports.defaults;
1702 code({ text, lang, escaped }) {
1703 const langString = (lang || '').match(/^\S*/)?.[0];
1704 const code = text.replace(/\n$/, '') + '\n';
1706 return '<pre><code>'
1707 + (escaped ? code : escape$1(code, true))
1708 + '</code></pre>\n';
1710 return '<pre><code class="language-'
1711 + escape$1(langString)
1713 + (escaped ? code : escape$1(code, true))
1714 + '</code></pre>\n';
1716 blockquote({ tokens }) {
1717 const body = this.parser.parse(tokens);
1718 return `<blockquote>\n${body}</blockquote>\n`;
1723 heading({ tokens, depth }) {
1724 return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\n`;
1730 const ordered = token.ordered;
1731 const start = token.start;
1733 for (let j = 0; j < token.items.length; j++) {
1734 const item = token.items[j];
1735 body += this.listitem(item);
1737 const type = ordered ? 'ol' : 'ul';
1738 const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : '';
1739 return '<' + type + startAttr + '>\n' + body + '</' + type + '>\n';
1744 const checkbox = this.checkbox({ checked: !!item.checked });
1746 if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
1747 item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
1748 if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
1749 item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
1753 item.tokens.unshift({
1755 raw: checkbox + ' ',
1756 text: checkbox + ' ',
1761 itemBody += checkbox + ' ';
1764 itemBody += this.parser.parse(item.tokens, !!item.loose);
1765 return `<li>${itemBody}</li>\n`;
1767 checkbox({ checked }) {
1769 + (checked ? 'checked="" ' : '')
1770 + 'disabled="" type="checkbox">';
1772 paragraph({ tokens }) {
1773 return `<p>${this.parser.parseInline(tokens)}</p>\n`;
1779 for (let j = 0; j < token.header.length; j++) {
1780 cell += this.tablecell(token.header[j]);
1782 header += this.tablerow({ text: cell });
1784 for (let j = 0; j < token.rows.length; j++) {
1785 const row = token.rows[j];
1787 for (let k = 0; k < row.length; k++) {
1788 cell += this.tablecell(row[k]);
1790 body += this.tablerow({ text: cell });
1793 body = `<tbody>${body}</tbody>`;
1801 tablerow({ text }) {
1802 return `<tr>\n${text}</tr>\n`;
1805 const content = this.parser.parseInline(token.tokens);
1806 const type = token.header ? 'th' : 'td';
1807 const tag = token.align
1808 ? `<${type} align="${token.align}">`
1810 return tag + content + `</${type}>\n`;
1813 * span level renderer
1815 strong({ tokens }) {
1816 return `<strong>${this.parser.parseInline(tokens)}</strong>`;
1819 return `<em>${this.parser.parseInline(tokens)}</em>`;
1821 codespan({ text }) {
1822 return `<code>${text}</code>`;
1828 return `<del>${this.parser.parseInline(tokens)}</del>`;
1830 link({ href, title, tokens }) {
1831 const text = this.parser.parseInline(tokens);
1832 const cleanHref = cleanUrl(href);
1833 if (cleanHref === null) {
1837 let out = '<a href="' + href + '"';
1839 out += ' title="' + title + '"';
1841 out += '>' + text + '</a>';
1844 image({ href, title, text }) {
1845 const cleanHref = cleanUrl(href);
1846 if (cleanHref === null) {
1850 let out = `<img src="${href}" alt="${text}"`;
1852 out += ` title="${title}"`;
1858 return 'tokens' in token && token.tokens ? this.parser.parseInline(token.tokens) : token.text;
1864 * returns only the textual part of the token
1866 class _TextRenderer {
1867 // no need for block level renderers
1874 codespan({ text }) {
1898 * Parsing & Compiling
1904 constructor(options) {
1905 this.options = options || exports.defaults;
1906 this.options.renderer = this.options.renderer || new _Renderer();
1907 this.renderer = this.options.renderer;
1908 this.renderer.options = this.options;
1909 this.renderer.parser = this;
1910 this.textRenderer = new _TextRenderer();
1913 * Static Parse Method
1915 static parse(tokens, options) {
1916 const parser = new _Parser(options);
1917 return parser.parse(tokens);
1920 * Static Parse Inline Method
1922 static parseInline(tokens, options) {
1923 const parser = new _Parser(options);
1924 return parser.parseInline(tokens);
1929 parse(tokens, top = true) {
1931 for (let i = 0; i < tokens.length; i++) {
1932 const anyToken = tokens[i];
1933 // Run any renderer extensions
1934 if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
1935 const genericToken = anyToken;
1936 const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
1937 if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(genericToken.type)) {
1942 const token = anyToken;
1943 switch (token.type) {
1945 out += this.renderer.space(token);
1949 out += this.renderer.hr(token);
1953 out += this.renderer.heading(token);
1957 out += this.renderer.code(token);
1961 out += this.renderer.table(token);
1964 case 'blockquote': {
1965 out += this.renderer.blockquote(token);
1969 out += this.renderer.list(token);
1973 out += this.renderer.html(token);
1977 out += this.renderer.paragraph(token);
1981 let textToken = token;
1982 let body = this.renderer.text(textToken);
1983 while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {
1984 textToken = tokens[++i];
1985 body += '\n' + this.renderer.text(textToken);
1988 out += this.renderer.paragraph({
1992 tokens: [{ type: 'text', raw: body, text: body }],
2001 const errMsg = 'Token with "' + token.type + '" type was not found.';
2002 if (this.options.silent) {
2003 console.error(errMsg);
2007 throw new Error(errMsg);
2015 * Parse Inline Tokens
2017 parseInline(tokens, renderer) {
2018 renderer = renderer || this.renderer;
2020 for (let i = 0; i < tokens.length; i++) {
2021 const anyToken = tokens[i];
2022 // Run any renderer extensions
2023 if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
2024 const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
2025 if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {
2030 const token = anyToken;
2031 switch (token.type) {
2033 out += renderer.text(token);
2037 out += renderer.html(token);
2041 out += renderer.link(token);
2045 out += renderer.image(token);
2049 out += renderer.strong(token);
2053 out += renderer.em(token);
2057 out += renderer.codespan(token);
2061 out += renderer.br(token);
2065 out += renderer.del(token);
2069 out += renderer.text(token);
2073 const errMsg = 'Token with "' + token.type + '" type was not found.';
2074 if (this.options.silent) {
2075 console.error(errMsg);
2079 throw new Error(errMsg);
2091 constructor(options) {
2092 this.options = options || exports.defaults;
2094 static passThroughHooks = new Set([
2100 * Process markdown before marked
2102 preprocess(markdown) {
2106 * Process HTML after marked is finished
2112 * Process all tokens before walk tokens
2114 processAllTokens(tokens) {
2118 * Provide function to tokenize markdown
2121 return this.block ? _Lexer.lex : _Lexer.lexInline;
2124 * Provide function to parse tokens
2127 return this.block ? _Parser.parse : _Parser.parseInline;
2132 defaults = _getDefaults();
2133 options = this.setOptions;
2134 parse = this.parseMarkdown(true);
2135 parseInline = this.parseMarkdown(false);
2137 Renderer = _Renderer;
2138 TextRenderer = _TextRenderer;
2140 Tokenizer = _Tokenizer;
2142 constructor(...args) {
2146 * Run callback for every token
2148 walkTokens(tokens, callback) {
2150 for (const token of tokens) {
2151 values = values.concat(callback.call(this, token));
2152 switch (token.type) {
2154 const tableToken = token;
2155 for (const cell of tableToken.header) {
2156 values = values.concat(this.walkTokens(cell.tokens, callback));
2158 for (const row of tableToken.rows) {
2159 for (const cell of row) {
2160 values = values.concat(this.walkTokens(cell.tokens, callback));
2166 const listToken = token;
2167 values = values.concat(this.walkTokens(listToken.items, callback));
2171 const genericToken = token;
2172 if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
2173 this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
2174 const tokens = genericToken[childTokens].flat(Infinity);
2175 values = values.concat(this.walkTokens(tokens, callback));
2178 else if (genericToken.tokens) {
2179 values = values.concat(this.walkTokens(genericToken.tokens, callback));
2187 const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
2188 args.forEach((pack) => {
2189 // copy options to new object
2190 const opts = { ...pack };
2191 // set async to true if it was set to true before
2192 opts.async = this.defaults.async || opts.async || false;
2193 // ==-- Parse "addon" extensions --== //
2194 if (pack.extensions) {
2195 pack.extensions.forEach((ext) => {
2197 throw new Error('extension name required');
2199 if ('renderer' in ext) { // Renderer extensions
2200 const prevRenderer = extensions.renderers[ext.name];
2202 // Replace extension with func to run new extension but fall back if false
2203 extensions.renderers[ext.name] = function (...args) {
2204 let ret = ext.renderer.apply(this, args);
2205 if (ret === false) {
2206 ret = prevRenderer.apply(this, args);
2212 extensions.renderers[ext.name] = ext.renderer;
2215 if ('tokenizer' in ext) { // Tokenizer Extensions
2216 if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {
2217 throw new Error("extension level must be 'block' or 'inline'");
2219 const extLevel = extensions[ext.level];
2221 extLevel.unshift(ext.tokenizer);
2224 extensions[ext.level] = [ext.tokenizer];
2226 if (ext.start) { // Function to check for start of token
2227 if (ext.level === 'block') {
2228 if (extensions.startBlock) {
2229 extensions.startBlock.push(ext.start);
2232 extensions.startBlock = [ext.start];
2235 else if (ext.level === 'inline') {
2236 if (extensions.startInline) {
2237 extensions.startInline.push(ext.start);
2240 extensions.startInline = [ext.start];
2245 if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens
2246 extensions.childTokens[ext.name] = ext.childTokens;
2249 opts.extensions = extensions;
2251 // ==-- Parse "overwrite" extensions --== //
2252 if (pack.renderer) {
2253 const renderer = this.defaults.renderer || new _Renderer(this.defaults);
2254 for (const prop in pack.renderer) {
2255 if (!(prop in renderer)) {
2256 throw new Error(`renderer '${prop}' does not exist`);
2258 if (['options', 'parser'].includes(prop)) {
2259 // ignore options property
2262 const rendererProp = prop;
2263 const rendererFunc = pack.renderer[rendererProp];
2264 const prevRenderer = renderer[rendererProp];
2265 // Replace renderer with func to run extension, but fall back if false
2266 renderer[rendererProp] = (...args) => {
2267 let ret = rendererFunc.apply(renderer, args);
2268 if (ret === false) {
2269 ret = prevRenderer.apply(renderer, args);
2274 opts.renderer = renderer;
2276 if (pack.tokenizer) {
2277 const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
2278 for (const prop in pack.tokenizer) {
2279 if (!(prop in tokenizer)) {
2280 throw new Error(`tokenizer '${prop}' does not exist`);
2282 if (['options', 'rules', 'lexer'].includes(prop)) {
2283 // ignore options, rules, and lexer properties
2286 const tokenizerProp = prop;
2287 const tokenizerFunc = pack.tokenizer[tokenizerProp];
2288 const prevTokenizer = tokenizer[tokenizerProp];
2289 // Replace tokenizer with func to run extension, but fall back if false
2290 // @ts-expect-error cannot type tokenizer function dynamically
2291 tokenizer[tokenizerProp] = (...args) => {
2292 let ret = tokenizerFunc.apply(tokenizer, args);
2293 if (ret === false) {
2294 ret = prevTokenizer.apply(tokenizer, args);
2299 opts.tokenizer = tokenizer;
2301 // ==-- Parse Hooks extensions --== //
2303 const hooks = this.defaults.hooks || new _Hooks();
2304 for (const prop in pack.hooks) {
2305 if (!(prop in hooks)) {
2306 throw new Error(`hook '${prop}' does not exist`);
2308 if (['options', 'block'].includes(prop)) {
2309 // ignore options and block properties
2312 const hooksProp = prop;
2313 const hooksFunc = pack.hooks[hooksProp];
2314 const prevHook = hooks[hooksProp];
2315 if (_Hooks.passThroughHooks.has(prop)) {
2316 // @ts-expect-error cannot type hook function dynamically
2317 hooks[hooksProp] = (arg) => {
2318 if (this.defaults.async) {
2319 return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {
2320 return prevHook.call(hooks, ret);
2323 const ret = hooksFunc.call(hooks, arg);
2324 return prevHook.call(hooks, ret);
2328 // @ts-expect-error cannot type hook function dynamically
2329 hooks[hooksProp] = (...args) => {
2330 let ret = hooksFunc.apply(hooks, args);
2331 if (ret === false) {
2332 ret = prevHook.apply(hooks, args);
2340 // ==-- Parse WalkTokens extensions --== //
2341 if (pack.walkTokens) {
2342 const walkTokens = this.defaults.walkTokens;
2343 const packWalktokens = pack.walkTokens;
2344 opts.walkTokens = function (token) {
2346 values.push(packWalktokens.call(this, token));
2348 values = values.concat(walkTokens.call(this, token));
2353 this.defaults = { ...this.defaults, ...opts };
2358 this.defaults = { ...this.defaults, ...opt };
2361 lexer(src, options) {
2362 return _Lexer.lex(src, options ?? this.defaults);
2364 parser(tokens, options) {
2365 return _Parser.parse(tokens, options ?? this.defaults);
2367 parseMarkdown(blockType) {
2368 // eslint-disable-next-line @typescript-eslint/no-explicit-any
2369 const parse = (src, options) => {
2370 const origOpt = { ...options };
2371 const opt = { ...this.defaults, ...origOpt };
2372 const throwError = this.onError(!!opt.silent, !!opt.async);
2373 // throw error if an extension set async to true but parse was called with async: false
2374 if (this.defaults.async === true && origOpt.async === false) {
2375 return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));
2377 // throw error in case of non string input
2378 if (typeof src === 'undefined' || src === null) {
2379 return throwError(new Error('marked(): input parameter is undefined or null'));
2381 if (typeof src !== 'string') {
2382 return throwError(new Error('marked(): input parameter is of type '
2383 + Object.prototype.toString.call(src) + ', string expected'));
2386 opt.hooks.options = opt;
2387 opt.hooks.block = blockType;
2389 const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);
2390 const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);
2392 return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)
2393 .then(src => lexer(src, opt))
2394 .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens)
2395 .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)
2396 .then(tokens => parser(tokens, opt))
2397 .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)
2402 src = opt.hooks.preprocess(src);
2404 let tokens = lexer(src, opt);
2406 tokens = opt.hooks.processAllTokens(tokens);
2408 if (opt.walkTokens) {
2409 this.walkTokens(tokens, opt.walkTokens);
2411 let html = parser(tokens, opt);
2413 html = opt.hooks.postprocess(html);
2418 return throwError(e);
2423 onError(silent, async) {
2425 e.message += '\nPlease report this to https://github.com/markedjs/marked.';
2427 const msg = '<p>An error occurred:</p><pre>'
2428 + escape$1(e.message + '', true)
2431 return Promise.resolve(msg);
2436 return Promise.reject(e);
2443 const markedInstance = new Marked();
2444 function marked(src, opt) {
2445 return markedInstance.parse(src, opt);
2448 * Sets the default options.
2450 * @param options Hash of options
2453 marked.setOptions = function (options) {
2454 markedInstance.setOptions(options);
2455 marked.defaults = markedInstance.defaults;
2456 changeDefaults(marked.defaults);
2460 * Gets the original marked default options.
2462 marked.getDefaults = _getDefaults;
2463 marked.defaults = exports.defaults;
2467 marked.use = function (...args) {
2468 markedInstance.use(...args);
2469 marked.defaults = markedInstance.defaults;
2470 changeDefaults(marked.defaults);
2474 * Run callback for every token
2476 marked.walkTokens = function (tokens, callback) {
2477 return markedInstance.walkTokens(tokens, callback);
2480 * Compiles markdown to HTML without enclosing `p` tag.
2482 * @param src String of markdown source to be compiled
2483 * @param options Hash of options
2484 * @return String of compiled HTML
2486 marked.parseInline = markedInstance.parseInline;
2490 marked.Parser = _Parser;
2491 marked.parser = _Parser.parse;
2492 marked.Renderer = _Renderer;
2493 marked.TextRenderer = _TextRenderer;
2494 marked.Lexer = _Lexer;
2495 marked.lexer = _Lexer.lex;
2496 marked.Tokenizer = _Tokenizer;
2497 marked.Hooks = _Hooks;
2498 marked.parse = marked;
2499 const options = marked.options;
2500 const setOptions = marked.setOptions;
2501 const use = marked.use;
2502 const walkTokens = marked.walkTokens;
2503 const parseInline = marked.parseInline;
2504 const parse = marked;
2505 const parser = _Parser.parse;
2506 const lexer = _Lexer.lex;
2508 exports.Hooks = _Hooks;
2509 exports.Lexer = _Lexer;
2510 exports.Marked = Marked;
2511 exports.Parser = _Parser;
2512 exports.Renderer = _Renderer;
2513 exports.TextRenderer = _TextRenderer;
2514 exports.Tokenizer = _Tokenizer;
2515 exports.getDefaults = _getDefaults;
2516 exports.lexer = lexer;
2517 exports.marked = marked;
2518 exports.options = options;
2519 exports.parse = parse;
2520 exports.parseInline = parseInline;
2521 exports.parser = parser;
2522 exports.setOptions = setOptions;
2524 exports.walkTokens = walkTokens;
2527//# sourceMappingURL=marked.umd.js.map