PHP and Javascript implementations of a simple markdown parser
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

markdown.js 55KB

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