PHP and Javascript implementations of a simple markdown parser
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

markdown.js 54KB

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