PHP and Javascript implementations of a simple markdown parser
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

markdown.js 54KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159
  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: Test broken/incomplete syntax thoroughly
  4. // TODO: Sanity checks on loops/recursion?
  5. // TODO: Tolerate whitespace between tokens (e.g. [click here] [urlref])
  6. // TODO: Spreadsheet functions in tables
  7. class _MDHAlign {
  8. static Left = new _MDHAlign('Left');
  9. static Center = new _MDHAlign('Center');
  10. static Right = new _MDHAlign('Right');
  11. /** @var {String} */
  12. name;
  13. constructor(name) {
  14. this.name = name;
  15. }
  16. toString() {
  17. return `${this.constructor.name}.${this.name}`;
  18. }
  19. static toHTMLAttribute(align) {
  20. switch (align) {
  21. case _MDHAlign.Left: return ' align="left"';
  22. case _MDHAlign.Center: return ' align="center"';
  23. case _MDHAlign.Right: return ' align="right"';
  24. }
  25. return '';
  26. }
  27. }
  28. class _MDTokenType {
  29. static Text = new _MDTokenType('Text');
  30. static Whitespace = new _MDTokenType('Whitespace');
  31. static Underscore = new _MDTokenType('Underscore');
  32. static Asterisk = new _MDTokenType('Asterisk');
  33. static Slash = new _MDTokenType('Slash');
  34. static Tilde = new _MDTokenType('Tilde');
  35. static Bang = new _MDTokenType('Bang');
  36. static Backtick = new _MDTokenType('Backtick');
  37. static Label = new _MDTokenType('Label'); // content=label
  38. static URL = new _MDTokenType('URL'); // content=URL, extra=title
  39. static Email = new _MDTokenType('Email'); // content=email address, extra=title
  40. static SimpleLink = new _MDTokenType('SimpleLink'); // content=URL
  41. static SimpleEmail = new _MDTokenType('SimpleEmail'); // content=email address
  42. static Footnote = new _MDTokenType('Footnote'); // content=symbol
  43. static Modifier = new _MDTokenType('Modifier'); // content
  44. static HTMLTag = new _MDTokenType('HTMLTag'); // content=tag string, tag=_MDHTMLTag
  45. static META_AnyNonWhitespace = new _MDTokenType('METAAnyNonWhitespace');
  46. /** @var {String} */
  47. name;
  48. constructor(name) {
  49. this.name = name;
  50. }
  51. toString() {
  52. return `${this.constructor.name}.${this.name}`;
  53. }
  54. }
  55. class _MDToken {
  56. /**
  57. * The original token string.
  58. * @var {String}
  59. */
  60. original;
  61. /** @var {_MDTokenType} */
  62. type;
  63. /** @var {String|null} */
  64. content;
  65. /** @var {String|null} */
  66. extra;
  67. /** @var {_MDHTMLTag|null} */
  68. tag;
  69. /** @var {_MDTagModifier|null} */
  70. modifier;
  71. /**
  72. * @param {String} original
  73. * @param {_MDTokenType} type
  74. * @param {String|_MDTagModifier|null} content
  75. * @param {String|null} extra
  76. * @param {_MDHTMLTag|null} tag
  77. */
  78. constructor(original, type, content=null, extra=null, tag=null) {
  79. this.original = original;
  80. this.type = type;
  81. if (content instanceof _MDTagModifier) {
  82. this.content = null;
  83. this.modifier = content;
  84. } else {
  85. this.content = content;
  86. this.modifier = null;
  87. }
  88. this.extra = extra;
  89. this.tag = tag;
  90. }
  91. }
  92. class _MDUtils {
  93. /**
  94. * @param {String} str
  95. * @returns {String}
  96. */
  97. static escapeHTML(str) {
  98. return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  99. }
  100. }
  101. // -- Spans -----------------------------------------------------------------
  102. class _MDSpan {
  103. /** @var {String[]} */
  104. cssClasses = [];
  105. /** @var {String|null} */
  106. id = null;
  107. /** @var {Object} */
  108. attributes = {};
  109. /**
  110. * @param {_MDState} state
  111. * @returns {String} HTML
  112. */
  113. toHTML(state) {
  114. throw new Error(self.constructor.name + ".toHTML not implemented");
  115. }
  116. htmlAttributes() {
  117. var html = '';
  118. if (this.cssClasses.length > 0) {
  119. html += ` class="${this.cssClasses.join(' ')}"`;
  120. }
  121. if (this.id !== null) {
  122. html += ` id="${this.id}"`;
  123. }
  124. for (const name in this.attributes) {
  125. let value = this.attributes[name];
  126. html += ` ${name}="${_MDUtils.escapeHTML(value)}"`;
  127. }
  128. return html;
  129. }
  130. /**
  131. * @param {_MDSpan[]} spans
  132. * @param {_MDState} state
  133. */
  134. static toHTML(spans, state) {
  135. return spans.map((span) => span.toHTML(state)).join("");
  136. }
  137. }
  138. class _MDMultiSpan extends _MDSpan {
  139. /** @var {_MDSpan[]} */
  140. content;
  141. /**
  142. * @param {_MDSpan[]} content
  143. */
  144. constructor(content) {
  145. super();
  146. this.content = content;
  147. }
  148. toHTML(state) {
  149. return _MDSpan.toHTML(this.content, state);
  150. }
  151. }
  152. class _MDTextSpan extends _MDSpan {
  153. /** @param {String} text */
  154. text;
  155. /**
  156. * @param {String} text
  157. */
  158. constructor(text) {
  159. super();
  160. this.text = text;
  161. }
  162. toHTML(state) {
  163. let html = this.text.replace('<', '&lt;');
  164. let abbrevs = state.abbreviations;
  165. let regexes = state.abbreviationRegexes;
  166. for (const abbrev in abbrevs) {
  167. let def = abbrevs[abbrev];
  168. let regex = regexes[abbrev];
  169. let escapedDef = _MDUtils.escapeHTML(def);
  170. html = html.replace(regex, `<abbr title="${escapedDef}">$1</abbr>`);
  171. }
  172. return html;
  173. }
  174. }
  175. class _MDHTMLSpan extends _MDSpan {
  176. /** @param {String} html */
  177. html;
  178. /**
  179. * @param {String} html
  180. */
  181. constructor(html) {
  182. super();
  183. this.html = html;
  184. }
  185. toHTML(state) {
  186. return this.html;
  187. }
  188. }
  189. class _MDLinkSpan extends _MDSpan {
  190. /** @var {String} */
  191. link;
  192. /** @var {String|null} */
  193. target = null;
  194. /** @var {_MDSpan} */
  195. content;
  196. /** @var {String|null} */
  197. title = null;
  198. /**
  199. * @param {String} link
  200. * @param {_MDSpan} content
  201. */
  202. constructor(link, content, title=null) {
  203. super();
  204. this.link = link;
  205. this.content = content;
  206. this.title = title;
  207. }
  208. toHTML(state) {
  209. var html = `<a href="${_MDUtils.escapeHTML(this.link)}"`;
  210. if (this.target) {
  211. html += ` target="${_MDUtils.escapeHTML(this.target)}"`;
  212. }
  213. if (this.title) {
  214. html += ` title="${_MDUtils.escapeHTML(this.title)}"`;
  215. }
  216. html += this.htmlAttributes();
  217. html += '>' + this.content.toHTML(state) + '</a>';
  218. return html;
  219. }
  220. }
  221. class _MDReferencedLinkSpan extends _MDLinkSpan {
  222. /** @var {String} id */
  223. id;
  224. constructor(id, content) {
  225. super(null, content);
  226. this.id = id;
  227. }
  228. /**
  229. * @param {_MDState} state
  230. */
  231. toHTML(state) {
  232. if (!this.link) {
  233. let url = state.urls[this.id.toLowerCase()];
  234. let title = state.urlTitles[this.id.toLowerCase()];
  235. this.link = url;
  236. this.title = title || this.title;
  237. }
  238. if (this.link) {
  239. return super.toHTML(state);
  240. } else {
  241. let contentHTML = this.content.toHTML(state);
  242. return `[${contentHTML}][${this.id}]`;
  243. }
  244. }
  245. }
  246. class _MDEmphasisSpan extends _MDSpan {
  247. /** @var {_MDSpan} */
  248. #content;
  249. /**
  250. * @param {_MDSpan} content
  251. */
  252. constructor(content) {
  253. super();
  254. this.#content = content;
  255. }
  256. toHTML(state) {
  257. let contentHTML = this.#content.toHTML(state);
  258. return `<em${this.htmlAttributes()}>${contentHTML}</em>`;
  259. }
  260. }
  261. class _MDStrongSpan extends _MDSpan {
  262. /** @var {_MDSpan} content */
  263. #content;
  264. /**
  265. * @param {_MDSpan} content
  266. */
  267. constructor(content) {
  268. super();
  269. this.#content = content;
  270. }
  271. toHTML(state) {
  272. let contentHTML = this.#content.toHTML(state);
  273. return `<strong${this.htmlAttributes()}>${contentHTML}</strong>`;
  274. }
  275. }
  276. class _MDStrikethroughSpan extends _MDSpan {
  277. /** @var {_MDSpan} content */
  278. #content;
  279. /**
  280. * @param {_MDSpan} content
  281. */
  282. constructor(content) {
  283. super();
  284. this.#content = content;
  285. }
  286. toHTML(state) {
  287. let contentHTML = this.#content.toHTML(state);
  288. return `<strike${this.htmlAttributes()}>${contentHTML}</strike>`;
  289. }
  290. }
  291. class _MDCodeSpan extends _MDSpan {
  292. /** @var {String} content */
  293. #content;
  294. /**
  295. * @param {String} content
  296. */
  297. constructor(content) {
  298. super();
  299. this.#content = content;
  300. }
  301. toHTML(state) {
  302. return `<code${this.htmlAttributes()}>${_MDUtils.escapeHTML(this.#content)}</code>`;
  303. }
  304. }
  305. class _MDImageSpan extends _MDSpan {
  306. /** @var {String} */
  307. source;
  308. /** @var {String|null} */
  309. alt;
  310. /** @var {String|null} */
  311. title;
  312. /**
  313. * @param {String} source
  314. */
  315. constructor(source, alt, title=null) {
  316. super();
  317. this.source = source;
  318. this.alt = alt;
  319. this.title = title;
  320. }
  321. toHTML(state) {
  322. let html = `<img src="${_MDUtils.escapeHTML(this.source)}"`;
  323. if (this.alt) {
  324. html += ` alt="${_MDUtils.escapeHTML(this.alt)}"`;
  325. }
  326. if (this.title) {
  327. html += ` title="${_MDUtils.escapeHTML(this.title)}"`;
  328. }
  329. html += this.htmlAttributes();
  330. html += '>';
  331. return html;
  332. }
  333. }
  334. class _MDReferencedImageSpan extends _MDImageSpan {
  335. /** @var {String} */
  336. id;
  337. /**
  338. * @param {String} id
  339. */
  340. constructor(id, alt) {
  341. super(null, alt);
  342. this.id = id;
  343. }
  344. toHTML(state) {
  345. if (!this.source) {
  346. let url = state.urls[this.id.toLowerCase()];
  347. let title = state.urlTitles[this.id.toLowerCase()];
  348. this.source = url;
  349. this.title = title || this.title;
  350. }
  351. if (this.source) {
  352. return super.toHTML(state);
  353. } else {
  354. return `![${_MDUtils.escapeHTML(this.alt)}][${_MDUtils.escapeHTML(this.id)}]`;
  355. }
  356. }
  357. }
  358. class _MDFootnoteReferenceSpan extends _MDSpan {
  359. /** @var {String} */
  360. symbol;
  361. /**
  362. * @param {String} symbol
  363. */
  364. constructor(symbol) {
  365. super();
  366. this.symbol = symbol;
  367. }
  368. toHTML(state) {
  369. return `<!--FNREF:{${this.symbol}}-->`;
  370. }
  371. }
  372. // -- Blocks ----------------------------------------------------------------
  373. class _MDBlock {
  374. /** @var {String[]} */
  375. cssClasses = [];
  376. /** @var {String|null} */
  377. id = null;
  378. /** @var {Object} */
  379. attributes = {};
  380. /**
  381. * @param {_MDState} state
  382. */
  383. toHTML(state) {
  384. throw new Error(self.constructor.name + ".toHTML not implemented");
  385. }
  386. htmlAttributes() {
  387. var html = '';
  388. if (this.cssClasses.length > 0) {
  389. html += ` class="${this.cssClasses.join(' ')}"`;
  390. }
  391. if (this.id !== null) {
  392. html += ` id="${this.id}"`;
  393. }
  394. for (const name in this.attributes) {
  395. let value = this.attributes[name];
  396. html += ` ${name}="${_MDUtils.escapeHTML(value)}"`;
  397. }
  398. return html;
  399. }
  400. /**
  401. * @param {_MDBlock[]} blocks
  402. * @param {_MDState} state
  403. * @returns {String}
  404. */
  405. static toHTML(blocks, state) {
  406. return blocks.map((block) => block.toHTML(state)).join("\n");
  407. }
  408. }
  409. class _MDMultiBlock extends _MDBlock {
  410. /** @var {_MDBlock[]} */
  411. #blocks;
  412. /**
  413. * @param {_MDBlock[]} blocks
  414. */
  415. constructor(blocks) {
  416. super();
  417. this.#blocks = blocks;
  418. }
  419. toHTML(state) {
  420. return _MDBlock.toHTML(this.#blocks, state);
  421. }
  422. }
  423. class _MDParagraphBlock extends _MDBlock {
  424. /** @var {_MDBlock} */
  425. content;
  426. /**
  427. * @param {_MDBlock} content
  428. */
  429. constructor(content) {
  430. super();
  431. this.content = content;
  432. }
  433. toHTML(state) {
  434. let contentHTML = this.content.toHTML(state);
  435. return `<p${this.htmlAttributes()}>${contentHTML}</p>\n`;
  436. }
  437. }
  438. class _MDHeaderBlock extends _MDBlock {
  439. /** @var {number} */
  440. level;
  441. /** @var {_MDBlock} */
  442. content;
  443. /**
  444. * @param {number} level
  445. * @param {_MDBlock} content
  446. */
  447. constructor(level, content) {
  448. super();
  449. this.level = level;
  450. this.content = content;
  451. }
  452. toHTML(state) {
  453. let contentHTML = this.content.toHTML(state);
  454. return `<h${this.level}${this.htmlAttributes()}>${contentHTML}</h${this.level}>\n`;
  455. }
  456. }
  457. class _MDBlockquoteBlock extends _MDBlock {
  458. /** @var {_MDBlock[]} */
  459. content;
  460. /**
  461. * @param {_MDBlock[]} content
  462. */
  463. constructor(content) {
  464. super();
  465. this.content = content;
  466. }
  467. toHTML(state) {
  468. let contentHTML = _MDBlock.toHTML(this.content, state);
  469. return `<blockquote${this.htmlAttributes()}>\n${contentHTML}\n</blockquote>`;
  470. }
  471. }
  472. class _MDUnorderedListBlock extends _MDBlock {
  473. /** @var {_MDListItemBlock[]} */
  474. items;
  475. /**
  476. * @param {_MDListItemBlock[]} items
  477. */
  478. constructor(items) {
  479. super();
  480. this.items = items;
  481. }
  482. toHTML(state) {
  483. let contentHTML = _MDBlock.toHTML(this.items, state);
  484. return `<ul${this.htmlAttributes()}>\n${contentHTML}\n</ul>`;
  485. }
  486. }
  487. class _MDOrderedListBlock extends _MDBlock {
  488. /** @var {_MDListItemBlock[]} */
  489. items;
  490. /** @var {Number|null} */
  491. startOrdinal;
  492. /**
  493. * @param {_MDListItemBlock[]} items
  494. */
  495. constructor(items, startOrdinal=null) {
  496. super();
  497. this.items = items;
  498. this.startOrdinal = startOrdinal;
  499. }
  500. htmlAttributes() {
  501. var html = super.htmlAttributes();
  502. if (this.startOrdinal !== null) {
  503. html += ` start="${this.startOrdinal}"`;
  504. }
  505. return html;
  506. }
  507. toHTML(state) {
  508. let contentHTML = _MDBlock.toHTML(this.items, state);
  509. return `<ol${this.htmlAttributes()}>\n${contentHTML}\n</ol>`;
  510. }
  511. }
  512. class _MDListItemBlock extends _MDBlock {
  513. /** @var {_MDBlock} */
  514. content;
  515. /** @var {Number|null} */
  516. ordinal;
  517. /**
  518. * @param {_MDBlock} content
  519. */
  520. constructor(content, ordinal=null) {
  521. super();
  522. this.content = content;
  523. this.ordinal = ordinal;
  524. }
  525. toHTML(state) {
  526. let contentHTML = this.content.toHTML(state);
  527. return `<li${this.htmlAttributes()}>${contentHTML}</li>`;
  528. }
  529. }
  530. class _MDCodeBlock extends _MDBlock {
  531. /** @var {String} */
  532. #code;
  533. /**
  534. * @param {String} code
  535. */
  536. constructor(code) {
  537. super();
  538. this.#code = code;
  539. }
  540. toHTML(state) {
  541. return `<pre${this.htmlAttributes()}><code>${this.#code}</code></pre>`;
  542. }
  543. }
  544. class _MDHorizontalRuleBlock extends _MDBlock {
  545. toHTML(state) {
  546. return `<hr${this.htmlAttributes()}>\n`;
  547. }
  548. }
  549. class _MDTableCellBlock extends _MDBlock {
  550. /** @var {_MDBlock} */
  551. #content;
  552. /** @var {_MDHAlign|null} */
  553. align = null;
  554. /**
  555. * @param {_MDBlock} content
  556. */
  557. constructor(content) {
  558. super();
  559. this.#content = content;
  560. }
  561. htmlAttributes() {
  562. var html = super.htmlAttributes();
  563. html += _MDHAlign.toHTMLAttribute(this.align);
  564. return html;
  565. }
  566. toHTML(state) {
  567. let contentHTML = this.#content.toHTML(state);
  568. return `<td${this.htmlAttributes()}>${contentHTML}</td>`;
  569. }
  570. }
  571. class _MDTableHeaderCellBlock extends _MDTableCellBlock {
  572. toHTML(state) {
  573. let html = super.toHTML(state);
  574. let groups = /^<td(.*)td>$/.exec(html);
  575. return `<th${groups[1]}th>`;
  576. }
  577. }
  578. class _MDTableRowBlock extends _MDBlock {
  579. /** @var {_MDTableCellBlock[]|_MDTableHeaderCellBlock[]} */
  580. #cells;
  581. /**
  582. * @param {_MDTableCellBlock[]|_MDTableHeaderCellBlock[]} cells
  583. */
  584. constructor(cells) {
  585. super();
  586. this.#cells = cells;
  587. }
  588. /**
  589. * @param {_MDHAlign[]} alignments
  590. */
  591. applyAlignments(alignments) {
  592. for (var i = 0; i < this.#cells.length; i++) {
  593. let cell = this.#cells[i];
  594. let align = i < alignments.length ? alignments[i] : null;
  595. cell.align = align;
  596. }
  597. }
  598. toHTML(state) {
  599. let cellsHTML = _MDBlock.toHTML(this.#cells, state);
  600. return `<tr${this.htmlAttributes()}>\n${cellsHTML}\n</tr>`;
  601. }
  602. }
  603. class _MDTableBlock extends _MDBlock {
  604. /** @var {_MDTableRowBlock} */
  605. #headerRow;
  606. /** @var {_MDTableRowBlock[]} */
  607. #bodyRows;
  608. /**
  609. * @param {_MDTableRowBlock} headerRow
  610. * @param {_MDTableRowBlock[]} bodyRows
  611. */
  612. constructor(headerRow, bodyRows) {
  613. super();
  614. this.#headerRow = headerRow;
  615. this.#bodyRows = bodyRows;
  616. }
  617. toHTML(state) {
  618. let headerRowHTML = this.#headerRow.toHTML(state);
  619. let bodyRowsHTML = _MDBlock.toHTML(this.#bodyRows, state);
  620. return `<table${this.htmlAttributes()}>\n<thead>\n${headerRowHTML}\n</thead>\n<tbody>\n${bodyRowsHTML}\n</tbody>\n</table>`;
  621. }
  622. }
  623. class _MDDefinitionListBlock extends _MDBlock {
  624. /** @var {_MDBlock[]} */
  625. #content;
  626. /**
  627. * @param {_MDBlock[]} content
  628. */
  629. constructor(content) {
  630. super();
  631. this.#content = content;
  632. }
  633. toHTML(state) {
  634. let contentHTML = _MDBlock.toHTML(this.#content, state);
  635. return `<dl${this.htmlAttributes()}>\n${contentHTML}\n</dl>`;
  636. }
  637. }
  638. class _MDDefinitionTermBlock extends _MDBlock {
  639. /** @var {_MDBlock} */
  640. #content;
  641. /**
  642. * @param {_MDBlock} content
  643. */
  644. constructor(content) {
  645. super();
  646. this.#content = content;
  647. }
  648. toHTML(state) {
  649. let contentHTML = this.#content.toHTML(state);
  650. return `<dt${this.htmlAttributes()}>${contentHTML}</dt>`;
  651. }
  652. }
  653. class _MDDefinitionDefinitionBlock extends _MDBlock {
  654. /** @var {_MDBlock} */
  655. #content;
  656. /**
  657. * @param {_MDBlock} content
  658. */
  659. constructor(content) {
  660. super();
  661. this.#content = content;
  662. }
  663. toHTML(state) {
  664. let contentHTML = this.#content.toHTML(state);
  665. return `<dd${this.htmlAttributes()}>${contentHTML}</dd>`;
  666. }
  667. }
  668. class _MDInlineBlock extends _MDBlock {
  669. /** @var {_MDSpan[]} */
  670. #content;
  671. /**
  672. * @param {_MDSpan[]} content
  673. */
  674. constructor(content) {
  675. super();
  676. this.#content = content;
  677. }
  678. toHTML(state) {
  679. return _MDSpan.toHTML(this.#content, state);
  680. }
  681. }
  682. class _MDHTMLTag {
  683. /** @var {String} */
  684. fullTag;
  685. /** @var {String} */
  686. tagName;
  687. /** @var {Boolean} */
  688. isCloser;
  689. /** @var {Object} */
  690. attributes;
  691. /**
  692. * @param {String} fullTag
  693. * @param {String} tagName
  694. * @param {Boolean} isCloser
  695. * @param {Object} attributes
  696. */
  697. constructor(fullTag, tagName, isCloser, attributes) {
  698. this.fullTag = fullTag;
  699. this.tagName = tagName;
  700. this.isCloser = isCloser;
  701. this.attributes = attributes;
  702. }
  703. }
  704. class _MDState {
  705. /** @var {String[]} */
  706. lines = [];
  707. /** @var {Object} */
  708. #abbreviations = {};
  709. /** @var {Object} */
  710. #abbreviationRegexes = {};
  711. /** @var {Object} */
  712. #footnotes = {};
  713. /** @var {Object} */
  714. #urlDefinitions = {};
  715. /** @var {Object} */
  716. #urlTitles = {};
  717. /** @var {number} */
  718. p = 0;
  719. /** @var {_MDState|null} */
  720. #parent = null;
  721. /** @var {Object} */
  722. get abbreviations() {
  723. return (this.#parent) ? this.#parent.abbreviations : this.#abbreviations;
  724. }
  725. /** @var {Object} */
  726. get abbreviationRegexes() {
  727. return (this.#parent) ? this.#parent.abbreviationRegexes : this.#abbreviationRegexes;
  728. }
  729. /** @var {Object} */
  730. get footnotes() {
  731. return (this.#parent) ? this.#parent.footnotes : this.#footnotes;
  732. }
  733. /** @var {Object} */
  734. get urls() {
  735. return (this.#parent) ? this.#parent.urls : this.#urlDefinitions;
  736. }
  737. /** @var {Object} */
  738. get urlTitles() {
  739. return (this.#parent) ? this.#parent.urlTitles : this.#urlTitles;
  740. }
  741. /**
  742. * @param {String[]} lines
  743. */
  744. copy(lines) {
  745. let cp = new _MDState();
  746. cp.#parent = this;
  747. cp.lines = lines;
  748. cp.p = 0;
  749. return cp;
  750. }
  751. /**
  752. * @param {String} abbreviation
  753. * @param {String} definition
  754. */
  755. defineAbbreviation(abbreviation, definition) {
  756. if (this.#parent) {
  757. this.#parent.defineAbbreviation(abbreviation, definition);
  758. return;
  759. }
  760. this.#abbreviations[abbreviation] = definition;
  761. let regex = new RegExp("\\b(" + abbreviation + ")\\b", "ig");
  762. this.#abbreviationRegexes[abbreviation] = regex;
  763. }
  764. /**
  765. * @param {String} symbol
  766. * @param {_MDBlock} footnote
  767. */
  768. defineFootnote(symbol, footnote) {
  769. if (this.#parent) {
  770. this.#parent.defineFootnote(symbol, footnote);
  771. } else {
  772. this.#footnotes[symbol] = footnote;
  773. }
  774. }
  775. defineURL(symbol, url, title=null) {
  776. if (this.#parent) {
  777. this.#parent.defineURL(symbol, url, title);
  778. } else {
  779. this.#urlDefinitions[symbol.toLowerCase()] = url;
  780. if (title !== null) {
  781. this.#urlTitles[symbol.toLowerCase()] = title;
  782. }
  783. }
  784. }
  785. hasLines(minCount, p=-1) {
  786. let relativeTo = (p < 0) ? this.p : p;
  787. return relativeTo + minCount <= this.lines.length;
  788. }
  789. }
  790. class _MDTagModifier {
  791. /** @var {String} */
  792. original;
  793. /** @var {String[]} */
  794. cssClasses = [];
  795. /** @var {String|null} */
  796. id = null;
  797. /** @var {Object} */
  798. attributes = {};
  799. static #baseClassRegex = /\.([a-z_\-][a-z0-9_\-]*?)/i;
  800. static #baseIdRegex = /#([a-z_\-][a-z0-9_\-]*?)/i;
  801. static #baseAttributeRegex = /([a-z0-9]+?)=([^\s\}]+?)/i;
  802. static #baseRegex = /\{([^}]+?)}/i;
  803. static #leadingClassRegex = new RegExp('^' + this.#baseRegex.source, 'i');
  804. static #trailingClassRegex = new RegExp('^(.*?)\\s*' + this.#baseRegex.source + '\\s*$', 'i');
  805. static #classRegex = new RegExp('^' + this.#baseClassRegex.source + '$', 'i'); // 1=classname
  806. static #idRegex = new RegExp('^' + this.#baseIdRegex.source + '$', 'i'); // 1=id
  807. static #attributeRegex = new RegExp('^' + this.#baseAttributeRegex.source + '$', 'i'); // 1=attribute name, 2=attribute value
  808. /**
  809. * @param {_MDBlock|_MDSpan} elem
  810. */
  811. applyTo(elem) {
  812. if (elem instanceof _MDBlock || elem instanceof _MDSpan) {
  813. elem.cssClasses = elem.cssClasses.concat(this.cssClasses);
  814. if (this.id) elem.id = this.id;
  815. for (const name in this.attributes) {
  816. elem.attributes[name] = this.attributes[name];
  817. }
  818. }
  819. }
  820. static #fromContents(contents) {
  821. let modifierTokens = contents.split(/\s+/);
  822. let mod = new _MDTagModifier();
  823. mod.original = `{${contents}}`;
  824. var groups;
  825. for (const token of modifierTokens) {
  826. if (token.trim() == '') continue;
  827. if (groups = this.#classRegex.exec(token)) {
  828. mod.cssClasses.push(groups[1]);
  829. } else if (groups = this.#idRegex.exec(token)) {
  830. mod.id = groups[1];
  831. } else if (groups = this.#attributeRegex.exec(token)) {
  832. mod.attributes[groups[1]] = groups[2];
  833. } else {
  834. return null;
  835. }
  836. }
  837. return mod;
  838. }
  839. /**
  840. * Extracts modifier from line.
  841. * @param {String} line
  842. * @returns {Array} Tuple with remaining line and _MDTagModifier.
  843. */
  844. static fromLine(line) {
  845. let groups = this.#trailingClassRegex.exec(line);
  846. if (groups === null) return [ line, null ];
  847. let bareLine = groups[1];
  848. let mod = this.#fromContents(groups[2]);
  849. return [ bareLine, mod ];
  850. }
  851. /**
  852. * Extracts modifier from head of string.
  853. * @param {String} line
  854. * @returns {_MDTagModifier}
  855. */
  856. static fromStart(line) {
  857. let groups = this.#leadingClassRegex.exec(line);
  858. if (groups === null) return null;
  859. return this.#fromContents(groups[1]);
  860. }
  861. /**
  862. * @param {String} line
  863. * @returns {String}
  864. */
  865. static strip(line) {
  866. let groups = this.#trailingClassRegex.exec(line);
  867. if (groups === null) return line;
  868. return groups[1];
  869. }
  870. }
  871. class Markdown {
  872. /**
  873. * @param {String} line
  874. */
  875. static #stripIndent(line, count=1) {
  876. let regex = new RegExp(`^(?: {1,4}|\\t){${count}}`);
  877. return line.replace(regex, '');
  878. }
  879. /**
  880. * @param {String} line
  881. * @param {Boolean} fullIndentsOnly
  882. * @returns {Number} indent count
  883. */
  884. static #countIndents(line, fullIndentsOnly=false) {
  885. var count = 0;
  886. var lastLine = line;
  887. while (line.length > 0) {
  888. line = (fullIndentsOnly)
  889. ? line.replace(/^(?: {4}|\t)/, '')
  890. : line.replace(/^(?: {1,4}|\t)/, '');
  891. if (line != lastLine) {
  892. count++;
  893. } else {
  894. break;
  895. }
  896. lastLine = line;
  897. }
  898. return count;
  899. }
  900. /**
  901. * @param {_MDState} state
  902. * @returns {_MDBlock[]}
  903. */
  904. static #readBlocks(state) {
  905. var blocks = [];
  906. while (state.hasLines(1)) {
  907. let block = this.#readNextBlock(state);
  908. if (block) {
  909. blocks.push(block);
  910. } else {
  911. break;
  912. }
  913. }
  914. return blocks;
  915. }
  916. /**
  917. * @param {_MDState} state
  918. * @returns {_MDBlock}
  919. */
  920. static #readNextBlock(state) {
  921. while (state.hasLines(1) && state.lines[state.p].trim().length == 0) {
  922. state.p++;
  923. }
  924. var block;
  925. block = this.#readUnderlineHeader(state); if (block) return block;
  926. block = this.#readHashHeader(state); if (block) return block;
  927. block = this.#readBlockQuote(state); if (block) return block;
  928. block = this.#readUnorderedList(state); if (block) return block;
  929. block = this.#readOrderedList(state); if (block) return block;
  930. block = this.#readFencedCodeBlock(state); if (block) return block;
  931. block = this.#readIndentedCodeBlock(state); if (block) return block;
  932. block = this.#readHorizontalRule(state); if (block) return block;
  933. block = this.#readTable(state); if (block) return block;
  934. block = this.#readFootnoteDef(state); if (block) return block;
  935. block = this.#readAbbreviationDef(state); if (block) return block;
  936. block = this.#readURLDef(state); if (block) return block;
  937. block = this.#readDefinitionList(state); if (block) return block;
  938. block = this.#readParagraph(state); if (block) return block;
  939. return null;
  940. }
  941. static #htmlTagNameFirstRegex = /[a-z]/i;
  942. static #htmlTagNameMedialRegex = /[a-z0-9]/i;
  943. static #htmlAttributeNameFirstRegex = /[a-z]/i;
  944. static #htmlAttributeNameMedialRegex = /[a-z0-9-]/i;
  945. static #whitespaceCharRegex = /\s/;
  946. /**
  947. * @param {String} line
  948. * @returns {_MDHTMLTag|null} HTML tag if possible
  949. */
  950. static #htmlTag(line) {
  951. let expectOpenBracket = 0;
  952. let expectCloserOrName = 1;
  953. let expectName = 2;
  954. let expectAttributeNameOrEnd = 3;
  955. let expectEqualsOrAttributeOrEnd = 4;
  956. let expectAttributeValue = 5;
  957. let expectCloseBracket = 6;
  958. var isCloser = false;
  959. var tagName = '';
  960. var attributeName = '';
  961. var attributeValue = '';
  962. var attributeQuote = null;
  963. var attributes = {};
  964. var fullTag = null;
  965. let endAttribute = function() {
  966. if (attributeName.length > 0) {
  967. if (attributeValue.length > 0 || attributeQuote) {
  968. attributes[attributeName] = attributeValue;
  969. } else {
  970. attributes[attributeName] = true;
  971. }
  972. }
  973. attributeName = '';
  974. attributeValue = '';
  975. attributeQuote = null;
  976. };
  977. var expect = expectOpenBracket;
  978. for (var p = 0; p < line.length && fullTag === null; p++) {
  979. let ch = line.substring(p, p + 1);
  980. let isWhitespace = this.#whitespaceCharRegex.exec(ch) !== null;
  981. switch (expect) {
  982. case expectOpenBracket:
  983. if (ch != '<') return null;
  984. expect = expectCloserOrName;
  985. break;
  986. case expectCloserOrName:
  987. if (ch == '/') {
  988. isCloser = true;
  989. } else {
  990. p--;
  991. }
  992. expect = expectName;
  993. break;
  994. case expectName:
  995. if (tagName.length == 0) {
  996. if (this.#htmlTagNameFirstRegex.exec(ch) === null) return null;
  997. tagName += ch;
  998. } else {
  999. if (this.#htmlTagNameMedialRegex.exec(ch)) {
  1000. tagName += ch;
  1001. } else {
  1002. p--;
  1003. expect = (isCloser) ? expectCloseBracket : expectAttributeNameOrEnd;
  1004. }
  1005. }
  1006. break;
  1007. case expectAttributeNameOrEnd:
  1008. if (attributeName.length == 0) {
  1009. if (isWhitespace) {
  1010. // skip whitespace
  1011. } else if (ch == '/') {
  1012. expect = expectCloseBracket;
  1013. } else if (ch == '>') {
  1014. fullTag = line.substring(0, p + 1);
  1015. break;
  1016. } else if (this.#htmlAttributeNameFirstRegex.exec(ch)) {
  1017. attributeName += ch;
  1018. } else {
  1019. return null;
  1020. }
  1021. } else if (isWhitespace) {
  1022. expect = expectEqualsOrAttributeOrEnd;
  1023. } else if (ch == '/') {
  1024. endAttribute();
  1025. expect = expectCloseBracket;
  1026. } else if (ch == '>') {
  1027. endAttribute();
  1028. fullTag = line.substring(0, p + 1);
  1029. break;
  1030. } else if (ch == '=') {
  1031. expect = expectAttributeValue;
  1032. } else if (this.#htmlAttributeNameMedialRegex.exec(ch)) {
  1033. attributeName += ch;
  1034. } else {
  1035. return null;
  1036. }
  1037. break;
  1038. case expectEqualsOrAttributeOrEnd:
  1039. if (ch == '=') {
  1040. expect = expectAttributeValue;
  1041. } else if (isWhitespace) {
  1042. // skip whitespace
  1043. } else if (ch == '/') {
  1044. expect = expectCloseBracket;
  1045. } else if (ch == '>') {
  1046. fullTag = line.substring(0, p + 1);
  1047. break;
  1048. } else if (this.#htmlAttributeNameFirstRegex.exec(ch)) {
  1049. endAttribute();
  1050. expect = expectAttributeNameOrEnd;
  1051. p--;
  1052. }
  1053. break;
  1054. case expectAttributeValue:
  1055. if (attributeValue.length == 0) {
  1056. if (attributeQuote === null) {
  1057. if (isWhitespace) {
  1058. // skip whitespace
  1059. } else if (ch == '"' || ch == "'") {
  1060. attributeQuote = ch;
  1061. } else {
  1062. attributeQuote = ''; // explicitly unquoted
  1063. p--;
  1064. }
  1065. } else {
  1066. if (ch === attributeQuote) {
  1067. // Empty string
  1068. endAttribute();
  1069. expect = expectAttributeNameOrEnd;
  1070. } else if (attributeQuote === '' && (ch == '/' || ch == '>')) {
  1071. return null;
  1072. } else {
  1073. attributeValue += ch;
  1074. }
  1075. }
  1076. } else {
  1077. if (ch === attributeQuote) {
  1078. endAttribute();
  1079. expect = expectAttributeNameOrEnd;
  1080. } else if (attributeQuote === '' && isWhitespace) {
  1081. endAttribute();
  1082. expect = expectAttributeNameOrEnd;
  1083. } else {
  1084. attributeValue += ch;
  1085. }
  1086. }
  1087. break;
  1088. case expectCloseBracket:
  1089. if (isWhitespace) {
  1090. // ignore whitespace
  1091. } else if (ch == '>') {
  1092. fullTag = line.substring(0, p + 1);
  1093. break;
  1094. }
  1095. break;
  1096. }
  1097. }
  1098. if (fullTag === null) return null;
  1099. endAttribute();
  1100. return new _MDHTMLTag(fullTag, tagName, isCloser, attributes);
  1101. }
  1102. static #textWhitespaceRegex = /^(\s*)(?:(\S|\S.*\S)(\s*?))?$/; // 1=leading WS, 2=text, 3=trailing WS
  1103. // Modified from https://urlregex.com/ to remove capture groups. Matches fully qualified URLs only.
  1104. static #baseURLRegex = /(?:(?:(?:[a-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[a-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[a-z0-9\.\-]+)(?:(?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/i;
  1105. // Modified from https://emailregex.com/ to remove capture groups.
  1106. 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;
  1107. static #footnoteWithTitleRegex = /^\[\^(\d+?)\s+"(.*?)"\]/; // 1=symbol, 2=title
  1108. static #footnoteRegex = /^\[\^(\d+?)\]/; // 1=symbol
  1109. static #urlWithTitleRegex = /^\((\S+?)\s+"(.*?)"\)/i; // 1=URL, 2=title
  1110. static #urlRegex = /^\((\S+?)\)/i; // 1=URL
  1111. static #emailWithTitleRegex = new RegExp("^\\(\\s*(" + this.#baseEmailRegex.source + ")\\s+\"(.*?)\"\\s*\\)", "i"); // 1=email, 2=title
  1112. static #emailRegex = new RegExp("^\\(\\s*(" + this.#baseEmailRegex.source + ")\\s*\\)", "i"); // 1=email
  1113. static #simpleURLRegex = new RegExp("^<" + this.#baseURLRegex.source + ">", "i"); // 1=URL
  1114. static #simpleEmailRegex = new RegExp("^<" + this.#baseEmailRegex.source + ">", "i"); // 1=email
  1115. /**
  1116. * Finds a `[label]` at the start of a string. Regex was too inefficient for this.
  1117. * @param {String} line
  1118. * @returns {String[]}
  1119. */
  1120. static #matchLabel(line) {
  1121. if (!line.startsWith('[')) return null;
  1122. var parenCount = 0;
  1123. var bracketCount = 0;
  1124. for (var p = 1; p < line.length; p++) {
  1125. let ch = line.substring(p, p + 1);
  1126. if (ch == '\\') {
  1127. p++;
  1128. } else 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. rawContent: contentTokens.map((token) => token.original).join(''),
  1387. };
  1388. } while (hasNewStart);
  1389. return null;
  1390. };
  1391. var spanMatch = null;
  1392. // Second pass - paired constructs. Prioritize pairs with no other paired tokens inside.
  1393. const delimiterTokens = new Set([
  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.rawContent));
  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. else if (spanMatch = matchPair([ _MDTokenType.Backtick ], disallowed)) {
  1419. spans.splice(spanMatch.startIndex, spanMatch.toDelete, new _MDCodeSpan(spanMatch.rawContent));
  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. }