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

markdown.js 54KB

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