PHP and Javascript implementations of a simple markdown parser
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

markdown.js 53KB

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