PHP and Javascript implementations of a simple markdown parser
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

markdown.js 49KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998
  1. // FIXME: Nested lists not working right
  2. // FIXME: Nested blockquotes require blank line
  3. // TODO: HTML tags probably need better handling. Consider whether interior of matched tags should be interpreted as markdown.
  4. // TODO: {.class #cssid lang=fr}
  5. // # Header {.class}
  6. // Header {.class}
  7. // ---
  8. // [link](url){.class}
  9. // ``` {.class}
  10. // TODO: Test broken/incomplete syntax thoroughly
  11. // TODO: Sanity checks on loops/recursion?
  12. class _MDHAlign {
  13. static Left = new _MDHAlign('Left');
  14. static Center = new _MDHAlign('Center');
  15. static Right = new _MDHAlign('Right');
  16. /** @var {String} */
  17. name;
  18. constructor(name) {
  19. this.name = name;
  20. }
  21. toString() {
  22. return `${this.constructor.name}.${this.name}`;
  23. }
  24. static toHTMLAttribute(align) {
  25. switch (align) {
  26. case _MDHAlign.Left: return ' align="left"';
  27. case _MDHAlign.Center: return ' align="center"';
  28. case _MDHAlign.Right: return ' align="right"';
  29. }
  30. return '';
  31. }
  32. }
  33. class _MDTokenType {
  34. static Text = new _MDTokenType('Text');
  35. static Whitespace = new _MDTokenType('Whitespace');
  36. static Underscore = new _MDTokenType('Underscore');
  37. static Asterisk = new _MDTokenType('Asterisk');
  38. static Slash = new _MDTokenType('Slash');
  39. static Tilde = new _MDTokenType('Tilde');
  40. static Bang = new _MDTokenType('Bang');
  41. static Backtick = new _MDTokenType('Backtick');
  42. static Label = new _MDTokenType('Label'); // content=label
  43. static URL = new _MDTokenType('URL'); // content=URL, extra=title
  44. static Email = new _MDTokenType('Email'); // content=email address, extra=title
  45. static SimpleLink = new _MDTokenType('SimpleLink'); // content=URL
  46. static SimpleEmail = new _MDTokenType('SimpleEmail'); // content=email address
  47. static Footnote = new _MDTokenType('Footnote'); // content=symbol
  48. static HTMLTag = new _MDTokenType('HTMLTag'); // content=tag string, tag=_MDHTMLTag
  49. static META_AnyNonWhitespace = new _MDTokenType('METAAnyNonWhitespace');
  50. /** @var {String} */
  51. name;
  52. constructor(name) {
  53. this.name = name;
  54. }
  55. toString() {
  56. return `${this.constructor.name}.${this.name}`;
  57. }
  58. }
  59. class _MDToken {
  60. /**
  61. * The original token string.
  62. * @var {String}
  63. */
  64. original;
  65. /** @var {_MDTokenType} */
  66. type;
  67. /** @var {String|null} */
  68. content;
  69. /** @var {String|null} */
  70. extra;
  71. /** @var {_MDHTMLTag|null} */
  72. tag;
  73. /**
  74. * @param {String} original
  75. * @param {_MDTokenType} type
  76. * @param {String|null} content
  77. * @param {String|null} extra
  78. * @param {_MDHTMLTag|null} tag
  79. */
  80. constructor(original, type, content=null, extra=null, tag=null) {
  81. this.original = original;
  82. this.type = type;
  83. this.content = content;
  84. this.extra = extra;
  85. this.tag = tag;
  86. }
  87. }
  88. // -- Spans -----------------------------------------------------------------
  89. class _MDSpan {
  90. /** @var {String[]} */
  91. cssClasses = [];
  92. /** @var {String|null} */
  93. id = null;
  94. /** @var {Object} */
  95. attributes = {};
  96. /**
  97. * @param {_MDState} state
  98. * @returns {String} HTML
  99. */
  100. toHTML(state) {
  101. throw new Error(self.constructor.name + ".toHTML not implemented");
  102. }
  103. htmlAttributes() {
  104. var html = '';
  105. if (this.cssClasses.length > 0) {
  106. html += ` class="${this.cssClasses.join(' ')}"`;
  107. }
  108. if (this.id !== null) {
  109. html += ` id="${this.id}"`;
  110. }
  111. for (const name in this.attributes) {
  112. let value = this.attributes[name];
  113. html += ` ${name}="${value.replace('"', '"')}"`;
  114. }
  115. return html;
  116. }
  117. /**
  118. * @param {_MDSpan[]} spans
  119. * @param {_MDState} state
  120. */
  121. static toHTML(spans, state) {
  122. return spans.map((span) => span.toHTML(state)).join("");
  123. }
  124. }
  125. class _MDMultiSpan extends _MDSpan {
  126. /** @var {_MDSpan[]} */
  127. content;
  128. /**
  129. * @param {_MDSpan[]} content
  130. */
  131. constructor(content) {
  132. super();
  133. this.content = content;
  134. }
  135. toHTML(state) {
  136. return _MDSpan.toHTML(this.content, state);
  137. }
  138. }
  139. class _MDTextSpan extends _MDSpan {
  140. /** @param {String} text */
  141. text;
  142. /**
  143. * @param {String} text
  144. */
  145. constructor(text) {
  146. super();
  147. this.text = text;
  148. }
  149. toHTML(state) {
  150. let html = this.text.replace('<', '&lt;');
  151. let abbrevs = state.abbreviations;
  152. let regexes = state.abbreviationRegexes;
  153. for (const abbrev in abbrevs) {
  154. let def = abbrevs[abbrev];
  155. let regex = regexes[abbrev];
  156. let escapedDef = def.replace('"', '&quot;');
  157. html = html.replace(regex, `<abbr title="${escapedDef}">$1</abbr>`);
  158. }
  159. return html;
  160. }
  161. }
  162. class _MDHTMLSpan extends _MDSpan {
  163. /** @param {String} html */
  164. html;
  165. /**
  166. * @param {String} html
  167. */
  168. constructor(html) {
  169. super();
  170. this.html = html;
  171. }
  172. toHTML(state) {
  173. return this.html;
  174. }
  175. }
  176. class _MDLinkSpan extends _MDSpan {
  177. /** @var {String} */
  178. link;
  179. /** @var {String|null} */
  180. target = null;
  181. /** @var {_MDSpan} */
  182. content;
  183. /** @var {String|null} */
  184. title = null;
  185. /**
  186. * @param {String} link
  187. * @param {_MDSpan} content
  188. */
  189. constructor(link, content, title=null) {
  190. super();
  191. this.link = link;
  192. this.content = content;
  193. this.title = title;
  194. }
  195. toHTML(state) {
  196. let escapedLink = this.link.replace('"', '&quot;');
  197. var html = `<a href="${escapedLink}"`;
  198. if (this.target) {
  199. let escapedTarget = this.target.replace('"', '&quot;');
  200. html += ` target="${escapedTarget}"`;
  201. }
  202. if (this.title) {
  203. html += ` title="${this.title.replace('"', '&quot;')}"`;
  204. }
  205. html += this.htmlAttributes();
  206. html += '>' + this.content.toHTML(state) + '</a>';
  207. return html;
  208. }
  209. }
  210. class _MDReferencedLinkSpan extends _MDLinkSpan {
  211. /** @var {String} id */
  212. id;
  213. constructor(id, content) {
  214. super(null, content);
  215. this.id = id;
  216. }
  217. /**
  218. * @param {_MDState} state
  219. */
  220. toHTML(state) {
  221. if (!this.link) {
  222. let url = state.urls[this.id.toLowerCase()];
  223. let title = state.urlTitles[this.id.toLowerCase()];
  224. this.link = url;
  225. this.title = title || this.title;
  226. }
  227. if (this.link) {
  228. return super.toHTML(state);
  229. } else {
  230. let contentHTML = this.content.toHTML(state);
  231. return `[${contentHTML}][${this.id}]`;
  232. }
  233. }
  234. }
  235. class _MDEmphasisSpan extends _MDSpan {
  236. /** @var {_MDSpan} */
  237. #content;
  238. /**
  239. * @param {_MDSpan} content
  240. */
  241. constructor(content) {
  242. super();
  243. this.#content = content;
  244. }
  245. toHTML(state) {
  246. let contentHTML = this.#content.toHTML(state);
  247. return `<em${this.htmlAttributes()}>${contentHTML}</em>`;
  248. }
  249. }
  250. class _MDStrongSpan extends _MDSpan {
  251. /** @var {_MDSpan} content */
  252. #content;
  253. /**
  254. * @param {_MDSpan} content
  255. */
  256. constructor(content) {
  257. super();
  258. this.#content = content;
  259. }
  260. toHTML(state) {
  261. let contentHTML = this.#content.toHTML(state);
  262. return `<strong${this.htmlAttributes()}>${contentHTML}</strong>`;
  263. }
  264. }
  265. class _MDStrikethroughSpan extends _MDSpan {
  266. /** @var {_MDSpan} content */
  267. #content;
  268. /**
  269. * @param {_MDSpan} content
  270. */
  271. constructor(content) {
  272. super();
  273. this.#content = content;
  274. }
  275. toHTML(state) {
  276. let contentHTML = this.#content.toHTML(state);
  277. return `<strike${this.htmlAttributes()}>${contentHTML}</strike>`;
  278. }
  279. }
  280. class _MDCodeSpan extends _MDSpan {
  281. /** @var {_MDSpan} content */
  282. #content;
  283. /**
  284. * @param {_MDSpan} content
  285. */
  286. constructor(content) {
  287. super();
  288. this.#content = content;
  289. }
  290. toHTML(state) {
  291. let contentHTML = this.#content.toHTML(state);
  292. return `<code${this.htmlAttributes()}>${contentHTML}</code>`;
  293. }
  294. }
  295. class _MDImageSpan extends _MDSpan {
  296. /** @var {String} */
  297. source;
  298. /** @var {String|null} */
  299. alt;
  300. /** @var {String|null} */
  301. title;
  302. /**
  303. * @param {String} source
  304. */
  305. constructor(source, alt, title=null) {
  306. super();
  307. this.source = source;
  308. this.alt = alt;
  309. this.title = title;
  310. }
  311. toHTML(state) {
  312. let escapedSource = this.source.replace('"', '&quot;');
  313. let html = `<img src="${escapedSource}"`;
  314. if (this.alt) {
  315. let altEscaped = this.alt.replace('"', '&quot');
  316. html += ` alt="${altEscaped}"`;
  317. }
  318. if (this.title) {
  319. let titleEscaped = this.title.replace('"', '&quot;');
  320. html += ` title="${titleEscaped}"`;
  321. }
  322. html += this.htmlAttributes();
  323. html += '>';
  324. return html;
  325. }
  326. }
  327. class _MDReferencedImageSpan extends _MDImageSpan {
  328. /** @var {String} */
  329. id;
  330. /**
  331. * @param {String} id
  332. */
  333. constructor(id, alt) {
  334. super(null, alt);
  335. this.id = id;
  336. }
  337. toHTML(state) {
  338. if (!this.source) {
  339. let url = state.urls[this.id.toLowerCase()];
  340. let title = state.urlTitles[this.id.toLowerCase()];
  341. this.source = url;
  342. this.title = title || this.title;
  343. }
  344. if (this.source) {
  345. return super.toHTML(state);
  346. } else {
  347. let altEscaped = this.alt.replace('"', '&quot;');
  348. let idEscaped = this.id.replace('"', '&quot;');
  349. return `![${altEscaped}][${idEscaped}]`;
  350. }
  351. }
  352. }
  353. class _MDFootnoteReferenceSpan extends _MDSpan {
  354. /** @var {String} */
  355. symbol;
  356. /**
  357. * @param {String} symbol
  358. */
  359. constructor(symbol) {
  360. super();
  361. this.symbol = symbol;
  362. }
  363. toHTML(state) {
  364. return `<!--FNREF:{${this.symbol}}-->`;
  365. }
  366. }
  367. // -- Blocks ----------------------------------------------------------------
  368. class _MDBlock {
  369. /** @var {String[]} */
  370. cssClasses = [];
  371. /** @var {String|null} */
  372. id = null;
  373. /** @var {Object} */
  374. attributes = {};
  375. /**
  376. * @param {_MDState} state
  377. */
  378. toHTML(state) {
  379. throw new Error(self.constructor.name + ".toHTML not implemented");
  380. }
  381. htmlAttributes() {
  382. var html = '';
  383. if (this.cssClasses.length > 0) {
  384. html += ` class="${this.cssClasses.join(' ')}"`;
  385. }
  386. if (this.id !== null) {
  387. html += ` id="${this.id}"`;
  388. }
  389. for (const name in this.attributes) {
  390. let value = this.attributes[name];
  391. html += ` ${name}="${value.replace('"', '&quot;')}"`;
  392. }
  393. return html;
  394. }
  395. /**
  396. * @param {_MDBlock[]} blocks
  397. * @param {_MDState} state
  398. * @returns {String}
  399. */
  400. static toHTML(blocks, state) {
  401. return blocks.map((block) => block.toHTML(state)).join("\n");
  402. }
  403. }
  404. class _MDMultiBlock extends _MDBlock {
  405. /** @var {_MDBlock[]} */
  406. #blocks;
  407. /**
  408. * @param {_MDBlock[]} blocks
  409. */
  410. constructor(blocks) {
  411. super();
  412. this.#blocks = blocks;
  413. }
  414. toHTML(state) {
  415. return _MDBlock.toHTML(this.#blocks, state);
  416. }
  417. }
  418. class _MDParagraphBlock extends _MDBlock {
  419. /** @var {_MDBlock} */
  420. content;
  421. /**
  422. * @param {_MDBlock} content
  423. */
  424. constructor(content) {
  425. super();
  426. this.content = content;
  427. }
  428. toHTML(state) {
  429. let contentHTML = this.content.toHTML(state);
  430. return `<p${this.htmlAttributes()}>${contentHTML}</p>\n`;
  431. }
  432. }
  433. class _MDHeaderBlock extends _MDBlock {
  434. /** @var {number} */
  435. level;
  436. /** @var {_MDBlock} */
  437. content;
  438. /**
  439. * @param {number} level
  440. * @param {_MDBlock} content
  441. */
  442. constructor(level, content) {
  443. super();
  444. this.level = level;
  445. this.content = content;
  446. }
  447. toHTML(state) {
  448. let contentHTML = this.content.toHTML(state);
  449. return `<h${this.level}${this.htmlAttributes()}>${contentHTML}</h${this.level}>\n`;
  450. }
  451. }
  452. class _MDBlockquoteBlock extends _MDBlock {
  453. /** @var {_MDBlock[]} */
  454. content;
  455. /**
  456. * @param {_MDBlock[]} content
  457. */
  458. constructor(content) {
  459. super();
  460. this.content = content;
  461. }
  462. toHTML(state) {
  463. let contentHTML = _MDBlock.toHTML(this.content, state);
  464. return `<blockquote${this.htmlAttributes()}>\n${contentHTML}\n</blockquote>`;
  465. }
  466. }
  467. class _MDUnorderedListBlock extends _MDBlock {
  468. /** @var {_MDListItemBlock[]} */
  469. items;
  470. /**
  471. * @param {_MDListItemBlock[]} items
  472. */
  473. constructor(items) {
  474. super();
  475. this.items = items;
  476. }
  477. toHTML(state) {
  478. let contentHTML = _MDBlock.toHTML(this.items, state);
  479. return `<ul${this.htmlAttributes()}>\n${contentHTML}\n</ul>`;
  480. }
  481. }
  482. class _MDOrderedListBlock extends _MDBlock {
  483. /** @var {_MDListItemBlock[]} */
  484. items;
  485. /** @var {Number|null} */
  486. startOrdinal;
  487. /**
  488. * @param {_MDListItemBlock[]} items
  489. */
  490. constructor(items, startOrdinal=null) {
  491. super();
  492. this.items = items;
  493. this.startOrdinal = startOrdinal;
  494. }
  495. htmlAttributes() {
  496. var html = super.htmlAttributes();
  497. if (this.startOrdinal !== null) {
  498. html += ` start="${this.startOrdinal}"`;
  499. }
  500. return html;
  501. }
  502. toHTML(state) {
  503. let contentHTML = _MDBlock.toHTML(this.items, state);
  504. return `<ol${this.htmlAttributes()}>\n${contentHTML}\n</ol>`;
  505. }
  506. }
  507. class _MDListItemBlock extends _MDBlock {
  508. /** @var {_MDBlock} */
  509. content;
  510. /** @var {Number|null} */
  511. ordinal;
  512. /**
  513. * @param {_MDBlock} content
  514. */
  515. constructor(content, ordinal=null) {
  516. super();
  517. this.content = content;
  518. this.ordinal = ordinal;
  519. }
  520. toHTML(state) {
  521. let contentHTML = this.content.toHTML(state);
  522. return `<li${this.htmlAttributes()}>${contentHTML}</li>`;
  523. }
  524. }
  525. class _MDCodeBlock extends _MDBlock {
  526. /** @var {String} */
  527. #code;
  528. /**
  529. * @param {String} code
  530. */
  531. constructor(code) {
  532. super();
  533. this.#code = code;
  534. }
  535. toHTML(state) {
  536. return `<pre${this.htmlAttributes()}><code>${this.#code}</code></pre>`;
  537. }
  538. }
  539. class _MDHorizontalRuleBlock extends _MDBlock {
  540. toHTML(state) {
  541. return `<hr${this.htmlAttributes()}>\n`;
  542. }
  543. }
  544. class _MDTableCellBlock extends _MDBlock {
  545. /** @var {_MDBlock} */
  546. #content;
  547. /** @var {_MDHAlign|null} */
  548. align = null;
  549. /**
  550. * @param {_MDBlock} content
  551. */
  552. constructor(content) {
  553. super();
  554. this.#content = content;
  555. }
  556. htmlAttributes() {
  557. var html = super.htmlAttributes();
  558. html += _MDHAlign.toHTMLAttribute(this.align);
  559. return html;
  560. }
  561. toHTML(state) {
  562. let contentHTML = this.#content.toHTML(state);
  563. return `<td${this.htmlAttributes()}>${contentHTML}</td>`;
  564. }
  565. }
  566. class _MDTableHeaderCellBlock extends _MDTableCellBlock {
  567. toHTML(state) {
  568. let html = super.toHTML(state);
  569. let groups = /^<td(.*)td>$/.exec(html);
  570. return `<th${groups[1]}th>`;
  571. }
  572. }
  573. class _MDTableRowBlock extends _MDBlock {
  574. /** @var {_MDTableCellBlock[]|_MDTableHeaderCellBlock[]} */
  575. #cells;
  576. /**
  577. * @param {_MDTableCellBlock[]|_MDTableHeaderCellBlock[]} cells
  578. */
  579. constructor(cells) {
  580. super();
  581. this.#cells = cells;
  582. }
  583. /**
  584. * @param {_MDHAlign[]} alignments
  585. */
  586. applyAlignments(alignments) {
  587. for (var i = 0; i < this.#cells.length; i++) {
  588. let cell = this.#cells[i];
  589. let align = i < alignments.length ? alignments[i] : null;
  590. cell.align = align;
  591. }
  592. }
  593. toHTML(state) {
  594. let cellsHTML = _MDBlock.toHTML(this.#cells, state);
  595. return `<tr${this.htmlAttributes()}>\n${cellsHTML}\n</tr>`;
  596. }
  597. }
  598. class _MDTableBlock extends _MDBlock {
  599. /** @var {_MDTableRowBlock} */
  600. #headerRow;
  601. /** @var {_MDTableRowBlock[]} */
  602. #bodyRows;
  603. /**
  604. * @param {_MDTableRowBlock} headerRow
  605. * @param {_MDTableRowBlock[]} bodyRows
  606. */
  607. constructor(headerRow, bodyRows) {
  608. super();
  609. this.#headerRow = headerRow;
  610. this.#bodyRows = bodyRows;
  611. }
  612. toHTML(state) {
  613. let headerRowHTML = this.#headerRow.toHTML(state);
  614. let bodyRowsHTML = _MDBlock.toHTML(this.#bodyRows, state);
  615. return `<table${this.htmlAttributes()}>\n<thead>\n${headerRowHTML}\n</thead>\n<tbody>\n${bodyRowsHTML}\n</tbody>\n</table>`;
  616. }
  617. }
  618. class _MDDefinitionListBlock extends _MDBlock {
  619. /** @var {_MDBlock[]} */
  620. #content;
  621. /**
  622. * @param {_MDBlock[]} content
  623. */
  624. constructor(content) {
  625. super();
  626. this.#content = content;
  627. }
  628. toHTML(state) {
  629. let contentHTML = _MDBlock.toHTML(this.#content, state);
  630. return `<dl${this.htmlAttributes()}>\n${contentHTML}\n</dl>`;
  631. }
  632. }
  633. class _MDDefinitionTermBlock extends _MDBlock {
  634. /** @var {_MDBlock} */
  635. #content;
  636. /**
  637. * @param {_MDBlock} content
  638. */
  639. constructor(content) {
  640. super();
  641. this.#content = content;
  642. }
  643. toHTML(state) {
  644. let contentHTML = this.#content.toHTML(state);
  645. return `<dt${this.htmlAttributes()}>${contentHTML}</dt>`;
  646. }
  647. }
  648. class _MDDefinitionDefinitionBlock extends _MDBlock {
  649. /** @var {_MDBlock} */
  650. #content;
  651. /**
  652. * @param {_MDBlock} content
  653. */
  654. constructor(content) {
  655. super();
  656. this.#content = content;
  657. }
  658. toHTML(state) {
  659. let contentHTML = this.#content.toHTML(state);
  660. return `<dd${this.htmlAttributes()}>${contentHTML}</dd>`;
  661. }
  662. }
  663. class _MDInlineBlock extends _MDBlock {
  664. /** @var {_MDSpan[]} */
  665. #content;
  666. /**
  667. * @param {_MDSpan[]} content
  668. */
  669. constructor(content) {
  670. super();
  671. this.#content = content;
  672. }
  673. toHTML(state) {
  674. return _MDSpan.toHTML(this.#content, state);
  675. }
  676. }
  677. class _MDHTMLTag {
  678. /** @var {String} */
  679. fullTag;
  680. /** @var {String} */
  681. tagName;
  682. /** @var {Boolean} */
  683. isCloser;
  684. /** @var {Object} */
  685. attributes;
  686. /**
  687. * @param {String} fullTag
  688. * @param {String} tagName
  689. * @param {Boolean} isCloser
  690. * @param {Object} attributes
  691. */
  692. constructor(fullTag, tagName, isCloser, attributes) {
  693. this.fullTag = fullTag;
  694. this.tagName = tagName;
  695. this.isCloser = isCloser;
  696. this.attributes = attributes;
  697. }
  698. }
  699. class _MDState {
  700. /** @var {String[]} */
  701. lines = [];
  702. /** @var {Object} */
  703. #abbreviations = {};
  704. /** @var {Object} */
  705. #abbreviationRegexes = {};
  706. /** @var {Object} */
  707. #footnotes = {};
  708. /** @var {Object} */
  709. #urlDefinitions = {};
  710. /** @var {Object} */
  711. #urlTitles = {};
  712. /** @var {number} */
  713. p = 0;
  714. /** @var {_MDState|null} */
  715. #parent = null;
  716. /** @var {Object} */
  717. get abbreviations() {
  718. return (this.#parent) ? this.#parent.abbreviations : this.#abbreviations;
  719. }
  720. /** @var {Object} */
  721. get abbreviationRegexes() {
  722. return (this.#parent) ? this.#parent.abbreviationRegexes : this.#abbreviationRegexes;
  723. }
  724. /** @var {Object} */
  725. get footnotes() {
  726. return (this.#parent) ? this.#parent.footnotes : this.#footnotes;
  727. }
  728. /** @var {Object} */
  729. get urls() {
  730. return (this.#parent) ? this.#parent.urls : this.#urlDefinitions;
  731. }
  732. /** @var {Object} */
  733. get urlTitles() {
  734. return (this.#parent) ? this.#parent.urlTitles : this.#urlTitles;
  735. }
  736. /**
  737. * @param {String[]} lines
  738. */
  739. copy(lines) {
  740. let cp = new _MDState();
  741. cp.#parent = this;
  742. cp.lines = lines;
  743. cp.p = 0;
  744. return cp;
  745. }
  746. /**
  747. * @param {String} abbreviation
  748. * @param {String} definition
  749. */
  750. defineAbbreviation(abbreviation, definition) {
  751. if (this.#parent) {
  752. this.#parent.defineAbbreviation(abbreviation, definition);
  753. return;
  754. }
  755. this.#abbreviations[abbreviation] = definition;
  756. let regex = new RegExp("\\b(" + abbreviation + ")\\b", "ig");
  757. this.#abbreviationRegexes[abbreviation] = regex;
  758. }
  759. /**
  760. * @param {String} symbol
  761. * @param {_MDBlock} footnote
  762. */
  763. defineFootnote(symbol, footnote) {
  764. if (this.#parent) {
  765. this.#parent.defineFootnote(symbol, footnote);
  766. } else {
  767. this.#footnotes[symbol] = footnote;
  768. }
  769. }
  770. defineURL(symbol, url, title=null) {
  771. if (this.#parent) {
  772. this.#parent.defineURL(symbol, url, title);
  773. } else {
  774. this.#urlDefinitions[symbol.toLowerCase()] = url;
  775. if (title !== null) {
  776. this.#urlTitles[symbol.toLowerCase()] = title;
  777. }
  778. }
  779. }
  780. hasLines(minCount, p=-1) {
  781. let relativeTo = (p < 0) ? this.p : p;
  782. return relativeTo + minCount <= this.lines.length;
  783. }
  784. }
  785. class Markdown {
  786. /**
  787. * @param {String} line
  788. */
  789. static #stripIndent(line, count=1) {
  790. let regex = new RegExp(`^(?: {1,4}|\\t){${count}}`);
  791. return line.replace(regex, '');
  792. }
  793. /**
  794. * @param {String} line
  795. * @param {Boolean} fullIndentsOnly
  796. * @returns {Number} indent count
  797. */
  798. static #countIndents(line, fullIndentsOnly=false) {
  799. var count = 0;
  800. var lastLine = line;
  801. while (line.length > 0) {
  802. line = (fullIndentsOnly)
  803. ? line.replace(/^(?: {4}|\t)/, '')
  804. : line.replace(/^(?: {1,4}|\t)/, '');
  805. if (line != lastLine) {
  806. count++;
  807. } else {
  808. break;
  809. }
  810. lastLine = line;
  811. }
  812. return count;
  813. }
  814. /**
  815. * @param {_MDState} state
  816. * @returns {_MDBlock[]}
  817. */
  818. static #readBlocks(state) {
  819. var blocks = [];
  820. while (state.hasLines(1)) {
  821. let block = this.#readNextBlock(state);
  822. if (block) {
  823. blocks.push(block);
  824. } else {
  825. break;
  826. }
  827. }
  828. return blocks;
  829. }
  830. /**
  831. * @param {_MDState} state
  832. * @returns {_MDBlock}
  833. */
  834. static #readNextBlock(state) {
  835. while (state.hasLines(1) && state.lines[state.p].trim().length == 0) {
  836. state.p++;
  837. }
  838. var block;
  839. block = this.#readUnderlineHeader(state); if (block) return block;
  840. block = this.#readHashHeader(state); if (block) return block;
  841. block = this.#readBlockQuote(state); if (block) return block;
  842. block = this.#readUnorderedList(state); if (block) return block;
  843. block = this.#readOrderedList(state); if (block) return block;
  844. block = this.#readFencedCodeBlock(state); if (block) return block;
  845. block = this.#readIndentedCodeBlock(state); if (block) return block;
  846. block = this.#readHorizontalRule(state); if (block) return block;
  847. block = this.#readTable(state); if (block) return block;
  848. block = this.#readFootnoteDef(state); if (block) return block;
  849. block = this.#readAbbreviationDef(state); if (block) return block;
  850. block = this.#readURLDef(state); if (block) return block;
  851. block = this.#readDefinitionList(state); if (block) return block;
  852. block = this.#readParagraph(state); if (block) return block;
  853. return null;
  854. }
  855. static #htmlTagNameFirstRegex = /[a-z]/i;
  856. static #htmlTagNameMedialRegex = /[a-z0-9]/i;
  857. static #htmlAttributeNameFirstRegex = /[a-z]/i;
  858. static #htmlAttributeNameMedialRegex = /[a-z0-9-]/i;
  859. static #whitespaceCharRegex = /\s/;
  860. /**
  861. * @param {String} line
  862. * @returns {_MDHTMLTag|null} HTML tag if possible
  863. */
  864. static #htmlTag(line) {
  865. let expectOpenBracket = 0;
  866. let expectCloserOrName = 1;
  867. let expectName = 2;
  868. let expectAttributeNameOrEnd = 3;
  869. let expectEqualsOrAttributeOrEnd = 4;
  870. let expectAttributeValue = 5;
  871. let expectCloseBracket = 6;
  872. var isCloser = false;
  873. var tagName = '';
  874. var attributeName = '';
  875. var attributeValue = '';
  876. var attributeQuote = null;
  877. var attributes = {};
  878. var fullTag = null;
  879. let endAttribute = function() {
  880. if (attributeName.length > 0) {
  881. if (attributeValue.length > 0 || attributeQuote) {
  882. attributes[attributeName] = attributeValue;
  883. } else {
  884. attributes[attributeName] = true;
  885. }
  886. }
  887. attributeName = '';
  888. attributeValue = '';
  889. attributeQuote = null;
  890. };
  891. var expect = expectOpenBracket;
  892. for (var p = 0; p < line.length && fullTag === null; p++) {
  893. let ch = line.substring(p, p + 1);
  894. let isWhitespace = this.#whitespaceCharRegex.exec(ch) !== null;
  895. switch (expect) {
  896. case expectOpenBracket:
  897. if (ch != '<') return null;
  898. expect = expectCloserOrName;
  899. break;
  900. case expectCloserOrName:
  901. if (ch == '/') {
  902. isCloser = true;
  903. } else {
  904. p--;
  905. }
  906. expect = expectName;
  907. break;
  908. case expectName:
  909. if (tagName.length == 0) {
  910. if (this.#htmlTagNameFirstRegex.exec(ch) === null) return null;
  911. tagName += ch;
  912. } else {
  913. if (this.#htmlTagNameMedialRegex.exec(ch)) {
  914. tagName += ch;
  915. } else {
  916. p--;
  917. expect = (isCloser) ? expectCloseBracket : expectAttributeNameOrEnd;
  918. }
  919. }
  920. break;
  921. case expectAttributeNameOrEnd:
  922. if (attributeName.length == 0) {
  923. if (isWhitespace) {
  924. // skip whitespace
  925. } else if (ch == '/') {
  926. expect = expectCloseBracket;
  927. } else if (ch == '>') {
  928. fullTag = line.substring(0, p + 1);
  929. break;
  930. } else if (this.#htmlAttributeNameFirstRegex.exec(ch)) {
  931. attributeName += ch;
  932. } else {
  933. return null;
  934. }
  935. } else if (isWhitespace) {
  936. expect = expectEqualsOrAttributeOrEnd;
  937. } else if (ch == '/') {
  938. endAttribute();
  939. expect = expectCloseBracket;
  940. } else if (ch == '>') {
  941. endAttribute();
  942. fullTag = line.substring(0, p + 1);
  943. break;
  944. } else if (ch == '=') {
  945. expect = expectAttributeValue;
  946. } else if (this.#htmlAttributeNameMedialRegex.exec(ch)) {
  947. attributeName += ch;
  948. } else {
  949. return null;
  950. }
  951. break;
  952. case expectEqualsOrAttributeOrEnd:
  953. if (ch == '=') {
  954. expect = expectAttributeValue;
  955. } else if (isWhitespace) {
  956. // skip whitespace
  957. } else if (ch == '/') {
  958. expect = expectCloseBracket;
  959. } else if (ch == '>') {
  960. fullTag = line.substring(0, p + 1);
  961. break;
  962. } else if (this.#htmlAttributeNameFirstRegex.exec(ch)) {
  963. endAttribute();
  964. expect = expectAttributeNameOrEnd;
  965. p--;
  966. }
  967. break;
  968. case expectAttributeValue:
  969. if (attributeValue.length == 0) {
  970. if (attributeQuote === null) {
  971. if (isWhitespace) {
  972. // skip whitespace
  973. } else if (ch == '"' || ch == "'") {
  974. attributeQuote = ch;
  975. } else {
  976. attributeQuote = ''; // explicitly unquoted
  977. p--;
  978. }
  979. } else {
  980. if (ch === attributeQuote) {
  981. // Empty string
  982. endAttribute();
  983. expect = expectAttributeNameOrEnd;
  984. } else if (attributeQuote === '' && (ch == '/' || ch == '>')) {
  985. return null;
  986. } else {
  987. attributeValue += ch;
  988. }
  989. }
  990. } else {
  991. if (ch === attributeQuote) {
  992. endAttribute();
  993. expect = expectAttributeNameOrEnd;
  994. } else if (attributeQuote === '' && isWhitespace) {
  995. endAttribute();
  996. expect = expectAttributeNameOrEnd;
  997. } else {
  998. attributeValue += ch;
  999. }
  1000. }
  1001. break;
  1002. case expectCloseBracket:
  1003. if (isWhitespace) {
  1004. // ignore whitespace
  1005. } else if (ch == '>') {
  1006. fullTag = line.substring(0, p + 1);
  1007. break;
  1008. }
  1009. break;
  1010. }
  1011. }
  1012. if (fullTag === null) return null;
  1013. endAttribute();
  1014. return new _MDHTMLTag(fullTag, tagName, isCloser, attributes);
  1015. }
  1016. static #textWhitespaceRegex = /^(\s*)(?:(\S|\S.*\S)(\s*?))?$/; // 1=leading WS, 2=text, 3=trailing WS
  1017. // Modified from https://urlregex.com/ to remove capture groups. Matches fully qualified URLs only.
  1018. static #baseURLRegex = /(?:(?:(?:[a-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[a-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[a-z0-9\.\-]+)(?:(?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/i;
  1019. // Modified from https://emailregex.com/ to remove capture groups.
  1020. static #baseEmailRegex = /(?:(?:[^<>()\[\]\\.,;:\s@"]+(?:\.[^<>()\[\]\\.,;:\s@"]+)*)|(?:".+"))@(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(?:(?:[a-z\-0-9]+\.)+[a-z]{2,}))/i;
  1021. static #footnoteWithTitleRegex = /^\[\^(\d+?)\s+"(.*?)"\]/; // 1=symbol, 2=title
  1022. static #footnoteRegex = /^\[\^(\d+?)\]/; // 1=symbol
  1023. // Note: label contents have to have matching pairs of [] and (). Handles images inside links.
  1024. static #labelRegex = /^\[((?:[^\[\]]*\[[^\[\]]*\][^\[\]]*|[^\(\)]*\([^\(\)]*?\)[^\(\)]*|[^\[\]\(\)]*?)*)\]/; // 1=content
  1025. static #urlWithTitleRegex = /^\((\S+?)\s+"(.*?)"\)/i; // 1=URL, 2=title
  1026. static #urlRegex = /^\((\S+?)\)/i; // 1=URL
  1027. static #emailWithTitleRegex = new RegExp("^\\(\\s*(" + this.#baseEmailRegex.source + ")\\s+\"(.*?)\"\\s*\\)", "i"); // 1=email, 2=title
  1028. static #emailRegex = new RegExp("^\\(\\s*(" + this.#baseEmailRegex.source + ")\\s*\\)", "i"); // 1=email
  1029. static #simpleURLRegex = new RegExp("^<" + this.#baseURLRegex.source + ">", "i"); // 1=URL
  1030. static #simpleEmailRegex = new RegExp("^<" + this.#baseEmailRegex.source + ">", "i"); // 1=email
  1031. /**
  1032. * @param {String} line
  1033. * @returns {_MDToken[]} tokens
  1034. */
  1035. static #tokenize(line) {
  1036. var tokens = [];
  1037. var text = '';
  1038. var expectLiteral = false;
  1039. var groups = null;
  1040. var tag = null;
  1041. const endText = function() {
  1042. if (text.length == 0) return;
  1043. let textGroups = Markdown.#textWhitespaceRegex.exec(text);
  1044. if (textGroups !== null) {
  1045. if (textGroups[1].length > 0) {
  1046. tokens.push(new _MDToken(textGroups[1], _MDTokenType.Whitespace, textGroups[1]));
  1047. }
  1048. if (textGroups[2] !== undefined && textGroups[2].length > 0) {
  1049. tokens.push(new _MDToken(textGroups[2], _MDTokenType.Text, textGroups[2]));
  1050. }
  1051. if (textGroups[3] !== undefined && textGroups[3].length > 0) {
  1052. tokens.push(new _MDToken(textGroups[3], _MDTokenType.Whitespace, textGroups[3]));
  1053. }
  1054. } else {
  1055. tokens.push(new _MDToken(text, _MDTokenType.Text, text));
  1056. }
  1057. text = '';
  1058. }
  1059. for (var p = 0; p < line.length; p++) {
  1060. let ch = line.substring(p, p + 1);
  1061. let remainder = line.substring(p);
  1062. if (expectLiteral) {
  1063. text += ch;
  1064. expectLiteral = false;
  1065. continue;
  1066. }
  1067. if (ch == '\\') {
  1068. expectLiteral = true;
  1069. } else if (ch == '*') {
  1070. endText();
  1071. tokens.push(new _MDToken(ch, _MDTokenType.Asterisk));
  1072. } else if (ch == '_') {
  1073. endText();
  1074. tokens.push(new _MDToken(ch, _MDTokenType.Underscore));
  1075. } else if (ch == '`') {
  1076. endText();
  1077. tokens.push(new _MDToken(ch, _MDTokenType.Backtick));
  1078. } else if (ch == '~') {
  1079. endText();
  1080. tokens.push(new _MDToken(ch, _MDTokenType.Tilde));
  1081. } else if (ch == '!') {
  1082. endText();
  1083. tokens.push(new _MDToken(ch, _MDTokenType.Bang));
  1084. } else if (groups = this.#footnoteWithTitleRegex.exec(remainder)) {
  1085. // Footnote with title [^1 "Foo"]
  1086. endText();
  1087. tokens.push(new _MDToken(groups[0], _MDTokenType.Footnote, groups[1], groups[2]));
  1088. p += groups[0].length - 1;
  1089. } else if (groups = this.#footnoteRegex.exec(remainder)) {
  1090. // Footnote without title [^1]
  1091. endText();
  1092. tokens.push(new _MDToken(groups[0], _MDTokenType.Footnote, groups[1]));
  1093. p += groups[0].length - 1;
  1094. } else if (groups = this.#labelRegex.exec(remainder)) {
  1095. // Label/ref for link/image [Foo]
  1096. endText();
  1097. tokens.push(new _MDToken(groups[0], _MDTokenType.Label, groups[1]));
  1098. p += groups[0].length - 1;
  1099. } else if (groups = this.#urlWithTitleRegex.exec(remainder)) {
  1100. // URL with title (https://foo "Bar")
  1101. endText();
  1102. tokens.push(new _MDToken(groups[0], _MDTokenType.URL, groups[1], groups[2]));
  1103. p += groups[0].length - 1;
  1104. } else if (groups = this.#emailWithTitleRegex.exec(remainder)) {
  1105. // Email address with title (user@example.com "Foo")
  1106. endText();
  1107. tokens.push(new _MDToken(groups[0], _MDTokenType.Email, groups[1], groups[2]));
  1108. p += groups[0].length - 1;
  1109. } else if (groups = this.#urlRegex.exec(remainder)) {
  1110. // URL (https://example.com)
  1111. endText();
  1112. tokens.push(new _MDToken(groups[0], _MDTokenType.URL, groups[1]));
  1113. p += groups[0].length - 1;
  1114. } else if (groups = this.#emailRegex.exec(remainder)) {
  1115. // Email (user@example.com)
  1116. endText();
  1117. tokens.push(new _MDToken(groups[0], _MDTokenType.Email, groups[1]));
  1118. p += groups[0].length - 1;
  1119. } else if (groups = this.#simpleURLRegex.exec(remainder)) {
  1120. // Simple URL <https://example.com>
  1121. endText();
  1122. tokens.push(new _MDToken(groups[0], _MDTokenType.SimpleLink, groups[1]));
  1123. p += groups[0].length - 1;
  1124. } else if (groups = this.#simpleEmailRegex.exec(remainder)) {
  1125. // Simple email <user@example.com>
  1126. endText();
  1127. tokens.push(new _MDToken(groups[0], _MDTokenType.SimpleEmail, groups[1]));
  1128. p += groups[0].length - 1;
  1129. } else if (tag = this.#htmlTag(remainder)) {
  1130. endText();
  1131. tokens.push(new _MDToken(tag.fullTag, _MDTokenType.HTMLTag, tag.fullTag, null, tag));
  1132. p += tag.fullTag.length - 1;
  1133. } else {
  1134. text += ch;
  1135. }
  1136. }
  1137. endText();
  1138. return tokens;
  1139. }
  1140. static #firstTokenIndex(tokens, pattern, startIndex=0) {
  1141. for (var t = startIndex; t < tokens.length; t++) {
  1142. var matchedAll = true;
  1143. for (var p = 0; p < pattern.length; p++) {
  1144. var t0 = t + p;
  1145. if (t0 >= tokens.length) return null;
  1146. let token = tokens[t0];
  1147. let elem = pattern[p];
  1148. if (elem == _MDTokenType.META_AnyNonWhitespace) {
  1149. if (token instanceof _MDToken && token.type == _MDTokenType.Whitespace) {
  1150. matchedAll = false;
  1151. break;
  1152. }
  1153. } else {
  1154. if (!(token instanceof _MDToken) || token.type != elem) {
  1155. matchedAll = false;
  1156. break;
  1157. }
  1158. }
  1159. }
  1160. if (matchedAll) {
  1161. return t;
  1162. }
  1163. }
  1164. return null;
  1165. }
  1166. /**
  1167. * @param {_MDState} state
  1168. * @param {String} line
  1169. * @returns {_MDBlock|null}
  1170. */
  1171. static #readInline(state, line) {
  1172. var tokens = this.#tokenize(line);
  1173. return new _MDInlineBlock(this.#tokensToSpans(tokens, state));
  1174. }
  1175. /**
  1176. * @param {Array} tokens
  1177. * @returns {_MDSpan[]} spans
  1178. */
  1179. static #tokensToSpans(tokens, state) {
  1180. var spans = tokens.slice(0, tokens.length);
  1181. var anyChanges = false;
  1182. var index, index0;
  1183. // First pass - contiguous constructs
  1184. do {
  1185. anyChanges = false;
  1186. // ![alt](image.jpg)
  1187. if ((index = this.#firstTokenIndex(spans, [
  1188. _MDTokenType.Bang,
  1189. _MDTokenType.Label,
  1190. _MDTokenType.URL,
  1191. ])) !== null) {
  1192. let alt = spans[index + 1].content;
  1193. let url = spans[index + 2].content;
  1194. let title = spans[index + 2].extra;
  1195. spans.splice(index, 3, new _MDImageSpan(url, alt, title));
  1196. anyChanges = true;
  1197. }
  1198. // ![alt][ref]
  1199. else if ((index = this.#firstTokenIndex(spans, [
  1200. _MDTokenType.Bang,
  1201. _MDTokenType.Label,
  1202. _MDTokenType.Label,
  1203. ])) !== null) {
  1204. let alt = spans[index + 1].content;
  1205. let ref = spans[index + 2].content;
  1206. spans.splice(index, 3, new _MDReferencedImageSpan(ref, alt));
  1207. anyChanges = true;
  1208. }
  1209. // [text](link.html)
  1210. else if ((index = this.#firstTokenIndex(spans, [
  1211. _MDTokenType.Label,
  1212. _MDTokenType.URL,
  1213. ])) !== null) {
  1214. let text = spans[index + 0].content;
  1215. let url = spans[index + 1].content;
  1216. spans.splice(index, 2, new _MDLinkSpan(url, this.#readInline(state, text)));
  1217. anyChanges = true;
  1218. }
  1219. // [text][ref]
  1220. else if ((index = this.#firstTokenIndex(spans, [
  1221. _MDTokenType.Label,
  1222. _MDTokenType.Label,
  1223. ])) !== null) {
  1224. let text = spans[index + 0].content;
  1225. let ref = spans[index + 1].content;
  1226. spans.splice(index, 2, new _MDReferencedLinkSpan(ref, this.#readInline(state, text)));
  1227. anyChanges = true;
  1228. }
  1229. // [^1]
  1230. else if ((index = this.#firstTokenIndex(spans, [
  1231. _MDTokenType.Footnote,
  1232. ])) !== null) {
  1233. let symbol = spans[index].content;
  1234. spans.splice(index, 1, new _MDFootnoteReferenceSpan(symbol));
  1235. anyChanges = true;
  1236. }
  1237. } while (anyChanges);
  1238. /**
  1239. * @param {_MDTokenType[]} delimiter
  1240. * @param {Set<_MDTokenType>} disallowedInnerTokens
  1241. */
  1242. const matchPair = function(delimiter, disallowedInnerTokens=new Set()) {
  1243. var searchStart = 0;
  1244. var hasNewStart = false;
  1245. do {
  1246. hasNewStart = false;
  1247. let startIndex = Markdown.#firstTokenIndex(spans, delimiter.concat(_MDTokenType.META_AnyNonWhitespace), searchStart);
  1248. if (startIndex === null) return null;
  1249. let endIndex = Markdown.#firstTokenIndex(spans, [_MDTokenType.META_AnyNonWhitespace].concat(delimiter), startIndex + delimiter.length);
  1250. if (endIndex === null) return null;
  1251. let contentTokens = spans.slice(startIndex + delimiter.length, endIndex + 1);
  1252. if (disallowedInnerTokens.size > 0) {
  1253. for (const token of contentTokens) {
  1254. if (token instanceof _MDToken && disallowedInnerTokens.has(token.type)) {
  1255. searchStart = startIndex + 1;
  1256. hasNewStart = true;
  1257. break;
  1258. }
  1259. }
  1260. if (hasNewStart) continue;
  1261. }
  1262. let contentSpans = Markdown.#tokensToSpans(contentTokens, state);
  1263. return {
  1264. startIndex: startIndex,
  1265. toDelete: endIndex - startIndex + delimiter.length + 1,
  1266. content: new _MDMultiSpan(contentSpans),
  1267. };
  1268. } while (hasNewStart);
  1269. return null;
  1270. };
  1271. var spanMatch = null;
  1272. // Second pass - paired constructs. Prioritize pairs with no other paired tokens inside.
  1273. const delimiterTokens = new Set([
  1274. _MDTokenType.Backtick,
  1275. _MDTokenType.Tilde,
  1276. _MDTokenType.Asterisk,
  1277. _MDTokenType.Underscore
  1278. ]);
  1279. for (let disallowed of [ delimiterTokens, new Set() ]) {
  1280. do {
  1281. anyChanges = false;
  1282. // ``code``
  1283. if (spanMatch = matchPair([ _MDTokenType.Backtick, _MDTokenType.Backtick ], disallowed)) {
  1284. spans.splice(spanMatch.startIndex, spanMatch.toDelete, new _MDCodeSpan(spanMatch.content));
  1285. anyChanges = true;
  1286. }
  1287. // ~~strike~~
  1288. else if (spanMatch = matchPair([ _MDTokenType.Tilde, _MDTokenType.Tilde ], disallowed)) {
  1289. spans.splice(spanMatch.startIndex, spanMatch.toDelete, new _MDStrikethroughSpan(spanMatch.content));
  1290. anyChanges = true;
  1291. }
  1292. // **strong** __strong__
  1293. else if (spanMatch = (matchPair([ _MDTokenType.Asterisk, _MDTokenType.Asterisk ], disallowed) ||
  1294. matchPair([ _MDTokenType.Underscore, _MDTokenType.Underscore ], disallowed))) {
  1295. spans.splice(spanMatch.startIndex, spanMatch.toDelete, new _MDStrongSpan(spanMatch.content));
  1296. anyChanges = true;
  1297. }
  1298. // `code`
  1299. if (spanMatch = matchPair([ _MDTokenType.Backtick ], disallowed)) {
  1300. spans.splice(spanMatch.startIndex, spanMatch.toDelete, new _MDCodeSpan(spanMatch.content));
  1301. anyChanges = true;
  1302. }
  1303. // ~strike~
  1304. else if (spanMatch = matchPair([ _MDTokenType.Tilde ], disallowed)) {
  1305. spans.splice(spanMatch.startIndex, spanMatch.toDelete, new _MDStrikethroughSpan(spanMatch.content));
  1306. anyChanges = true;
  1307. }
  1308. // *strong* _strong_
  1309. else if (spanMatch = (matchPair([ _MDTokenType.Asterisk ], disallowed) ||
  1310. matchPair([ _MDTokenType.Underscore ], disallowed))) {
  1311. spans.splice(spanMatch.startIndex, spanMatch.toDelete, new _MDEmphasisSpan(spanMatch.content));
  1312. anyChanges = true;
  1313. }
  1314. } while (anyChanges);
  1315. }
  1316. spans = spans.map(function(span) {
  1317. if (span instanceof _MDToken) {
  1318. return new _MDTextSpan(span.original);
  1319. } else if (span instanceof _MDSpan) {
  1320. return span;
  1321. } else {
  1322. throw new Error(`Unexpected span type ${span.constructor.name}`);
  1323. }
  1324. });
  1325. return spans;
  1326. }
  1327. /**
  1328. * Reads the contents of something like a list item
  1329. * @param {_MDState} state
  1330. * @param {number} firstLineStartPos
  1331. * @param {RegExp} stopRegex
  1332. * @param {Boolean} inList
  1333. * @returns {_MDBlock}
  1334. */
  1335. static #readInteriorContent(state, firstLineStartPos, stopRegex, inList=false) {
  1336. var p = state.p;
  1337. var seenBlankLine = false;
  1338. var needsBlocks = false;
  1339. var lines = [];
  1340. var hasNestedList = false;
  1341. var firstNestedListLine = -1;
  1342. while (state.hasLines(1, p)) {
  1343. let line = state.lines[p++];
  1344. if (p == state.p + 1) {
  1345. line = line.substring(firstLineStartPos);
  1346. }
  1347. let isBlank = line.trim().length == 0;
  1348. let isIndented = /^\s+/.exec(line) !== null;
  1349. if (isBlank) {
  1350. seenBlankLine = true;
  1351. lines.push(line.trim());
  1352. } else if (stopRegex && stopRegex.exec(line)) {
  1353. p--;
  1354. break;
  1355. } else if (isIndented) {
  1356. if (seenBlankLine) {
  1357. needsBlocks = true;
  1358. }
  1359. if (inList && /^\s*(?:\*|\+|\-|\d+\.)\s+/.exec(line)) {
  1360. hasNestedList = true;
  1361. if (firstNestedListLine < 0) {
  1362. firstNestedListLine = lines.length;
  1363. }
  1364. }
  1365. lines.push(this.#stripIndent(line));
  1366. } else {
  1367. if (seenBlankLine) {
  1368. p--;
  1369. break;
  1370. }
  1371. lines.push(this.#stripIndent(line));
  1372. }
  1373. }
  1374. while (lines.length > 0 && lines[lines.length - 1].trim().length == 0) {
  1375. lines.pop();
  1376. }
  1377. if (inList && hasNestedList) {
  1378. let parentLines = lines.slice(0, firstNestedListLine);
  1379. let parentContent = this.#readInline(state, parentLines.join("\n"));
  1380. let nestedLines = lines.slice(firstNestedListLine);
  1381. let substate = state.copy(nestedLines);
  1382. let nestedContent = this.#readBlocks(substate);
  1383. state.p = p;
  1384. return new _MDMultiBlock([parentContent].concat(nestedContent));
  1385. }
  1386. if (needsBlocks) {
  1387. let substate = state.copy(lines);
  1388. let blocks = this.#readBlocks(substate);
  1389. state.p = p;
  1390. return new _MDMultiBlock(blocks);
  1391. } else {
  1392. state.p = p;
  1393. return this.#readInline(state, lines.join("\n"));
  1394. }
  1395. }
  1396. /**
  1397. * @param {_MDState} state
  1398. * @returns {_MDBlock|null}
  1399. */
  1400. static #readUnderlineHeader(state) {
  1401. var p = state.p;
  1402. if (!state.hasLines(2)) return null;
  1403. let contentLine = state.lines[p++].trim();
  1404. let underLine = state.lines[p++].trim();
  1405. if (contentLine == '') return null;
  1406. if (/^=+$/.exec(underLine)) {
  1407. state.p = p;
  1408. return new _MDHeaderBlock(1, this.#readInline(state, contentLine));
  1409. }
  1410. if (/^\-+$/.exec(underLine)) {
  1411. state.p = p;
  1412. return new _MDHeaderBlock(2, this.#readInline(state, contentLine));
  1413. }
  1414. return null;
  1415. }
  1416. static #hashHeaderRegex = /^(#{1,6})\s*([^#].*?)\s*\#*\s*$/; // 1=hashes, 2=content
  1417. /**
  1418. * @param {_MDState} state
  1419. * @returns {_MDBlock|null}
  1420. */
  1421. static #readHashHeader(state) {
  1422. var p = state.p;
  1423. var groups = this.#hashHeaderRegex.exec(state.lines[p++]);
  1424. if (groups === null) return null;
  1425. state.p = p;
  1426. return new _MDHeaderBlock(groups[1].length, this.#readInline(state, groups[2]));
  1427. }
  1428. /**
  1429. * @param {_MDState} state
  1430. * @returns {_MDBlock|null}
  1431. */
  1432. static #readBlockQuote(state) {
  1433. var blockquoteLines = [];
  1434. var p = state.p;
  1435. while (p < state.lines.length) {
  1436. let line = state.lines[p++];
  1437. if (line.startsWith(">")) {
  1438. blockquoteLines.push(line);
  1439. } else {
  1440. break;
  1441. }
  1442. }
  1443. if (blockquoteLines.length > 0) {
  1444. let contentLines = blockquoteLines.map(function(line) {
  1445. return line.substring(1).replace(/^ {0,3}\t?/, '');
  1446. });
  1447. let substate = state.copy(contentLines);
  1448. let quotedBlocks = this.#readBlocks(substate);
  1449. state.p = p;
  1450. return new _MDBlockquoteBlock(quotedBlocks);
  1451. }
  1452. return null;
  1453. }
  1454. static #unorderedListRegex = /^([\*\+\-]\s+)(.*)$/; // 1=bullet, 2=content
  1455. static #unorderedListItemRegex = /^[\*\+\-]\s+/;
  1456. /**
  1457. * @param {_MDState} state
  1458. * @returns {_MDListItemBlock|null}
  1459. */
  1460. static #readUnorderedListItem(state) {
  1461. var p = state.p;
  1462. let line = state.lines[p];
  1463. let groups = this.#unorderedListRegex.exec(line);
  1464. if (groups === null) return null;
  1465. return new _MDListItemBlock(this.#readInteriorContent(state, groups[1].length, this.#unorderedListItemRegex, true));
  1466. }
  1467. /**
  1468. * @param {_MDState} state
  1469. * @returns {_MDBlock|null}
  1470. */
  1471. static #readUnorderedList(state) {
  1472. var items = [];
  1473. var item = null;
  1474. do {
  1475. item = this.#readUnorderedListItem(state);
  1476. if (item) items.push(item);
  1477. } while (item);
  1478. if (items.length == 0) return null;
  1479. return new _MDUnorderedListBlock(items);
  1480. }
  1481. static #orderedListRegex = /^(\d+)(\.\s+)(.*)$/; // 1=number, 2=dot, 3=content
  1482. static #orderedListItemRegex = /^\d+\.\s+/;
  1483. /**
  1484. * @param {_MDState} state
  1485. * @returns {_MDListItemBlock|null}
  1486. */
  1487. static #readOrderedListItem(state) {
  1488. var p = state.p;
  1489. let line = state.lines[p];
  1490. let groups = this.#orderedListRegex.exec(line);
  1491. if (groups === null) return null;
  1492. let ordinal = parseInt(groups[1]);
  1493. let content = this.#readInteriorContent(state, groups[1].length + groups[2].length, this.#orderedListItemRegex, true);
  1494. return new _MDListItemBlock(content, ordinal);
  1495. }
  1496. /**
  1497. * @param {_MDState} state
  1498. * @returns {_MDBlock|null}
  1499. */
  1500. static #readOrderedList(state) {
  1501. var items = [];
  1502. var item = null;
  1503. do {
  1504. item = this.#readOrderedListItem(state);
  1505. if (item) items.push(item);
  1506. } while (item);
  1507. if (items.length == 0) return null;
  1508. return new _MDOrderedListBlock(items, items[0].ordinal);
  1509. }
  1510. /**
  1511. * @param {_MDState} state
  1512. * @returns {_MDBlock|null}
  1513. */
  1514. static #readFencedCodeBlock(state) {
  1515. if (!state.hasLines(2)) return null;
  1516. var p = state.p;
  1517. if (state.lines[p++].trim() != '```') return null;
  1518. var codeLines = [];
  1519. while (state.hasLines(1, p)) {
  1520. let line = state.lines[p++];
  1521. if (line.trim() == '```') {
  1522. state.p = p;
  1523. return new _MDCodeBlock(codeLines.join("\n"));
  1524. }
  1525. codeLines.push(line);
  1526. }
  1527. return null;
  1528. }
  1529. /**
  1530. * @param {_MDState} state
  1531. * @returns {_MDBlock|null}
  1532. */
  1533. static #readIndentedCodeBlock(state) {
  1534. var p = state.p;
  1535. var codeLines = [];
  1536. while (state.hasLines(1, p)) {
  1537. let line = state.lines[p++];
  1538. if (this.#countIndents(line, true) < 1) {
  1539. p--;
  1540. break;
  1541. }
  1542. codeLines.push(this.#stripIndent(line));
  1543. }
  1544. if (codeLines.length == 0) return null;
  1545. state.p = p;
  1546. return new _MDCodeBlock(codeLines.join("\n"));
  1547. }
  1548. static #horizontalRuleRegex = /^\s*(?:\-(?:\s*\-){2,}|\*(?:\s*\*){2,})\s*$/;
  1549. /**
  1550. * @param {_MDState} state
  1551. * @returns {_MDBlock|null}
  1552. */
  1553. static #readHorizontalRule(state) {
  1554. var p = state.p;
  1555. let line = state.lines[p++];
  1556. if (this.#horizontalRuleRegex.exec(line)) {
  1557. state.p = p;
  1558. return new _MDHorizontalRuleBlock();
  1559. }
  1560. return null;
  1561. }
  1562. /**
  1563. * @param {_MDState} state
  1564. * @param {Boolean} isHeader
  1565. * @return {_MDTableRowBlock|null}
  1566. */
  1567. static #readTableRow(state, isHeader) {
  1568. if (!state.hasLines(1)) return null;
  1569. var p = state.p;
  1570. let line = state.lines[p++].trim();
  1571. if (/.*\|.*/.exec(line) === null) return null;
  1572. if (line.startsWith('|')) line = line.substring(1);
  1573. if (line.endsWith('|')) line = line.substring(0, line.length - 1);
  1574. let cellTokens = line.split('|');
  1575. let cells = cellTokens.map(function(token) {
  1576. let content = Markdown.#readInline(state, token);
  1577. return isHeader ? new _MDTableHeaderCellBlock(content) : new _MDTableCellBlock(content);
  1578. });
  1579. state.p = p;
  1580. return new _MDTableRowBlock(cells);
  1581. }
  1582. /**
  1583. * @param {String} line
  1584. * @returns {_MDHAlign[]}
  1585. */
  1586. static #parseColumnAlignments(line) {
  1587. line = line.trim();
  1588. if (line.startsWith('|')) line = line.substring(1);
  1589. if (line.endsWith('|')) line = line.substring(0, line.length - 1);
  1590. return line.split('|').map(function(token) {
  1591. token = token.trim();
  1592. if (token.startsWith(':')) {
  1593. if (token.endsWith(':')) {
  1594. return _MDHAlign.Center;
  1595. }
  1596. return _MDHAlign.Left;
  1597. } else if (token.endsWith(':')) {
  1598. return _MDHAlign.Right;
  1599. }
  1600. return null;
  1601. });
  1602. }
  1603. static #tableDividerRegex = /^\s*[|]?(?:\s*[:]?-+[:]?\s*\|)(?:\s*[:]?-+[:]?\s*)[|]?\s*$/;
  1604. /**
  1605. * @param {_MDState} state
  1606. * @returns {_MDBlock|null}
  1607. */
  1608. static #readTable(state) {
  1609. if (!state.hasLines(2)) return null;
  1610. let startP = state.p;
  1611. let headerRow = this.#readTableRow(state, true);
  1612. if (headerRow === null) {
  1613. state.p = startP;
  1614. return null;
  1615. }
  1616. let dividerLine = state.lines[state.p++];
  1617. let dividerGroups = this.#tableDividerRegex.exec(dividerLine);
  1618. if (dividerGroups === null) {
  1619. state.p = startP;
  1620. return null;
  1621. }
  1622. let columnAlignments = this.#parseColumnAlignments(dividerLine);
  1623. headerRow.applyAlignments(columnAlignments);
  1624. var bodyRows = [];
  1625. while (state.hasLines(1)) {
  1626. let row = this.#readTableRow(state, false);
  1627. if (row === null) break;
  1628. row.applyAlignments(columnAlignments);
  1629. bodyRows.push(row);
  1630. }
  1631. return new _MDTableBlock(headerRow, bodyRows);
  1632. }
  1633. /**
  1634. * @param {_MDState} state
  1635. * @returns {_MDBlock|null}
  1636. */
  1637. static #readDefinitionList(state) {
  1638. var p = state.p;
  1639. var groups;
  1640. var termCount = 0;
  1641. var definitionCount = 0;
  1642. var defLines = [];
  1643. while (state.hasLines(1, p)) {
  1644. let line = state.lines[p++];
  1645. if (line.trim().length == 0) {
  1646. p--;
  1647. break;
  1648. }
  1649. if (/^\s+/.exec(line)) {
  1650. if (defLines.length == 0) return null;
  1651. defLines[defLines.length - 1] += "\n" + line;
  1652. } else if (/^:\s+/.exec(line)) {
  1653. defLines.push(line);
  1654. definitionCount++;
  1655. } else {
  1656. defLines.push(line);
  1657. termCount++;
  1658. }
  1659. }
  1660. if (termCount == 0 || definitionCount == 0) return null;
  1661. let blocks = defLines.map(function(line) {
  1662. if (groups = /^:\s+(.*)$/.exec(line)) {
  1663. return new _MDDefinitionDefinitionBlock(Markdown.#readInline(state, groups[1]));
  1664. } else {
  1665. return new _MDDefinitionTermBlock(Markdown.#readInline(state, line));
  1666. }
  1667. });
  1668. state.p = p;
  1669. return new _MDDefinitionListBlock(blocks);
  1670. }
  1671. /**
  1672. * @param {_MDState} state
  1673. * @returns {_MDBlock|null}
  1674. */
  1675. static #readFootnoteDef(state) {
  1676. var p = state.p;
  1677. let groups = /^\s*\[\^\s*([^\]]+)\s*\]:\s+(.*)\s*$/.exec(state.lines[p++]);
  1678. if (groups === null) return null;
  1679. let symbol = groups[1];
  1680. let def = groups[2];
  1681. while (state.hasLines(1, p)) {
  1682. let line = state.lines[p++];
  1683. if (/^\s+/.exec(line)) {
  1684. def += "\n" + line;
  1685. } else {
  1686. p--;
  1687. break;
  1688. }
  1689. }
  1690. state.p = p;
  1691. let content = this.#readInline(state, def);
  1692. state.defineFootnote(symbol, content);
  1693. state.p = p;
  1694. return new _MDMultiBlock([]);
  1695. }
  1696. /**
  1697. * @param {_MDState} state
  1698. * @returns {_MDBlock|null}
  1699. */
  1700. static #readAbbreviationDef(state) {
  1701. var p = state.p;
  1702. let line = state.lines[p++];
  1703. let groups = /^\s*\*\[([^\]]+?)\]:\s+(.*?)\s*$/.exec(line);
  1704. if (groups === null) return null;
  1705. let abbrev = groups[1];
  1706. let def = groups[2];
  1707. state.defineAbbreviation(abbrev, def);
  1708. state.p = p;
  1709. return new _MDMultiBlock([]);
  1710. }
  1711. /**
  1712. * @param {_MDState} state
  1713. * @returns {_MDBlock|null}
  1714. */
  1715. static #readURLDef(state) {
  1716. var p = state.p;
  1717. let line = state.lines[p++];
  1718. var symbol;
  1719. var url;
  1720. var title = null;
  1721. let groups = /^\s*\[(.+?)]:\s*(\S+)\s+"(.*?)"\s*$/.exec(line);
  1722. if (groups) {
  1723. symbol = groups[1];
  1724. url = groups[2];
  1725. title = groups[3];
  1726. } else {
  1727. groups = /^\s*\[(.+?)]:\s*(\S+)\s*$/.exec(line);
  1728. if (groups) {
  1729. symbol = groups[1];
  1730. url = groups[2];
  1731. } else {
  1732. return null;
  1733. }
  1734. }
  1735. state.defineURL(symbol, url, title);
  1736. state.p = p;
  1737. return new _MDInlineBlock([]);
  1738. }
  1739. /**
  1740. * @param {_MDState} state
  1741. * @returns {_MDBlock|null}
  1742. */
  1743. static #readParagraph(state) {
  1744. var paragraphLines = [];
  1745. var p = state.p;
  1746. while (p < state.lines.length) {
  1747. let line = state.lines[p++];
  1748. if (line.trim().length == 0) {
  1749. break;
  1750. }
  1751. paragraphLines.push(line);
  1752. }
  1753. if (paragraphLines.length > 0) {
  1754. state.p = p;
  1755. let content = paragraphLines.join("\n");
  1756. return new _MDParagraphBlock(this.#readInline(state, content));
  1757. }
  1758. return null;
  1759. }
  1760. /**
  1761. * @param {String} html
  1762. * @param {_MDState} state
  1763. * @returns {String}
  1764. */
  1765. static #postProcessFootnotes(html, state) {
  1766. let footnotes = state.footnotes;
  1767. if (Object.keys(footnotes).length == 0) return html;
  1768. var symbolOrder = [];
  1769. var footnoteOccurrences = {};
  1770. var footnoteIndex = 0;
  1771. html = html.replace(/<!--FNREF:{(\d+)}-->/g, function(match, symbol) {
  1772. footnoteIndex++;
  1773. symbol = symbol.toLowerCase();
  1774. if (!symbolOrder.includes(symbol)) {
  1775. symbolOrder.push(symbol);
  1776. }
  1777. var occurrences = footnoteOccurrences[symbol] || [];
  1778. occurrences.push(footnoteIndex);
  1779. footnoteOccurrences[symbol] = occurrences;
  1780. return `<sup id="footnoteref_${footnoteIndex}"><a href="#footnote_${symbol}">${symbol}</a></sup>`;
  1781. });
  1782. if (footnoteIndex == 0) return html;
  1783. html += '<div class="footnotes"><hr/>';
  1784. html += '<ol>';
  1785. for (const symbol of symbolOrder) {
  1786. let content = state.footnotes[symbol];
  1787. if (!content) continue;
  1788. html += `<li value="${symbol}" id="footnote_${symbol}">${content.toHTML(state)}`;
  1789. for (const ref of footnoteOccurrences[symbol]) {
  1790. html += ` <a href="#footnoteref_${ref}" class="footnote-backref" role="doc-backlink">↩︎</a>`;
  1791. }
  1792. html += `</li>\n`;
  1793. }
  1794. html += '</ol>';
  1795. html += '</div>';
  1796. return html;
  1797. }
  1798. /**
  1799. * @param {String} markdown
  1800. * @returns {String} HTML
  1801. */
  1802. static toHTML(markdown) {
  1803. var state = new _MDState();
  1804. let lines = markdown.split(/(?:\n|\r|\r\n)/);
  1805. state.lines = lines;
  1806. let blocks = this.#readBlocks(state);
  1807. let html = _MDBlock.toHTML(blocks, state);
  1808. html = this.#postProcessFootnotes(html, state);
  1809. return html;
  1810. }
  1811. }