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

markdown.js 55KB

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