PHP and Javascript implementations of a simple markdown parser
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

markdown.js 93KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610
  1. class MDTokenType {
  2. static Text = new MDTokenType('Text');
  3. static Whitespace = new MDTokenType('Whitespace');
  4. static Underscore = new MDTokenType('Underscore');
  5. static Asterisk = new MDTokenType('Asterisk');
  6. static Slash = new MDTokenType('Slash');
  7. static Tilde = new MDTokenType('Tilde');
  8. static Bang = new MDTokenType('Bang');
  9. static Backtick = new MDTokenType('Backtick');
  10. static Label = new MDTokenType('Label'); // content=label
  11. static URL = new MDTokenType('URL'); // content=URL, extra=title
  12. static Email = new MDTokenType('Email'); // content=email address, extra=title
  13. static SimpleLink = new MDTokenType('SimpleLink'); // content=URL
  14. static SimpleEmail = new MDTokenType('SimpleEmail'); // content=email address
  15. static Footnote = new MDTokenType('Footnote'); // content=symbol
  16. static Modifier = new MDTokenType('Modifier'); // content
  17. static HTMLTag = new MDTokenType('HTMLTag'); // content=tag string, tag=MDHTMLTag
  18. static META_AnyNonWhitespace = new MDTokenType('METAAnyNonWhitespace');
  19. static META_OptionalWhitespace = new MDTokenType('METAOptionalWhitespace');
  20. /** @type {string} */
  21. name;
  22. /**
  23. * @param {string} name
  24. */
  25. constructor(name) {
  26. this.name = name;
  27. }
  28. toString() {
  29. return `${this.constructor.name}.${this.name}`;
  30. }
  31. equals(other) {
  32. return (other instanceof MDTokenType) && other.name == this.name;
  33. }
  34. }
  35. class MDToken {
  36. /**
  37. * The original token string.
  38. * @type {string}
  39. */
  40. original;
  41. /** @type {MDTokenType} */
  42. type;
  43. /** @type {string|null} */
  44. content;
  45. /** @type {string|null} */
  46. extra;
  47. /** @type {MDHTMLTag|null} */
  48. tag;
  49. /** @type {MDTagModifier|null} */
  50. modifier;
  51. /**
  52. * @param {string} original
  53. * @param {MDTokenType} type
  54. * @param {string|MDTagModifier|null} content
  55. * @param {string|null} extra
  56. * @param {MDHTMLTag|null} tag
  57. */
  58. constructor(original, type, content=null, extra=null, tag=null) {
  59. this.original = original;
  60. this.type = type;
  61. if (content instanceof MDTagModifier) {
  62. this.content = null;
  63. this.modifier = content;
  64. } else {
  65. this.content = content;
  66. this.modifier = null;
  67. }
  68. this.extra = extra;
  69. this.tag = tag;
  70. }
  71. toString() {
  72. return `(${this.constructor.name} type=${this.type.toString()} content=${this.content})`;
  73. }
  74. /**
  75. * Searches an array of MDToken for the given pattern of MDTokenTypes.
  76. * If found, returns an object with the given keys.
  77. * - `tokens: MDToken[]` - the subarray of `tokensToSearch` that match the pattern
  78. * - `index: number` - index into `tokensToSearch` of first matching token
  79. *
  80. * @param {MDToken[]|MDSpan[]} tokensToSearch
  81. * @param {MDTokenType[]} pattern
  82. * @param {number} startIndex
  83. * @returns {object|null} match
  84. */
  85. static findFirstTokens(tokensToSearch, pattern, startIndex=0) {
  86. var matched = [];
  87. for (var t = startIndex; t < tokensToSearch.length; t++) {
  88. var matchedAll = true;
  89. matched = [];
  90. var patternOffset = 0;
  91. for (var p = 0; p < pattern.length; p++) {
  92. var t0 = t + p + patternOffset;
  93. if (t0 >= tokensToSearch.length) return null;
  94. let token = tokensToSearch[t0];
  95. let elem = pattern[p];
  96. if (elem == MDTokenType.META_OptionalWhitespace) {
  97. if (token instanceof MDToken && token.type == MDTokenType.Whitespace) {
  98. matched.push(token);
  99. } else {
  100. patternOffset--;
  101. }
  102. } else if (elem == MDTokenType.META_AnyNonWhitespace) {
  103. if (token instanceof MDToken && token.type == MDTokenType.Whitespace) {
  104. matchedAll = false;
  105. break;
  106. }
  107. matched.push(token);
  108. } else {
  109. if (!(token instanceof MDToken) || token.type != elem) {
  110. matchedAll = false;
  111. break;
  112. }
  113. matched.push(token);
  114. }
  115. }
  116. if (matchedAll) {
  117. return {
  118. 'tokens': matched,
  119. 'index': t,
  120. };
  121. }
  122. }
  123. return null;
  124. }
  125. /**
  126. * Searches an array of MDToken for a given starting pattern and ending
  127. * pattern and returns match info about both and the tokens in between.
  128. *
  129. * If `contentValidator` is specified, it will be called with the content
  130. * tokens of a potential match. If the validator returns `true`, the result
  131. * will be accepted and returned by this method. If the validator returns
  132. * `false`, this method will keep looking for another matching pair. If no
  133. * validator is given the first match will be returned regardless of content.
  134. *
  135. * If a match is found, returns an object with the given keys:
  136. * - `startTokens: MDToken[]` - tokens that matched `startPattern`
  137. * - `contentTokens: MDToken[]` - tokens between the start and end pattern. May be an empty array.
  138. * - `endTokens: MDToken[]` - tokens that matched `endPattern`
  139. * - `startIndex: number` - index into `tokensToSearch` where `startPattern` begins
  140. * - `contentIndex: number` - index into `tokensToSearch` of the first token that is between the start and end patterns
  141. * - `endIndex: number` - index into `tokensToSearch` where `endPattern` begins
  142. * - `totalLength: number` - total number of matched tokens
  143. *
  144. * @param {MDToken[]} tokensToSearch - array of `MDToken` to search in
  145. * @param {MDTokenType[]} startPattern - array of `MDTokenType` to find first
  146. * @param {MDTokenType[]} endPattern - array of `MDTokenType` to find positioned after `startPattern`
  147. * @param {function|null} contentValidator - optional validator function. If provided, will be passed an array of inner `MDToken`, and the function can return `true` to accept the contents or `false` to keep searching
  148. * @param {number} startIndex - token index where searching should begin
  149. * @returns {object|null} match object
  150. */
  151. static findPairedTokens(tokensToSearch, startPattern, endPattern, contentValidator=null, startIndex=0) {
  152. for (var s = startIndex; s < tokensToSearch.length; s++) {
  153. var startMatch = this.findFirstTokens(tokensToSearch, startPattern, s);
  154. if (startMatch === null) return null;
  155. var endStart = startMatch.index + startMatch.tokens.length;
  156. while (endStart < tokensToSearch.length) {
  157. var endMatch = this.findFirstTokens(tokensToSearch, endPattern, endStart);
  158. if (endMatch === null) break;
  159. var contents = tokensToSearch.slice(startMatch.index + startMatch.tokens.length, endMatch.index);
  160. if (contents.length > 0 && (contentValidator === null || contentValidator(contents))) {
  161. return {
  162. 'startTokens': startMatch.tokens,
  163. 'contentTokens': contents,
  164. 'endTokens': endMatch.tokens,
  165. 'startIndex': startMatch.index,
  166. 'contentIndex': startMatch.index + startMatch.tokens.length,
  167. 'endIndex': endMatch.index,
  168. 'totalLength': endMatch.index + endMatch.tokens.length - startMatch.index,
  169. };
  170. } else {
  171. // Contents rejected. Try next end match.
  172. endStart = endMatch.index + 1;
  173. }
  174. }
  175. // No end matches. Increment start match.
  176. s = startMatch.index;
  177. }
  178. return null;
  179. }
  180. equals(other) {
  181. if (!(other instanceof MDToken)) return false;
  182. if (other.original !== this.original) return false;
  183. if (!other.type.equals(this.type)) return false;
  184. if (other.content !== this.content) return false;
  185. if (other.extra !== this.extra) return false;
  186. if (!MDUtils.equal(other.tag, this.tag)) return false;
  187. if (!MDUtils.equals(other.modifier, this.modifier)) return false;
  188. return true
  189. }
  190. }
  191. class MDUtils {
  192. // Modified from https://urlregex.com/ to remove capture groups. Matches fully qualified URLs only.
  193. static baseURLRegex = /(?:(?:(?:[a-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[a-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[a-z0-9\.\-]+)(?:(?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/i;
  194. // Modified from https://emailregex.com/ to remove capture groups.
  195. 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;
  196. /**
  197. * Escapes special HTML characters.
  198. *
  199. * @param {string} str - string to escape
  200. * @param {boolean} encodeNewlinesAsBreaks - whether to convert newline characters to `<br>` tags
  201. * @returns {string} escaped HTML
  202. */
  203. static escapeHTML(str, encodeNewlinesAsBreaks=false) {
  204. if (typeof str !== 'string') return '';
  205. var html = str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  206. if (encodeNewlinesAsBreaks) {
  207. html = html.replace(/\n/g, "<br>\n");
  208. }
  209. return html;
  210. }
  211. /**
  212. * Encodes characters as HTML numeric entities to make it marginally more
  213. * difficult for web scrapers to grab sensitive info.
  214. *
  215. * @param {string} text - text to escape
  216. * @returns {string} escaped HTML
  217. */
  218. static escapeObfuscated(text) {
  219. var html = '';
  220. for (var p = 0; p < text.length; p++) {
  221. const cp = text.codePointAt(p);
  222. html += `&#${cp};`;
  223. }
  224. return html;
  225. }
  226. /**
  227. * Strips one or more leading indents from a line or lines of markdown. An
  228. * indent is defined as 4 spaces or one tab. Incomplete indents (i.e. 1-3
  229. * spaces) are treated like one indent level.
  230. *
  231. * @param {string|string[]} line - string or strings to strip
  232. * @param {number} levels - how many indent levels to strip
  233. * @returns {string|string[]} stripped lines
  234. */
  235. static stripIndent(line, levels=1) {
  236. const regex = new RegExp(`^(?: {1,4}|\t){${levels}}`);
  237. return (line instanceof Array) ? line.map((l) => l.replace(regex, '')) : line.replace(regex, '');
  238. }
  239. /**
  240. * Returns a copy of an array without any whitespace-only lines at the end.
  241. *
  242. * @param {String[]} lines - text lines
  243. * @returns {String[]} - text lines without trailing blank lines
  244. */
  245. static withoutTrailingBlankLines(lines) {
  246. var stripped = lines.slice();
  247. while (stripped.length > 0 && stripped[stripped.length - 1].trim().length == 0) {
  248. stripped.pop();
  249. }
  250. return stripped;
  251. }
  252. /**
  253. * Tests if an array of lines contains at least one blank. A blank line
  254. * can contain whitespace.
  255. *
  256. * @param {String[]} lines
  257. * @returns {boolean} whether `lines` contains any whitespace-only lines
  258. */
  259. static containsBlankLine(lines) {
  260. for (const line of lines) {
  261. if (line.trim().length == 0) return true;
  262. }
  263. return false;
  264. }
  265. /**
  266. * Counts the number of indent levels in a line of text. Partial indents
  267. * (1 to 3 spaces) are counted as one indent level unless `fullIndentsOnly`
  268. * is `true`.
  269. *
  270. * @param {string} line - line of markdown
  271. * @param {boolean} fullIndentsOnly - whether to only count full indent levels (4 spaces or a tab)
  272. * @returns {number} number of indent levels found
  273. */
  274. static countIndents(line, fullIndentsOnly=false) {
  275. // normalize indents to tabs
  276. return line.replace(fullIndentsOnly
  277. ? /(?: {4}|\t)/g
  278. : /(?: {1,4}|\t)/g,
  279. "\t")
  280. // remove content after indent
  281. .replace(/^(\t*)(.*?)$/, '$1')
  282. // count tabs
  283. .length;
  284. }
  285. /**
  286. * Attempts to parse a label from the beginning of `line`. A label is of the
  287. * form `[content]`. If found, returns an array with element 0 being the
  288. * entire label and element 1 being the content of the label.
  289. *
  290. * @param {string} line
  291. * @returns {string[]|null} match groups or null if not found
  292. */
  293. static tokenizeLabel(line) {
  294. if (!line.startsWith('[')) return null;
  295. var parenCount = 0;
  296. var bracketCount = 0;
  297. for (var p = 1; p < line.length; p++) {
  298. let ch = line.substring(p, p + 1);
  299. if (ch == '\\') {
  300. p++;
  301. } else if (ch == '(') {
  302. parenCount++;
  303. } else if (ch == ')') {
  304. parenCount--;
  305. if (parenCount < 0) return null;
  306. } else if (ch == '[') {
  307. bracketCount++;
  308. } else if (ch == ']') {
  309. if (bracketCount > 0) {
  310. bracketCount--;
  311. } else {
  312. return [ line.substring(0, p + 1), line.substring(1, p) ];
  313. }
  314. }
  315. }
  316. return null;
  317. }
  318. static #urlWithTitleRegex = /^\((\S+?)\s+"(.*?)"\)/i; // 1=URL, 2=title
  319. static #urlRegex = /^\((\S+?)\)/i; // 1=URL
  320. /**
  321. * Attempts to parse a URL from the beginning of `line`. A URL is of the
  322. * form `(url)` or `(url "title")`. If found, returns an array with element
  323. * 0 being the entire URL token, 1 is the URL, 2 is the optional title.
  324. *
  325. * @param {string} line
  326. * @returns {string[]} token tuple
  327. */
  328. static tokenizeURL(line) {
  329. var groups;
  330. if (groups = this.#urlWithTitleRegex.exec(line)) {
  331. if (this.tokenizeEmail(line)) return null; // make sure it's not better described as an email address
  332. return groups;
  333. }
  334. if (groups = this.#urlRegex.exec(line)) {
  335. if (this.tokenizeEmail(line)) return null;
  336. return [...groups, null];
  337. }
  338. return null;
  339. }
  340. static #emailWithTitleRegex = new RegExp("^\\(\\s*(" + MDUtils.baseEmailRegex.source + ")\\s+\"(.*?)\"\\s*\\)", "i"); // 1=email, 2=title
  341. static #emailRegex = new RegExp("^\\(\\s*(" + MDUtils.baseEmailRegex.source + ")\\s*\\)", "i"); // 1=email
  342. /**
  343. * Attempts to parse an email address from the beginning of `line`. An
  344. * email address is of the form `(user@example.com)` or `(user@example.com "link title")`.
  345. * If found, returns an array with element 0 being the entire token, 1 is the
  346. * email address, and 2 is the optional link title.
  347. *
  348. * @param {string} line
  349. * @returns {string[]} token tuple
  350. */
  351. static tokenizeEmail(line) {
  352. var groups;
  353. if (groups = this.#emailWithTitleRegex.exec(line)) {
  354. return groups;
  355. }
  356. if (groups = this.#emailRegex.exec(line)) {
  357. return [...groups, null];
  358. }
  359. return null;
  360. }
  361. /**
  362. * Describes the type of a variable for debugging.
  363. *
  364. * @param {any} value - value
  365. * @returns {String} description of type
  366. */
  367. static typename(value) {
  368. if (value === null) return 'null';
  369. if (value instanceof Object) {
  370. return value.constructor.name;
  371. }
  372. return typeof value;
  373. }
  374. static #equalArrays(a, b) {
  375. if (a === b) return true;
  376. if (!(a instanceof Array) || !(b instanceof Array)) return false;
  377. if (a == null || b == null) return false;
  378. if (a.length != b.length) return false;
  379. for (var i = 0; i < a.length; i++) {
  380. if (!this.equal(a[i], b[i])) return false;
  381. }
  382. return true;
  383. }
  384. static #equalObjects(a, b) {
  385. if (a === b) return true;
  386. if (!(a instanceof Object) || !(b instanceof Object)) return false;
  387. if (a == null || b == null) return false;
  388. if (a.equals !== undefined) {
  389. return a.equals(b);
  390. }
  391. for (const key of Object.keys(a)) {
  392. if (!this.equal(a[key], b[key])) return false;
  393. }
  394. for (const key of Object.keys(b)) {
  395. if (!this.equal(a[key], b[key])) return false;
  396. }
  397. return true;
  398. }
  399. /**
  400. * Tests for equality on lots of different kinds of values including objects
  401. * and arrays. Will use `.equals` on objects that implement it.
  402. *
  403. * @param {any} a
  404. * @param {any} b
  405. * @returns {boolean}
  406. */
  407. static equal(a, b, floatDifferencePercent=0.0) {
  408. if (a instanceof Array && b instanceof Array) {
  409. return this.#equalArrays(a, b);
  410. }
  411. if (a instanceof Object && b instanceof Object) {
  412. return this.#equalObjects(a, b);
  413. }
  414. if (typeof a == 'number' && typeof b == 'number') {
  415. if (a === b) return true;
  416. const delta = b - a;
  417. const ratio = delta / a;
  418. return Math.abs(ratio) <= floatDifferencePercent;
  419. }
  420. return a == b;
  421. }
  422. }
  423. // -- Block readers ---------------------------------------------------------
  424. /**
  425. * Base class for reading from an array of markdown lines and finding a block
  426. * of a given type. Readers are checked in `priority` order and `readBlock` is
  427. * called to see the reader implementation recognizes a particular kind of block
  428. * at the given line pointer, returning that block if so or null if not.
  429. *
  430. * Inline markdown is processed in a separate stage by `MDInlineReader`.
  431. */
  432. class MDBlockReader {
  433. /** @type {number} */
  434. #priority;
  435. /**
  436. * A unitless relative priority value that determines which readers are
  437. * tried first. Lower values are tried first. In the range of 0.0 to 100.0.
  438. * @type {number} priority
  439. */
  440. get priority() { return this.#priority; }
  441. /**
  442. * Creates a block reader.
  443. *
  444. * When overriding the constructor, it is suggested to allow the caller to
  445. * specify an optional custom priority value, falling back to a reasonable
  446. * default if not specified.
  447. *
  448. * @param {number} priority
  449. */
  450. constructor(priority) {
  451. this.#priority = priority;
  452. }
  453. /**
  454. * Attempts to read a block of this type from the given read state. If
  455. * successful, the state's line pointer should be incremented to the line
  456. * just after the last line of the block and the read block should be
  457. * returned.
  458. *
  459. * @param {MDState} state - read state
  460. * @returns {MDBlock|null} the read block
  461. */
  462. readBlock(state) {
  463. throw Error(`Abstract readBlock must be overridden in ${this.constructor.name}`);
  464. }
  465. /**
  466. * Called after the full document has been generated for optional
  467. * post-processing.
  468. *
  469. * @param {MDState} state
  470. * @param {MDBlock[]} blocks - top-level document block list
  471. */
  472. postProcess(state, blocks) {
  473. // no op
  474. }
  475. }
  476. /**
  477. * Reads markdown blocks for headers denoted with the underline syntax.
  478. *
  479. * Example:
  480. *
  481. * > ```markdown
  482. * > Header 1
  483. * > ========
  484. * > ```
  485. */
  486. class MDUnderlinedHeaderBlockReader extends MDBlockReader {
  487. constructor(priority=0.0) {
  488. super(priority);
  489. }
  490. /**
  491. * @param {MDState} state
  492. */
  493. readBlock(state) {
  494. var p = state.p;
  495. if (!state.hasLines(2)) return null;
  496. var modifier;
  497. let contentLine = state.lines[p++].trim();
  498. [contentLine, modifier] = MDTagModifier.fromLine(contentLine);
  499. let underLine = state.lines[p++].trim();
  500. if (contentLine == '') return null;
  501. if (/^=+$/.exec(underLine)) {
  502. state.p = p;
  503. let block = new MDHeaderBlock(1, state.inlineMarkdownToSpan(contentLine));
  504. if (modifier) modifier.applyTo(block);
  505. return block;
  506. }
  507. if (/^\-+$/.exec(underLine)) {
  508. state.p = p;
  509. let block = new MDHeaderBlock(2, state.inlineMarkdownToSpan(contentLine));
  510. if (modifier) modifier.applyTo(block);
  511. return block;
  512. }
  513. return null;
  514. }
  515. }
  516. /**
  517. * Reads markdown blocks for headers denoted with hash marks. Header levels 1 to
  518. * 6 are supported.
  519. *
  520. * Examples:
  521. *
  522. * > ```markdown
  523. * > # Header 1
  524. * >
  525. * > ## Header 2
  526. * >
  527. * > # Enclosing Hashes Are Optional #
  528. * >
  529. * > ## Trailing Hashes Don't Have to Match in Number ####
  530. * > ```
  531. */
  532. class MDHashHeaderBlockReader extends MDBlockReader {
  533. static #hashHeaderRegex = /^(#{1,6})\s*([^#].*?)\s*\#*\s*$/; // 1=hashes, 2=content
  534. constructor(priority=5.0) {
  535. super(priority);
  536. }
  537. readBlock(state) {
  538. var p = state.p;
  539. let line = state.lines[p++];
  540. var modifier;
  541. [line, modifier] = MDTagModifier.fromLine(line);
  542. var groups = MDHashHeaderBlockReader.#hashHeaderRegex.exec(line);
  543. if (groups === null) return null;
  544. state.p = p;
  545. const level = groups[1].length;
  546. const content = groups[2];
  547. let block = new MDHeaderBlock(level, new MDInlineBlock(state.inlineMarkdownToSpan(content)));
  548. if (modifier) modifier.applyTo(block);
  549. return block;
  550. }
  551. }
  552. /**
  553. * Reads markdown blocks for blockquoted text.
  554. *
  555. * Example:
  556. *
  557. * > ```markdown
  558. * > > Blockquoted text
  559. * > ```
  560. */
  561. class MDBlockQuoteBlockReader extends MDBlockReader {
  562. constructor(priority=10.0) {
  563. super(priority);
  564. }
  565. /**
  566. * @param {MDState} state
  567. */
  568. readBlock(state) {
  569. var blockquoteLines = [];
  570. var p = state.p;
  571. while (p < state.lines.length) {
  572. let line = state.lines[p++];
  573. if (line.startsWith(">")) {
  574. blockquoteLines.push(line);
  575. } else {
  576. break;
  577. }
  578. }
  579. if (blockquoteLines.length > 0) {
  580. let contentLines = blockquoteLines.map(function(line) {
  581. return line.substring(1).replace(/^ {0,3}\t?/, '');
  582. });
  583. let substate = state.copy(contentLines);
  584. let quotedBlocks = substate.readBlocks();
  585. state.p = p;
  586. return new MDBlockquoteBlock(quotedBlocks);
  587. }
  588. return null;
  589. }
  590. }
  591. /**
  592. * Abstract base class for ordered and unordered lists.
  593. */
  594. class MDBaseListBlockReader extends MDBlockReader {
  595. constructor(priority) {
  596. super(priority);
  597. }
  598. #readItemLines(state, firstLineStartPos) {
  599. var p = state.p;
  600. var lines = [];
  601. var seenBlankLine = false;
  602. var stripTrailingBlankLines = true;
  603. while (state.hasLines(1, p)) {
  604. const isFirstLine = p == state.p;
  605. var line = state.lines[p++];
  606. if (isFirstLine) {
  607. line = line.substring(firstLineStartPos);
  608. }
  609. if (/^(?:\*|\+|\-|\d+\.)\s+/.exec(line)) {
  610. // Found next list item
  611. stripTrailingBlankLines = false; // because this signals extra spacing intended
  612. break;
  613. }
  614. const isBlankLine = line.trim().length == 0;
  615. const isIndented = /^\s+\S/.exec(line) !== null;
  616. if (isBlankLine) {
  617. seenBlankLine = true;
  618. } else if (!isIndented && seenBlankLine) {
  619. // Post-list content
  620. break;
  621. }
  622. lines.push(line);
  623. }
  624. lines = MDUtils.withoutTrailingBlankLines(lines);
  625. return MDUtils.stripIndent(lines);
  626. }
  627. /**
  628. * @param {MDState} state
  629. * @param {number} firstLineStart
  630. * @return {MDBlock}
  631. */
  632. readListItemContent(state, firstLineStartPos) {
  633. const itemLines = this.#readItemLines(state, firstLineStartPos);
  634. state.p += Math.max(itemLines.length, 1);
  635. if (itemLines.length == 1) {
  636. return new MDInlineBlock(state.inlineMarkdownToSpans(itemLines[0]));
  637. }
  638. const hasBlankLines = itemLines.filter((line) => line.trim().length == 0).length > 0;
  639. if (hasBlankLines) {
  640. const substate = state.copy(itemLines);
  641. const blocks = substate.readBlocks();
  642. return (blocks.length == 1) ? blocks[0] : new MDMultiBlock(blocks);
  643. }
  644. // Multiline content with no blank lines. Search for new block
  645. // boundaries without the benefit of a blank line to demarcate it.
  646. for (var p = 1; p < itemLines.length; p++) {
  647. const line = itemLines[p];
  648. if (/^(?:\*|\-|\+|\d+\.)\s+/.exec(line)) {
  649. // Nested list found
  650. const firstBlock = new MDInlineBlock(state.inlineMarkdownToSpans(itemLines.slice(0, p).join("\n")));
  651. const substate = state.copy(itemLines.slice(p));
  652. const blocks = substate.readBlocks();
  653. return new MDMultiBlock([ firstBlock, ...blocks ]);
  654. }
  655. }
  656. // Ok, give up and just do a standard block read
  657. {
  658. const substate = state.copy(itemLines);
  659. const blocks = substate.readBlocks();
  660. return (blocks.length == 1) ? blocks[0] : new MDMultiBlock(blocks);
  661. }
  662. }
  663. readBlock(state) {
  664. throw new Error(`Abstract readBlock must be overridden in ${this.constructor.name}`);
  665. }
  666. }
  667. /**
  668. * Block reader for unordered (bulleted) lists.
  669. *
  670. * Example:
  671. *
  672. * > ```markdown
  673. * > * First item
  674. * > * Second item
  675. * > * Third item
  676. * > ```
  677. */
  678. class MDUnorderedListBlockReader extends MDBaseListBlockReader {
  679. static #unorderedListRegex = /^([\*\+\-]\s+)(.*)$/; // 1=bullet, 2=content
  680. constructor(priority=15.0) {
  681. super(priority);
  682. }
  683. /**
  684. * @param {MDState} state
  685. * @returns {MDListItemBlock|null}
  686. */
  687. #readUnorderedListItem(state) {
  688. var p = state.p;
  689. let line = state.lines[p];
  690. let groups = MDUnorderedListBlockReader.#unorderedListRegex.exec(line);
  691. if (groups === null) return null;
  692. const firstLineOffset = groups[1].length;
  693. return new MDListItemBlock(this.readListItemContent(state, firstLineOffset));
  694. }
  695. readBlock(state) {
  696. var items = [];
  697. var item = null;
  698. do {
  699. item = this.#readUnorderedListItem(state);
  700. if (item) items.push(item);
  701. } while (item);
  702. if (items.length == 0) return null;
  703. return new MDUnorderedListBlock(items);
  704. }
  705. }
  706. /**
  707. * Block reader for ordered (numbered) lists. The number of the first item is
  708. * used to begin counting. The subsequent items increase by 1, regardless of
  709. * their value.
  710. *
  711. * Example:
  712. *
  713. * > ```markdown
  714. * > 1. First
  715. * > 2. Second
  716. * > 3. Third
  717. * > ```
  718. */
  719. class MDOrderedListBlockReader extends MDBaseListBlockReader {
  720. static #orderedListRegex = /^(\d+)(\.\s+)(.*)$/; // 1=number, 2=dot, 3=content
  721. constructor(priority=16.0) {
  722. super(priority);
  723. }
  724. /**
  725. * @param {MDState} state
  726. * @returns {MDListItemBlock|null}
  727. */
  728. #readOrderedListItem(state) {
  729. var p = state.p;
  730. let line = state.lines[p];
  731. let groups = MDOrderedListBlockReader.#orderedListRegex.exec(line);
  732. if (groups === null) return null;
  733. const ordinal = parseInt(groups[1]);
  734. const firstLineOffset = groups[1].length + groups[2].length;
  735. return new MDListItemBlock(this.readListItemContent(state, firstLineOffset), ordinal);
  736. }
  737. readBlock(state) {
  738. var items = [];
  739. var item = null;
  740. do {
  741. item = this.#readOrderedListItem(state);
  742. if (item) items.push(item);
  743. } while (item);
  744. if (items.length == 0) return null;
  745. return new MDOrderedListBlock(items, items[0].ordinal);
  746. }
  747. }
  748. /**
  749. * Block reader for code blocks denoted by pairs of triple tickmarks.
  750. *
  751. * Example:
  752. *
  753. * > ```markdown
  754. * > \`\`\`
  755. * > function formattedAsCode() {
  756. * > }
  757. * > \`\`\`
  758. * > ```
  759. */
  760. class MDFencedCodeBlockReader extends MDBlockReader {
  761. constructor(priority=20.0) {
  762. super(priority);
  763. }
  764. readBlock(state) {
  765. if (!state.hasLines(2)) return null;
  766. var p = state.p;
  767. let openFenceLine = state.lines[p++];
  768. var modifier;
  769. [openFenceLine, modifier] = MDTagModifier.fromLine(openFenceLine);
  770. if (openFenceLine.trim() != '```') return null;
  771. var codeLines = [];
  772. while (state.hasLines(1, p)) {
  773. let line = state.lines[p++];
  774. if (line.trim() == '```') {
  775. state.p = p;
  776. let block = new MDCodeBlock(codeLines.join("\n"));
  777. if (modifier) modifier.applyTo(block);
  778. return block;
  779. }
  780. codeLines.push(line);
  781. }
  782. return null;
  783. }
  784. }
  785. /**
  786. * Block reader for code blocks denoted by indenting text.
  787. *
  788. * Example (indent spaces rendered visibly for clarity):
  789. *
  790. * > ```markdown
  791. * > ⎵⎵⎵⎵function formattedAsCode() {
  792. * > ⎵⎵⎵⎵}
  793. * > ```
  794. */
  795. class MDIndentedCodeBlockReader extends MDBlockReader {
  796. constructor(priority=21.0) {
  797. super(priority);
  798. }
  799. readBlock(state) {
  800. var p = state.p;
  801. var codeLines = [];
  802. while (state.hasLines(1, p)) {
  803. let line = state.lines[p++];
  804. if (MDUtils.countIndents(line, true) < 1) {
  805. p--;
  806. break;
  807. }
  808. codeLines.push(MDUtils.stripIndent(line));
  809. }
  810. if (codeLines.length == 0) return null;
  811. state.p = p;
  812. return new MDCodeBlock(codeLines.join("\n"));
  813. }
  814. }
  815. /**
  816. * Block reader for horizontal rules. Composed of three or more hypens or
  817. * asterisks on a line by themselves, with or without intermediate whitespace.
  818. *
  819. * Examples:
  820. *
  821. * > ```markdown
  822. * > ---
  823. * >
  824. * > - - -
  825. * >
  826. * > * * * * *
  827. * >
  828. * > ****
  829. * > ```
  830. */
  831. class MDHorizontalRuleBlockReader extends MDBlockReader {
  832. static #horizontalRuleRegex = /^\s*(?:\-(?:\s*\-){2,}|\*(?:\s*\*){2,})\s*$/;
  833. constructor(priority=25.0) {
  834. super(priority);
  835. }
  836. /**
  837. * @param {MDState} state
  838. * @returns {MDBlock|null}
  839. */
  840. readBlock(state) {
  841. var p = state.p;
  842. let line = state.lines[p++];
  843. var modifier;
  844. [line, modifier] = MDTagModifier.fromLine(line);
  845. if (MDHorizontalRuleBlockReader.#horizontalRuleRegex.exec(line)) {
  846. state.p = p;
  847. let block = new MDHorizontalRuleBlock();
  848. if (modifier) modifier.applyTo(block);
  849. return block;
  850. }
  851. return null;
  852. }
  853. }
  854. /**
  855. * Block reader for tables.
  856. *
  857. * Examples:
  858. *
  859. * > ```markdown
  860. * > Name | Age
  861. * > --- | ---
  862. * > Joe | 34
  863. * > Alice | 25
  864. * >
  865. * > | Leading | And Trailing |
  866. * > | - | - |
  867. * > | Required | for single column tables |
  868. * >
  869. * > | Left aligned column | Center aligned | Right aligned |
  870. * > | :-- | :--: | --: |
  871. * > | Joe | x | 34 |
  872. * > ```
  873. */
  874. class MDTableBlockReader extends MDBlockReader {
  875. constructor(priority=30.0) {
  876. super(priority);
  877. }
  878. /**
  879. * @param {MDState} state
  880. * @param {boolean} isHeader
  881. * @return {MDTableRowBlock|null}
  882. */
  883. #readTableRow(state, isHeader) {
  884. if (!state.hasLines(1)) return null;
  885. var p = state.p;
  886. let line = MDTagModifier.strip(state.lines[p++].trim());
  887. if (/.*\|.*/.exec(line) === null) return null;
  888. if (line.startsWith('|')) line = line.substring(1);
  889. if (line.endsWith('|')) line = line.substring(0, line.length - 1);
  890. let cellTokens = line.split('|');
  891. let cells = cellTokens.map(function(token) {
  892. let content = state.inlineMarkdownToSpan(token.trim());
  893. return isHeader ? new MDTableHeaderCellBlock(content) : new MDTableCellBlock(content);
  894. });
  895. state.p = p;
  896. return new MDTableRowBlock(cells);
  897. }
  898. /**
  899. * @param {string} line
  900. * @returns {string[]}
  901. */
  902. #parseColumnAlignments(line) {
  903. line = line.trim();
  904. if (line.startsWith('|')) line = line.substring(1);
  905. if (line.endsWith('|')) line = line.substring(0, line.length - 1);
  906. return line.split(/\s*\|\s*/).map(function(token) {
  907. if (token.startsWith(':')) {
  908. if (token.endsWith(':')) {
  909. return MDTableCellBlock.AlignCenter;
  910. }
  911. return MDTableCellBlock.AlignLeft;
  912. } else if (token.endsWith(':')) {
  913. return MDTableCellBlock.AlignRight;
  914. }
  915. return null;
  916. });
  917. }
  918. static #tableDividerRegex = /^\s*[|]?\s*(?:[:]?-+[:]?)(?:\s*\|\s*[:]?-+[:]?)*\s*[|]?\s*$/;
  919. readBlock(state) {
  920. if (!state.hasLines(2)) return null;
  921. let startP = state.p;
  922. let firstLine = state.lines[startP];
  923. var modifier = MDTagModifier.fromLine(firstLine)[1];
  924. let headerRow = this.#readTableRow(state, true);
  925. if (headerRow === null) {
  926. state.p = startP;
  927. return null;
  928. }
  929. let dividerLine = state.lines[state.p++];
  930. let dividerGroups = MDTableBlockReader.#tableDividerRegex.exec(dividerLine);
  931. if (dividerGroups === null) {
  932. state.p = startP;
  933. return null;
  934. }
  935. let columnAlignments = this.#parseColumnAlignments(dividerLine);
  936. headerRow.applyAlignments(columnAlignments);
  937. var bodyRows = [];
  938. while (state.hasLines(1)) {
  939. let row = this.#readTableRow(state, false);
  940. if (row === null) break;
  941. row.applyAlignments(columnAlignments);
  942. bodyRows.push(row);
  943. }
  944. let table = new MDTableBlock(headerRow, bodyRows);
  945. if (modifier) modifier.applyTo(table);
  946. return table;
  947. }
  948. }
  949. /**
  950. * Block reader for definition lists. Definitions go directly under terms starting
  951. * with a colon.
  952. *
  953. * Example:
  954. *
  955. * > ```markdown
  956. * > markdown
  957. * > : a language for generating HTML from simplified syntax
  958. * > parser
  959. * > : code that converts human-readable code into machine language
  960. * > ```
  961. */
  962. class MDDefinitionListBlockReader extends MDBlockReader {
  963. constructor(priority=35.0) {
  964. super(priority);
  965. }
  966. readBlock(state) {
  967. var p = state.p;
  968. var groups;
  969. var termCount = 0;
  970. var definitionCount = 0;
  971. var defLines = [];
  972. while (state.hasLines(1, p)) {
  973. let line = state.lines[p++];
  974. if (line.trim().length == 0) {
  975. break;
  976. }
  977. if (/^\s+/.exec(line)) {
  978. if (defLines.length == 0) return null;
  979. defLines[defLines.length - 1] += "\n" + line;
  980. } else if (/^:\s+/.exec(line)) {
  981. defLines.push(line);
  982. definitionCount++;
  983. } else {
  984. defLines.push(line);
  985. termCount++;
  986. }
  987. }
  988. if (termCount == 0 || definitionCount == 0) return null;
  989. let blocks = defLines.map(function(line) {
  990. if (groups = /^:\s+(.*?)$/s.exec(line)) {
  991. return new MDDefinitionDefinitionBlock(state.inlineMarkdownToSpans(groups[1]));
  992. } else {
  993. return new MDDefinitionTermBlock(state.inlineMarkdownToSpans(line));
  994. }
  995. });
  996. state.p = p;
  997. return new MDDefinitionListBlock(blocks);
  998. }
  999. }
  1000. /**
  1001. * Block reader for defining footnote contents. Footnotes can be defined anywhere
  1002. * in the document but will always be rendered at the end of a page or end of
  1003. * the document.
  1004. *
  1005. * Examples:
  1006. *
  1007. * > ```markdown
  1008. * > [^1]: Content of a footnote. Anywhere `[^1]` appears in the
  1009. * > main text, it will hyperlink to this content at the bottom
  1010. * > of the document. There will also be backlinks at the end
  1011. * > of this footnote to all references to it.
  1012. * > ```
  1013. */
  1014. class MDFootnoteDefinitionBlockReader extends MDBlockReader {
  1015. constructor(priority=40.0) {
  1016. super(priority);
  1017. }
  1018. /**
  1019. * @param {MDState} state
  1020. */
  1021. readBlock(state) {
  1022. var p = state.p;
  1023. let groups = /^\s*\[\^\s*([^\]]+)\s*\]:\s+(.*)\s*$/.exec(state.lines[p++]);
  1024. if (groups === null) return null;
  1025. let symbol = groups[1];
  1026. let def = groups[2];
  1027. while (state.hasLines(1, p)) {
  1028. let line = state.lines[p++];
  1029. if (/^\s+/.exec(line)) {
  1030. def += "\n" + line;
  1031. } else {
  1032. p--;
  1033. break;
  1034. }
  1035. }
  1036. state.p = p;
  1037. let content = state.inlineMarkdownToSpan(def);
  1038. state.defineFootnote(symbol, content);
  1039. state.p = p;
  1040. return new MDMultiBlock([]);
  1041. }
  1042. }
  1043. /**
  1044. * Block reader for abbreviation definitions. Anywhere the abbreviation appears
  1045. * in the text will have its definition available when hovering over it.
  1046. * Definitions can appear anywhere in the document. Their content should only
  1047. * contain simple text, not markdown.
  1048. *
  1049. * Example:
  1050. *
  1051. * > ```markdown
  1052. * > *[HTML]: Hyper Text Markup Language
  1053. * > ```
  1054. */
  1055. class MDAbbreviationDefinitionBlockReader extends MDBlockReader {
  1056. constructor(priority=45.0) {
  1057. super(priority);
  1058. }
  1059. readBlock(state) {
  1060. var p = state.p;
  1061. let line = state.lines[p++];
  1062. let groups = /^\s*\*\[([^\]]+?)\]:\s+(.*?)\s*$/.exec(line);
  1063. if (groups === null) return null;
  1064. let abbrev = groups[1];
  1065. let def = groups[2];
  1066. state.defineAbbreviation(abbrev, def);
  1067. state.p = p;
  1068. return new MDMultiBlock([]);
  1069. }
  1070. }
  1071. /**
  1072. * Block reader for URL definitions. Links in the document can include a
  1073. * reference instead of a verbatim URL so it can be defined in one place and
  1074. * reused in many places. These can be defined anywhere in the document. Nothing
  1075. * of the definition is rendered in the document.
  1076. *
  1077. * Example:
  1078. *
  1079. * > ```markdown
  1080. * > [foo]: https://example.com
  1081. * > ```
  1082. */
  1083. class MDURLDefinitionBlockReader extends MDBlockReader {
  1084. constructor(priority=50.0) {
  1085. super(priority);
  1086. }
  1087. readBlock(state) {
  1088. var p = state.p;
  1089. let line = state.lines[p++];
  1090. var symbol;
  1091. var url;
  1092. var title = null;
  1093. let groups = /^\s*\[(.+?)]:\s*(\S+)\s+"(.*?)"\s*$/.exec(line);
  1094. if (groups) {
  1095. symbol = groups[1];
  1096. url = groups[2];
  1097. title = groups[3];
  1098. } else {
  1099. groups = /^\s*\[(.+?)]:\s*(\S+)\s*$/.exec(line);
  1100. if (groups) {
  1101. symbol = groups[1];
  1102. url = groups[2];
  1103. } else {
  1104. return null;
  1105. }
  1106. }
  1107. state.defineURL(symbol, url, title);
  1108. state.p = p;
  1109. return new MDInlineBlock([]);
  1110. }
  1111. }
  1112. /**
  1113. * Block reader for simple paragraphs. Paragraphs are separated by a blank (or
  1114. * whitespace-only) line. This reader should be prioritized last since there
  1115. * is no distinguishing syntax.
  1116. *
  1117. * Example:
  1118. *
  1119. * > ```markdown
  1120. * > Lorem ipsum dolor
  1121. * > sit amet. This is all one paragraph.
  1122. * >
  1123. * > Beginning of a new paragraph.
  1124. * > ```
  1125. */
  1126. class MDParagraphBlockReader extends MDBlockReader {
  1127. constructor(priority=100.0) {
  1128. super(priority);
  1129. }
  1130. readBlock(state) {
  1131. var paragraphLines = [];
  1132. var p = state.p;
  1133. var foundBlankLine = false;
  1134. while (p < state.lines.length) {
  1135. let line = state.lines[p++];
  1136. if (line.trim().length == 0) {
  1137. foundBlankLine = true;
  1138. break;
  1139. }
  1140. paragraphLines.push(line);
  1141. }
  1142. if (state.p == 0 && p >= state.lines.length) {
  1143. // If it's the entire document don't wrap it in a paragraph
  1144. return null;
  1145. }
  1146. if (paragraphLines.length > 0) {
  1147. state.p = p;
  1148. let content = paragraphLines.join("\n");
  1149. return new MDParagraphBlock(new MDInlineBlock(state.inlineMarkdownToSpans(content)));
  1150. }
  1151. return null;
  1152. }
  1153. }
  1154. // -- Inline reader ---------------------------------------------------------
  1155. class MDInlineReader {
  1156. /** @type {number} */
  1157. #tokenizePriority;
  1158. /** @type {number|number[]} */
  1159. #substitutePriority;
  1160. /**
  1161. * A unitless relative tokenizing priority value that determines which
  1162. * readers are tried first. Lower values are tried first. Standard readers
  1163. * are in the range of 0.0 to 100.0 but any value is valid. Longer
  1164. * tokens should generally be prioritized over short or single character tokens.
  1165. *
  1166. * @returns {number} priority or priorities for tokenization
  1167. */
  1168. get tokenizePriority() { return this.#tokenizePriority; }
  1169. /**
  1170. * A unitless relative substitution priority value that determines which
  1171. * readers are tried first. Lower values are tried first. If an array of
  1172. * values is given, the same reader will be included twice in the
  1173. * prioritization. This allows for multiple passes. Standard readers
  1174. * are in the range of 0.0 to 100.0 but any value is valid. Priority should
  1175. * be used to help resolve ambiguous parsings, with longer, more complex
  1176. * constructions best prioritized before shorter, simpler ones.
  1177. *
  1178. * @returns {number|number[]} priority or priorities for substitution
  1179. */
  1180. get substitutePriority() { return this.#substitutePriority; }
  1181. /**
  1182. * @param {number} tokenizePriority
  1183. * @param {number|number[]} substitutePriority
  1184. */
  1185. constructor(tokenizePriority, substitutePriority) {
  1186. this.#tokenizePriority = tokenizePriority;
  1187. this.#substitutePriority = substitutePriority;
  1188. }
  1189. /**
  1190. * Attempts to read a token from the start of the given string.
  1191. *
  1192. * @param {string} remainingText - remainder of the current line of markdown text left to tokenize
  1193. * @returns {MDToken|null} a token or `null` if not found
  1194. */
  1195. readFirstToken(state, priority, remainingText) {
  1196. throw new Error(`Abstract readFirstToken must be overridden in ${this.constructor.name}`);
  1197. }
  1198. /**
  1199. * Attempts to substitute one or more tokens in the given array. The given
  1200. * array is edited in-place via `.splice` operations. It consists of mixed
  1201. * elements of unprocessed `MDToken` and interpreted `MDSpan` elements.
  1202. *
  1203. * If a structure consists of inner content that is also markdown encoded,
  1204. * those elements can be passed to `state.tokensToSpans` to resolve to an
  1205. * array of `MDSpan` elements.
  1206. *
  1207. * @param {MDState} state
  1208. * @param {number} priority - used to differentiate passes when multiple
  1209. * values of `this.substitutePriority` are given
  1210. * @param {MDToken[]|MDSpan[]} tokens - mixed array of `MDToken` and
  1211. * `MDSpan` elements to be modified by reference
  1212. * @returns {boolean} `true` if any substitutions were made; `false` if not
  1213. */
  1214. substituteTokens(state, priority, tokens) {
  1215. throw new Error(`Abstract substituteTokens must be overridden in ${this.constructor.name}`);
  1216. }
  1217. /**
  1218. * Called after the full document has been generated for optional
  1219. * post-processing.
  1220. *
  1221. * @param {MDState} state
  1222. * @param {MDBlock[]} blocks - top-level document block list
  1223. */
  1224. postProcess(state, blocks) {
  1225. // no op
  1226. }
  1227. }
  1228. /**
  1229. * Abstract base class for readers that look for one or more delimiting tokens
  1230. * around some content.
  1231. */
  1232. class MDSimplePairInlineReader extends MDInlineReader {
  1233. constructor(tokenizePriority, substitutePriority) {
  1234. super(tokenizePriority, substitutePriority);
  1235. }
  1236. /**
  1237. * Attempts a substitution of a matched pair of delimiting token types.
  1238. * If successful, the substitution is performed on `tokens` and `true` is
  1239. * returned, otherwise `false` is returned and the array is untouched.
  1240. *
  1241. * If multiple `substitutePriority` values are specified, the first pass
  1242. * will reject matches with the delimiting character inside the content
  1243. * tokens. If a single `substitutePriority` is given or a subsequent pass
  1244. * is performed with multiple values any contents will be accepted.
  1245. *
  1246. * @param {MDState} state
  1247. * @param {number} priority
  1248. * @param {MDToken[]} tokens
  1249. * @param {class} spanClass
  1250. * @param {MDTokenType} delimiter
  1251. * @param {number} count - how many times the token is repeated to form the delimiter
  1252. * @returns {boolean} `true` if substitution performed, `false` if not
  1253. */
  1254. attemptPair(state, priority, tokens, spanClass, delimiter, count=1, plaintext=false) {
  1255. let delimiters = Array(count).fill(delimiter);
  1256. let firstPassPriority = (this.substitutePriority instanceof Array) ? this.substitutePriority[0] : null;
  1257. let match = MDToken.findPairedTokens(tokens, delimiters, delimiters, function(content) {
  1258. const firstType = content[0] instanceof MDToken ? content[0].type : null;
  1259. const lastType = content[content.length - 1] instanceof MDToken ? content[content.length - 1].type : null;
  1260. if (firstType == MDTokenType.Whitespace) return false;
  1261. if (lastType == MDTokenType.Whitespace) return false;
  1262. if (priority == firstPassPriority) {
  1263. var innerCount = 0;
  1264. for (let token of content) {
  1265. if (token instanceof MDToken && token.type == delimiter) innerCount++;
  1266. }
  1267. if ((innerCount % 2) != 0) return false;
  1268. }
  1269. return true;
  1270. });
  1271. if (match === null) return false;
  1272. let content = (plaintext)
  1273. ? match.contentTokens.map((token) => token.original).join('')
  1274. : state.tokensToSpans(match.contentTokens);
  1275. tokens.splice(match.startIndex, match.totalLength, new spanClass(content));
  1276. return true;
  1277. }
  1278. }
  1279. class MDStrongInlineReader extends MDSimplePairInlineReader {
  1280. constructor(tokenizePriority=0.0, substitutePriority=[0.0, 50.0]) {
  1281. super(tokenizePriority, substitutePriority);
  1282. }
  1283. readFirstToken(state, priority, remainingText) {
  1284. if (remainingText.startsWith('*')) return new MDToken('*', MDTokenType.Asterisk);
  1285. if (remainingText.startsWith('_')) return new MDToken('_', MDTokenType.Underscore);
  1286. return null;
  1287. }
  1288. substituteTokens(state, priority, tokens) {
  1289. if (this.attemptPair(state, priority, tokens, MDStrongSpan, MDTokenType.Asterisk, 2)) return true;
  1290. if (this.attemptPair(state, priority, tokens, MDStrongSpan, MDTokenType.Underscore, 2)) return true;
  1291. return false;
  1292. }
  1293. }
  1294. class MDEmphasisInlineReader extends MDSimplePairInlineReader {
  1295. constructor(tokenizePriority=0.0, substitutePriority=[0.0, 50.0]) {
  1296. super(tokenizePriority, substitutePriority);
  1297. }
  1298. readFirstToken(state, priority, remainingText) {
  1299. if (remainingText.startsWith('*')) return new MDToken('*', MDTokenType.Asterisk);
  1300. if (remainingText.startsWith('_')) return new MDToken('_', MDTokenType.Underscore);
  1301. return null;
  1302. }
  1303. substituteTokens(state, priority, tokens) {
  1304. if (this.attemptPair(state, priority, tokens, MDEmphasisSpan, MDTokenType.Asterisk)) return true;
  1305. if (this.attemptPair(state, priority, tokens, MDEmphasisSpan, MDTokenType.Underscore)) return true;
  1306. return false;
  1307. }
  1308. }
  1309. class MDCodeInlineReader extends MDSimplePairInlineReader {
  1310. constructor(tokenizePriority=0.0, substitutePriority=0.0) {
  1311. super(tokenizePriority, substitutePriority);
  1312. }
  1313. readFirstToken(state, priority, remainingText) {
  1314. if (remainingText.startsWith('`')) return new MDToken('`', MDTokenType.Backtick);
  1315. return null;
  1316. }
  1317. substituteTokens(state, priority, tokens) {
  1318. // ignore priority
  1319. if (this.attemptPair(state, -1, tokens, MDCodeSpan, MDTokenType.Backtick, 2, true)) return true;
  1320. if (this.attemptPair(state, -1, tokens, MDCodeSpan, MDTokenType.Backtick, 1, true)) return true;
  1321. return false;
  1322. }
  1323. }
  1324. class MDStrikethroughInlineReader extends MDSimplePairInlineReader {
  1325. constructor(tokenizePriority=0.0, substitutePriority=[0.0, 50.0]) {
  1326. super(tokenizePriority, substitutePriority);
  1327. }
  1328. readFirstToken(state, priority, remainingText) {
  1329. if (remainingText.startsWith('~')) return new MDToken('~', MDTokenType.Tilde);
  1330. return null;
  1331. }
  1332. substituteTokens(state, priority, tokens) {
  1333. if (this.attemptPair(state, priority, tokens, MDStrikethroughSpan, MDTokenType.Tilde, 2)) return true;
  1334. if (this.attemptPair(state, priority, tokens, MDStrikethroughSpan, MDTokenType.Tilde)) return true;
  1335. return false;
  1336. }
  1337. }
  1338. class MDImageInlineReader extends MDInlineReader {
  1339. constructor(tokenizePriority=0.0, substitutePriority=0.0) {
  1340. super(tokenizePriority, substitutePriority);
  1341. }
  1342. readFirstToken(state, priority, remainingText) {
  1343. if (remainingText.startsWith('!')) return new MDToken('!', MDTokenType.Bang);
  1344. var groups;
  1345. if (groups = MDUtils.tokenizeLabel(remainingText)) {
  1346. return new MDToken(groups[0], MDTokenType.Label, groups[1]);
  1347. }
  1348. if (groups = MDUtils.tokenizeURL(remainingText)) {
  1349. return new MDToken(groups[0], MDTokenType.URL, groups[1], groups[2]);
  1350. }
  1351. return null;
  1352. }
  1353. substituteTokens(state, priority, tokens) {
  1354. var match;
  1355. if (match = MDToken.findFirstTokens(tokens, [ MDTokenType.Bang, MDTokenType.Label, MDTokenType.META_OptionalWhitespace, MDTokenType.URL ])) {
  1356. let alt = match.tokens[1].content;
  1357. let url = match.tokens[match.tokens.length - 1].content;
  1358. let title = match.tokens[match.tokens.length - 1].extra;
  1359. tokens.splice(match.index, match.tokens.length, new MDImageSpan(url, alt, title));
  1360. return true;
  1361. }
  1362. if (match = MDToken.findFirstTokens(tokens, [ MDTokenType.Bang, MDTokenType.Label, MDTokenType.META_OptionalWhitespace, MDTokenType.Label ])) {
  1363. let alt = match.tokens[1].content;
  1364. let ref = match.tokens[match.tokens.length - 1].content;
  1365. tokens.splice(match.index, match.tokens.length, new MDReferencedImageSpan(ref, alt));
  1366. return true;
  1367. }
  1368. return false;
  1369. }
  1370. }
  1371. class MDFootnoteInlineReader extends MDInlineReader {
  1372. static #footnoteWithTitleRegex = /^\[\^([^\]]+?)\s+"(.*?)"\]/; // 1=symbol, 2=title
  1373. static #footnoteRegex = /^\[\^([^\]]+?)\]/; // 1=symbol
  1374. constructor(tokenizePriority=0.0, substitutePriority=0.0) {
  1375. super(tokenizePriority, substitutePriority);
  1376. }
  1377. readFirstToken(state, priority, remainingText) {
  1378. var groups;
  1379. if (groups = MDFootnoteInlineReader.#footnoteWithTitleRegex.exec(remainingText)) {
  1380. return new MDToken(groups[0], MDTokenType.Footnote, groups[1], groups[2]);
  1381. }
  1382. if (groups = MDFootnoteInlineReader.#footnoteRegex.exec(remainingText)) {
  1383. return new MDToken(groups[0], MDTokenType.Footnote, groups[1]);
  1384. }
  1385. return null;
  1386. }
  1387. substituteTokens(state, priority, tokens) {
  1388. var match;
  1389. if (match = MDToken.findFirstTokens(tokens, [ MDTokenType.Footnote ])) {
  1390. let footnoteToken = match.tokens[0];
  1391. tokens.splice(match.index, 1, new MDFootnoteReferenceSpan(footnoteToken.content));
  1392. return true;
  1393. }
  1394. return false;
  1395. }
  1396. /**
  1397. * @param {MDState} state
  1398. * @param {MDBlock[]} blocks
  1399. */
  1400. postProcess(state, blocks) {
  1401. var unique = 1;
  1402. for (const block of blocks) {
  1403. block.visitChildren(function(node) {
  1404. if (!(node instanceof MDFootnoteReferenceSpan)) return;
  1405. node.differentiator = unique++;
  1406. state.registerUniqueFootnote(node.symbol, node.differentiator);
  1407. });
  1408. }
  1409. if (Object.keys(state.footnotes).length == 0) return;
  1410. blocks.push(new MDFootnoteListingBlock());
  1411. }
  1412. }
  1413. class MDLinkInlineReader extends MDInlineReader {
  1414. constructor(tokenizePriority=0.0, substitutePriority=0.0) {
  1415. super(tokenizePriority, substitutePriority);
  1416. }
  1417. readFirstToken(state, priority, remainingText) {
  1418. var groups;
  1419. if (groups = MDUtils.tokenizeLabel(remainingText)) {
  1420. return new MDToken(groups[0], MDTokenType.Label, groups[1]);
  1421. }
  1422. if (groups = MDUtils.tokenizeEmail(remainingText)) {
  1423. return new MDToken(groups[0], MDTokenType.Email, groups[1], groups[2]);
  1424. }
  1425. if (groups = MDUtils.tokenizeURL(remainingText)) {
  1426. return new MDToken(groups[0], MDTokenType.URL, groups[1], groups[2]);
  1427. }
  1428. return null;
  1429. }
  1430. /**
  1431. * @param {MDState} state
  1432. */
  1433. substituteTokens(state, priority, tokens) {
  1434. var match;
  1435. if (match = MDToken.findFirstTokens(tokens, [ MDTokenType.Label, MDTokenType.META_OptionalWhitespace, MDTokenType.URL ])) {
  1436. let text = match.tokens[0].content;
  1437. let url = match.tokens[match.tokens.length - 1].content;
  1438. let title = match.tokens[match.tokens.length - 1].extra;
  1439. tokens.splice(match.index, match.tokens.length, new MDLinkSpan(url, state.inlineMarkdownToSpan(text), title));
  1440. return true;
  1441. }
  1442. if (match = MDToken.findFirstTokens(tokens, [ MDTokenType.Label, MDTokenType.META_OptionalWhitespace, MDTokenType.Email ])) {
  1443. let text = match.tokens[0].content;
  1444. let email = match.tokens[match.tokens.length - 1].content;
  1445. let url = `mailto:${email}`;
  1446. let title = match.tokens[match.tokens.length - 1].extra;
  1447. tokens.splice(match.index, match.tokens.length, new MDLinkSpan(url, state.inlineMarkdownToSpan(text), title));
  1448. return true;
  1449. }
  1450. if (match = MDToken.findFirstTokens(tokens, [ MDTokenType.Label, MDTokenType.META_OptionalWhitespace, MDTokenType.Label ])) {
  1451. let text = match.tokens[0].content;
  1452. let ref = match.tokens[match.tokens.length - 1].content;
  1453. tokens.splice(match.index, match.tokens.length, new MDReferencedLinkSpan(ref, state.inlineMarkdownToSpan(text)));
  1454. return true;
  1455. }
  1456. return false;
  1457. }
  1458. }
  1459. class MDSimpleLinkInlineReader extends MDInlineReader {
  1460. static #simpleEmailRegex = new RegExp("^<(" + MDUtils.baseEmailRegex.source + ")>", "i"); // 1=email
  1461. static #simpleURLRegex = new RegExp("^<(" + MDUtils.baseURLRegex.source + ")>", "i"); // 1=URL
  1462. constructor(tokenizePriority=0.0, substitutePriority=0.0) {
  1463. super(tokenizePriority, substitutePriority);
  1464. }
  1465. readFirstToken(state, priority, remainingText) {
  1466. var groups;
  1467. if (groups = MDSimpleLinkInlineReader.#simpleEmailRegex.exec(remainingText)) {
  1468. return new MDToken(groups[0], MDTokenType.SimpleEmail, groups[1]);
  1469. }
  1470. if (groups = MDSimpleLinkInlineReader.#simpleURLRegex.exec(remainingText)) {
  1471. return new MDToken(groups[0], MDTokenType.SimpleLink, groups[1]);
  1472. }
  1473. return null;
  1474. }
  1475. #substituteEmail(state, tokens) {
  1476. const result = MDToken.findFirstTokens(tokens, [ MDTokenType.SimpleEmail ]);
  1477. if (result === null) return false;
  1478. /** @type {MDToken} */
  1479. const token = result.tokens[0];
  1480. const link = `mailto:${token.content}`;
  1481. const span = new MDLinkSpan(link, new MDObfuscatedTextSpan(token.content));
  1482. tokens.splice(result.index, 1, span);
  1483. return true;
  1484. }
  1485. #substituteURL(state, tokens) {
  1486. const result = MDToken.findFirstTokens(tokens, [ MDTokenType.SimpleLink ]);
  1487. if (result === null) return false;
  1488. /** @type {MDToken} */
  1489. const token = result.tokens[0];
  1490. const link = token.content;
  1491. const span = new MDLinkSpan(link, new MDTextSpan(link));
  1492. tokens.splice(result.index, 1, span);
  1493. return true;
  1494. }
  1495. substituteTokens(state, priority, tokens) {
  1496. if (this.#substituteEmail(state, tokens)) return true;
  1497. if (this.#substituteURL(state, tokens)) return true;
  1498. return false;
  1499. }
  1500. }
  1501. class MDHTMLTagInlineReader extends MDInlineReader {
  1502. constructor(tokenizePriority=0.0, substitutePriority=95.0) {
  1503. super(tokenizePriority, substitutePriority);
  1504. }
  1505. readFirstToken(state, priority, remainingText) {
  1506. var tag = MDHTMLTag.fromLineStart(remainingText);
  1507. if (tag) return new MDToken(tag.fullTag, MDTokenType.HTMLTag, tag.fullTag, null, tag);
  1508. return null;
  1509. }
  1510. substituteTokens(state, priority, tokens) {
  1511. const result = MDToken.findFirstTokens(tokens, [ MDTokenType.HTMLTag ]);
  1512. if (result === null) return false;
  1513. /** @type {MDToken} */
  1514. const token = result.tokens[0];
  1515. const tag = token.tag;
  1516. const span = new MDHTMLSpan(tag);
  1517. tokens.splice(result.index, 1, span);
  1518. return true;
  1519. }
  1520. }
  1521. class MDModifierInlineReader extends MDInlineReader {
  1522. constructor(tokenizePriority=0.0, substitutePriority=100.0) {
  1523. super(tokenizePriority, substitutePriority);
  1524. }
  1525. readFirstToken(state, priority, remainingText) {
  1526. var modifier = MDTagModifier.fromStart(remainingText);
  1527. if (modifier) return new MDToken(modifier.original, MDTokenType.Modifier, modifier);
  1528. return null;
  1529. }
  1530. substituteTokens(state, priority, tokens) {
  1531. // Modifiers are applied elsewhere, and if they're not it's fine if they're
  1532. // rendered as the original syntax.
  1533. return false;
  1534. }
  1535. }
  1536. // -- Blocks ----------------------------------------------------------------
  1537. class MDBlock {
  1538. /** @type {string[]} */
  1539. cssClasses = [];
  1540. /** @type {string|null} */
  1541. cssId = null;
  1542. /** @type {object} */
  1543. attributes = {};
  1544. /**
  1545. * @param {MDState} state
  1546. * @returns {string}
  1547. */
  1548. toHTML(state) {
  1549. throw new Error(`Abstract ${this.constructor.name}.toHTML must be implemented`);
  1550. }
  1551. /**
  1552. * @param {MDState} state
  1553. * @returns {string}
  1554. */
  1555. toPlaintext(state) {
  1556. throw new Error(`Abstract ${this.constructor.name}.toPlaintext must be implemented`);
  1557. }
  1558. htmlAttributes() {
  1559. var html = '';
  1560. if (this.cssClasses.length > 0) {
  1561. html += ` class="${this.cssClasses.join(' ')}"`;
  1562. }
  1563. if (this.cssId !== null) {
  1564. html += ` id="${this.cssId}"`;
  1565. }
  1566. for (const name in this.attributes) {
  1567. let value = this.attributes[name];
  1568. html += ` ${name}="${MDUtils.escapeHTML(value)}"`;
  1569. }
  1570. return html;
  1571. }
  1572. /**
  1573. * @param {MDBlock[]} blocks
  1574. * @param {MDState} state
  1575. * @returns {string}
  1576. */
  1577. static toHTML(blocks, state) {
  1578. return blocks.map((block) => block.toHTML(state)).join("\n");
  1579. }
  1580. /**
  1581. * @param {MDBlock[]} blocks
  1582. * @param {MDState} state
  1583. * @returns {string}
  1584. */
  1585. static toPlaintext(blocks, state) {
  1586. return blocks.map((block) => block.toPlaintext(state)).join("\n");
  1587. }
  1588. /**
  1589. * Visits all block and inline children of this block, calling the given
  1590. * function with each. Should be implemented for any block with child nodes.
  1591. *
  1592. * @param {function} fn
  1593. */
  1594. visitChildren(fn) {}
  1595. }
  1596. class MDMultiBlock extends MDBlock {
  1597. /** @type {MDBlock[]} */
  1598. blocks;
  1599. /**
  1600. * @param {MDBlock[]} blocks
  1601. */
  1602. constructor(blocks) {
  1603. super();
  1604. if (blocks instanceof Array) {
  1605. this.blocks = blocks;
  1606. } else {
  1607. throw new Error(`${MDUtils.typename(this)} expects MDBlock[], got ${MDUtils.typename(blocks)}`);
  1608. }
  1609. }
  1610. toHTML(state) {
  1611. return MDBlock.toHTML(this.blocks, state);
  1612. }
  1613. toPlaintext(state) {
  1614. return MDBlock.toPlaintext(this.blocks, state);
  1615. }
  1616. visitChildren(fn) {
  1617. for (const block of this.blocks) {
  1618. fn(block);
  1619. block.visitChildren(fn);
  1620. }
  1621. }
  1622. }
  1623. class MDParagraphBlock extends MDBlock {
  1624. /** @type {MDBlock[]} */
  1625. content;
  1626. /**
  1627. * @param {MDBlock|MDBlock[]} content
  1628. */
  1629. constructor(content) {
  1630. super();
  1631. if (content instanceof Array) {
  1632. this.content = content;
  1633. } else if (content instanceof MDBlock) {
  1634. this.content = [ content ];
  1635. } else {
  1636. throw new Error(`${MDUtils.typename(this)} expects MDBlock[] or MDBlock, got ${MDUtils.typename(content)}`);
  1637. }
  1638. }
  1639. toHTML(state) {
  1640. const contentHTML = MDBlock.toHTML(this.content, state);
  1641. return `<p${this.htmlAttributes()}>${contentHTML}</p>\n`;
  1642. }
  1643. toPlaintext(state) {
  1644. return MDBlock.toPlaintext(this.content, state);
  1645. }
  1646. visitChildren(fn) {
  1647. for (const child of this.content) {
  1648. fn(child);
  1649. child.visitChildren(fn);
  1650. }
  1651. }
  1652. }
  1653. class MDHeaderBlock extends MDBlock {
  1654. /** @type {number} */
  1655. level;
  1656. /** @type {MDBlock[]} */
  1657. content;
  1658. /**
  1659. * @param {number} level
  1660. * @param {MDBlock|MDBlock[]} content
  1661. */
  1662. constructor(level, content) {
  1663. super();
  1664. this.level = level;
  1665. this.content = (content instanceof Array) ? content : [ content ];
  1666. }
  1667. toHTML(state) {
  1668. let contentHTML = MDBlock.toHTML(this.content, state);
  1669. return `<h${this.level}${this.htmlAttributes()}>${contentHTML}</h${this.level}>\n`;
  1670. }
  1671. toPlaintext(state) {
  1672. return MDBlock.toPlaintext(this.content, state);
  1673. }
  1674. visitChildren(fn) {
  1675. for (const child of this.content) {
  1676. fn(child);
  1677. child.visitChildren(fn);
  1678. }
  1679. }
  1680. }
  1681. class MDBlockquoteBlock extends MDBlock {
  1682. /** @type {MDBlock[]} */
  1683. content;
  1684. /**
  1685. * @param {MDBlock|MDBlock[]} content
  1686. */
  1687. constructor(content) {
  1688. super();
  1689. this.content = (content instanceof MDBlock) ? [ content ] : content;
  1690. }
  1691. toHTML(state) {
  1692. let contentHTML = MDBlock.toHTML(this.content, state);
  1693. return `<blockquote${this.htmlAttributes()}>\n${contentHTML}\n</blockquote>`;
  1694. }
  1695. toPlaintext(state) {
  1696. return MDBlock.toPlaintext(this.content, state);
  1697. }
  1698. visitChildren(fn) {
  1699. for (const block of this.content) {
  1700. fn(block);
  1701. block.visitChildren(fn);
  1702. }
  1703. }
  1704. }
  1705. class MDUnorderedListBlock extends MDBlock {
  1706. /** @type {MDListItemBlock[]} */
  1707. items;
  1708. /**
  1709. * @param {MDListItemBlock[]} items
  1710. */
  1711. constructor(items) {
  1712. super();
  1713. this.items = items;
  1714. }
  1715. toHTML(state) {
  1716. let contentHTML = MDBlock.toHTML(this.items, state);
  1717. return `<ul${this.htmlAttributes()}>\n${contentHTML}\n</ul>`;
  1718. }
  1719. toPlaintext(state) {
  1720. return MDBlock.toPlaintext(this.items, state);
  1721. }
  1722. visitChildren(fn) {
  1723. for (const item of this.items) {
  1724. fn(item);
  1725. item.visitChildren(fn);
  1726. }
  1727. }
  1728. }
  1729. class MDOrderedListBlock extends MDBlock {
  1730. /** @type {MDListItemBlock[]} */
  1731. items;
  1732. /** @type {number|null} */
  1733. startOrdinal;
  1734. /**
  1735. * @param {MDListItemBlock[]} items
  1736. */
  1737. constructor(items, startOrdinal=null) {
  1738. super();
  1739. this.items = items;
  1740. this.startOrdinal = startOrdinal;
  1741. }
  1742. htmlAttributes() {
  1743. var html = super.htmlAttributes();
  1744. if (this.startOrdinal !== null && this.startOrdinal != 1) {
  1745. html += ` start="${this.startOrdinal}"`;
  1746. }
  1747. return html;
  1748. }
  1749. toHTML(state) {
  1750. let contentHTML = MDBlock.toHTML(this.items, state);
  1751. return `<ol${this.htmlAttributes()}>\n${contentHTML}\n</ol>`;
  1752. }
  1753. toPlaintext(state) {
  1754. return MDBlock.toPlaintext(this.items, state);
  1755. }
  1756. visitChildren(fn) {
  1757. for (const item of this.items) {
  1758. fn(item);
  1759. item.visitChildren(fn);
  1760. }
  1761. }
  1762. }
  1763. class MDListItemBlock extends MDBlock {
  1764. /** @type {MDBlock[]} */
  1765. content;
  1766. /** @type {number|null} */
  1767. ordinal;
  1768. /**
  1769. * @param {MDBlock|MDBlock[]} content
  1770. * @param {number|null} ordinal
  1771. */
  1772. constructor(content, ordinal=null) {
  1773. super();
  1774. if (content instanceof Array) {
  1775. this.content = content;
  1776. } else {
  1777. this.content = [ content ];
  1778. }
  1779. this.ordinal = ordinal;
  1780. }
  1781. toHTML(state) {
  1782. let contentHTML = MDBlock.toHTML(this.content, state);
  1783. return `<li${this.htmlAttributes()}>${contentHTML}</li>`;
  1784. }
  1785. toPlaintext(state) {
  1786. return MDBlock.toPlaintext(this.content, state);
  1787. }
  1788. visitChildren(fn) {
  1789. for (const child of this.content) {
  1790. fn(child);
  1791. child.visitChildren(fn);
  1792. }
  1793. }
  1794. }
  1795. class MDCodeBlock extends MDBlock {
  1796. /** @type {string} */
  1797. code;
  1798. /**
  1799. * @param {string} code
  1800. */
  1801. constructor(code) {
  1802. super();
  1803. this.code = code;
  1804. }
  1805. toHTML(state) {
  1806. return `<pre${this.htmlAttributes()}><code>${MDUtils.escapeHTML(this.code)}</code></pre>`;
  1807. }
  1808. toPlaintext(state) {
  1809. return this.code;
  1810. }
  1811. }
  1812. class MDHorizontalRuleBlock extends MDBlock {
  1813. toHTML(state) {
  1814. return `<hr${this.htmlAttributes()}>\n`;
  1815. }
  1816. toPlaintext(state) {
  1817. return '';
  1818. }
  1819. }
  1820. class MDTableCellBlock extends MDBlock {
  1821. static AlignLeft = 'left';
  1822. static AlignCenter = 'center';
  1823. static AlignRight = 'right';
  1824. /** @type {MDBlock} */
  1825. content;
  1826. /** @type {string|null} */
  1827. align = null;
  1828. /**
  1829. * @param {MDBlock} content
  1830. */
  1831. constructor(content) {
  1832. super();
  1833. this.content = content;
  1834. }
  1835. #alignAttribute() {
  1836. switch (this.align) {
  1837. case MDTableCellBlock.AlignLeft: return ' align="left"';
  1838. case MDTableCellBlock.AlignCenter: return ' align="center"';
  1839. case MDTableCellBlock.AlignRight: return ' align="right"';
  1840. default: return '';
  1841. }
  1842. }
  1843. htmlAttributes() {
  1844. var html = super.htmlAttributes();
  1845. html += this.#alignAttribute();
  1846. return html;
  1847. }
  1848. toHTML(state) {
  1849. let contentHTML = this.content.toHTML(state);
  1850. return `<td${this.htmlAttributes()}>${contentHTML}</td>`;
  1851. }
  1852. toPlaintext(state) {
  1853. return this.content.toPlaintext(state);
  1854. }
  1855. visitChildren(fn) {
  1856. fn(this.content);
  1857. this.content.visitChildren(fn);
  1858. }
  1859. }
  1860. class MDTableHeaderCellBlock extends MDTableCellBlock {
  1861. toHTML(state) {
  1862. let html = super.toHTML(state);
  1863. let groups = /^<td(.*)td>$/.exec(html);
  1864. return `<th${groups[1]}th>`;
  1865. }
  1866. }
  1867. class MDTableRowBlock extends MDBlock {
  1868. /** @type {MDTableCellBlock[]|MDTableHeaderCellBlock[]} */
  1869. cells;
  1870. /**
  1871. * @param {MDTableCellBlock[]|MDTableHeaderCellBlock[]} cells
  1872. */
  1873. constructor(cells) {
  1874. super();
  1875. this.cells = cells;
  1876. }
  1877. /**
  1878. * @param {string[]} alignments
  1879. */
  1880. applyAlignments(alignments) {
  1881. for (var i = 0; i < this.cells.length; i++) {
  1882. let cell = this.cells[i];
  1883. let align = i < alignments.length ? alignments[i] : null;
  1884. cell.align = align;
  1885. }
  1886. }
  1887. toHTML(state) {
  1888. let cellsHTML = MDBlock.toHTML(this.cells, state);
  1889. return `<tr${this.htmlAttributes()}>\n${cellsHTML}\n</tr>`;
  1890. }
  1891. toPlaintext(state) {
  1892. return this.cells.map((cell) => cell.toPlaintext(state)).join(' ');
  1893. }
  1894. visitChildren(fn) {
  1895. for (const cell of this.cells) {
  1896. fn(cell);
  1897. cell.visitChildren(fn);
  1898. }
  1899. }
  1900. }
  1901. class MDTableBlock extends MDBlock {
  1902. /** @type {MDTableRowBlock} */
  1903. headerRow;
  1904. /** @type {MDTableRowBlock[]} */
  1905. bodyRows;
  1906. /**
  1907. * @param {MDTableRowBlock} headerRow
  1908. * @param {MDTableRowBlock[]} bodyRows
  1909. */
  1910. constructor(headerRow, bodyRows) {
  1911. super();
  1912. this.headerRow = headerRow;
  1913. this.bodyRows = bodyRows;
  1914. }
  1915. toHTML(state) {
  1916. let headerRowHTML = this.headerRow.toHTML(state);
  1917. let bodyRowsHTML = MDBlock.toHTML(this.bodyRows, state);
  1918. return `<table${this.htmlAttributes()}>\n<thead>\n${headerRowHTML}\n</thead>\n<tbody>\n${bodyRowsHTML}\n</tbody>\n</table>`;
  1919. }
  1920. toPlaintext(state) {
  1921. return this.headerRow.toPlaintext(state) + "\n" + this.bodyRows.map((row) => row.toPlaintext(state)).join("\n");
  1922. }
  1923. visitChildren(fn) {
  1924. fn(this.headerRow);
  1925. this.headerRow.visitChildren(fn);
  1926. for (const row of this.bodyRows) {
  1927. fn(row);
  1928. row.visitChildren(fn);
  1929. }
  1930. }
  1931. }
  1932. class MDDefinitionListBlock extends MDBlock {
  1933. /** @type {MDBlock[]} */
  1934. content;
  1935. /**
  1936. * @param {MDBlock[]} content
  1937. */
  1938. constructor(content) {
  1939. super();
  1940. this.content = content;
  1941. }
  1942. toHTML(state) {
  1943. let contentHTML = MDBlock.toHTML(this.content, state);
  1944. return `<dl${this.htmlAttributes()}>\n${contentHTML}\n</dl>`;
  1945. }
  1946. toPlaintext(state) {
  1947. return MDBlock.toPlaintext(this.content, state);
  1948. }
  1949. visitChildren(fn) {
  1950. for (const block of this.content) {
  1951. fn(block);
  1952. block.visitChildren(fn);
  1953. }
  1954. }
  1955. }
  1956. class MDDefinitionTermBlock extends MDBlock {
  1957. /** @type {MDBlock[]} */
  1958. content;
  1959. /**
  1960. * @param {MDBlock|MDBlock[]} content
  1961. */
  1962. constructor(content) {
  1963. super();
  1964. if (content instanceof Array) {
  1965. this.content = content;
  1966. } else if (content instanceof MDBlock) {
  1967. this.content = [ content ];
  1968. } else {
  1969. throw new Error(`${this.constructor.name} expects MDBlock or MDBlock[], got ${typeof content}`);
  1970. }
  1971. }
  1972. toHTML(state) {
  1973. let contentHTML = MDBlock.toHTML(this.content, state);
  1974. return `<dt${this.htmlAttributes()}>${contentHTML}</dt>`;
  1975. }
  1976. toPlaintext(state) {
  1977. return MDBlock.toPlaintext(this.content, state);
  1978. }
  1979. visitChildren(fn) {
  1980. for (const child of this.content) {
  1981. fn(child);
  1982. child.visitChildren(fn);
  1983. }
  1984. }
  1985. }
  1986. class MDDefinitionDefinitionBlock extends MDBlock {
  1987. /** @type {MDBlock[]} */
  1988. content;
  1989. /**
  1990. * @param {MDBlock|MDBlock[]} content
  1991. */
  1992. constructor(content) {
  1993. super();
  1994. if (content instanceof Array) {
  1995. this.content = content;
  1996. } else if (content instanceof MDBlock) {
  1997. this.content = [ content ];
  1998. } else {
  1999. throw new Error(`${this.constructor.name} expects MDBlock or MDBlock[], got ${typeof content}`);
  2000. }
  2001. }
  2002. toHTML(state) {
  2003. let contentHTML = MDBlock.toHTML(this.content, state);
  2004. return `<dd${this.htmlAttributes()}>${contentHTML}</dd>`;
  2005. }
  2006. toPlaintext(state) {
  2007. return MDBlock.toPlaintext(this.content, state);
  2008. }
  2009. visitChildren(fn) {
  2010. for (const child of this.content) {
  2011. fn(child);
  2012. child.visitChildren(fn);
  2013. }
  2014. }
  2015. }
  2016. class MDFootnoteListingBlock extends MDBlock {
  2017. constructor() {
  2018. super();
  2019. }
  2020. /**
  2021. * @param {MDState} state
  2022. */
  2023. toHTML(state) {
  2024. const footnotes = state.footnotes;
  2025. var symbolOrder = Object.keys(footnotes);
  2026. if (Object.keys(footnotes).length == 0) return '';
  2027. const footnoteUniques = state.footnoteInstances;
  2028. var html = '';
  2029. html += '<div class="footnotes"><hr/>';
  2030. html += '<ol>';
  2031. for (const symbol of symbolOrder) {
  2032. /** @type {MDBlock} */
  2033. let content = footnotes[symbol];
  2034. if (!content) continue;
  2035. html += `<li value="${symbol}" id="footnote_${symbol}">${content.toHTML(state)}`;
  2036. for (const unique of footnoteUniques[symbol]) {
  2037. html += ` <a href="#footnoteref_${unique}" class="footnote-backref">↩︎</a>`;
  2038. }
  2039. html += `</li>\n`;
  2040. }
  2041. html += '</ol>';
  2042. html += '</div>';
  2043. return html;
  2044. }
  2045. toPlaintext(state) {
  2046. const footnotes = state.footnotes;
  2047. var symbolOrder = Object.keys(footnotes);
  2048. if (Object.keys(footnotes).length == 0) return '';
  2049. var text = '';
  2050. for (const symbol of symbolOrder) {
  2051. let content = footnotes[symbol];
  2052. if (!content) continue;
  2053. text += `${symbol}. ${content.toPlaintext(state)}\n`;
  2054. }
  2055. return text.trim();
  2056. }
  2057. }
  2058. class MDInlineBlock extends MDBlock {
  2059. /** @type {MDSpan[]} */
  2060. content;
  2061. /**
  2062. * @param {MDSpan|MDSpan[]} content
  2063. */
  2064. constructor(content) {
  2065. super();
  2066. this.content = (content instanceof Array) ? content : [ content ];
  2067. for (const span of this.content) {
  2068. if (!(span instanceof MDSpan)) {
  2069. throw new Error(`${this.constructor.name} expects MDSpan or MDSpan[], got ${MDUtils.typename(span)}`);
  2070. }
  2071. }
  2072. }
  2073. toHTML(state) {
  2074. return MDSpan.toHTML(this.content, state);
  2075. }
  2076. toPlaintext(state) {
  2077. return MDSpan.toPlaintext(this.content, state);
  2078. }
  2079. visitChildren(fn) {
  2080. for (const span of this.content) {
  2081. fn(span);
  2082. span.visitChildren(fn);
  2083. }
  2084. }
  2085. }
  2086. // -- Spans -----------------------------------------------------------------
  2087. class MDSpan {
  2088. /** @type {string[]} */
  2089. cssClasses = [];
  2090. /** @type {string|null} */
  2091. cssId = null;
  2092. /** @type {object} */
  2093. attributes = {};
  2094. /**
  2095. * @param {MDState} state
  2096. * @returns {string} HTML
  2097. */
  2098. toHTML(state) {
  2099. throw new Error(`Abstract ${this.constructor.name}.toHTML must be implemented`);
  2100. }
  2101. toPlaintext(state) {
  2102. throw new Error(`Abstract ${this.constructor.name}.toPlaintext must be implemented`);
  2103. }
  2104. htmlAttributes() {
  2105. var html = '';
  2106. if (this.cssClasses.length > 0) {
  2107. html += ` class="${this.cssClasses.join(' ')}"`;
  2108. }
  2109. if (this.cssId !== null) {
  2110. html += ` id="${this.cssId}"`;
  2111. }
  2112. for (const name in this.attributes) {
  2113. let value = this.attributes[name];
  2114. html += ` ${name}="${MDUtils.escapeHTML(value)}"`;
  2115. }
  2116. return html;
  2117. }
  2118. /**
  2119. * @param {MDSpan[]} spans
  2120. * @param {MDState} state
  2121. * @returns {string}
  2122. */
  2123. static toHTML(spans, state) {
  2124. return spans.map((span) => span.toHTML(state)).join('');
  2125. }
  2126. /**
  2127. * @param {MDSpan[]} spans
  2128. * @param {MDState} state
  2129. * @returns {string}
  2130. */
  2131. static toPlaintext(spans, state) {
  2132. return spans.map((span) => span.toPlaintext(state)).join('');
  2133. }
  2134. /**
  2135. * Visits all inline children of this span, calling the given function with
  2136. * each. Should be implemented for any span with child nodes.
  2137. *
  2138. * @param {function} fn
  2139. */
  2140. visitChildren(fn) {}
  2141. }
  2142. class MDMultiSpan extends MDSpan {
  2143. /** @type {MDSpan[]} */
  2144. content;
  2145. /**
  2146. * @param {MDSpan[]} content
  2147. */
  2148. constructor(content) {
  2149. super();
  2150. this.content = content;
  2151. }
  2152. toHTML(state) {
  2153. return MDSpan.toHTML(this.content, state);
  2154. }
  2155. toPlaintext(state) {
  2156. return MDSpan.toPlaintext(this.content, state);
  2157. }
  2158. visitChildren(fn) {
  2159. for (const span of this.content) {
  2160. fn(span);
  2161. span.visitChildren(fn);
  2162. }
  2163. }
  2164. }
  2165. class MDTextSpan extends MDSpan {
  2166. /** @param {string} text */
  2167. text;
  2168. /**
  2169. * @param {string} text
  2170. */
  2171. constructor(text) {
  2172. super();
  2173. this.text = text;
  2174. }
  2175. toHTML(state) {
  2176. let html = MDUtils.escapeHTML(this.text);
  2177. let abbrevs = state.abbreviations;
  2178. let regexes = state.abbreviationRegexes;
  2179. for (const abbrev in abbrevs) {
  2180. let def = abbrevs[abbrev];
  2181. let regex = regexes[abbrev];
  2182. let escapedDef = MDUtils.escapeHTML(def);
  2183. html = html.replace(regex, `<abbr title="${escapedDef}">$1</abbr>`);
  2184. }
  2185. return html;
  2186. }
  2187. toPlaintext(state) {
  2188. return this.text;
  2189. }
  2190. }
  2191. class MDHTMLSpan extends MDSpan {
  2192. /** @param {string} */
  2193. tag;
  2194. /**
  2195. * @param {MDHTMLTag} tag
  2196. */
  2197. constructor(tag) {
  2198. super();
  2199. this.tag = tag;
  2200. }
  2201. toHTML(state) {
  2202. return this.tag.fullTag;
  2203. }
  2204. toPlaintext(state) {
  2205. return '';
  2206. }
  2207. }
  2208. class MDObfuscatedTextSpan extends MDSpan {
  2209. /** @param {string} text */
  2210. text;
  2211. /**
  2212. * @param {string} text
  2213. */
  2214. constructor(text) {
  2215. super();
  2216. this.text = text;
  2217. }
  2218. toHTML(state) {
  2219. return MDUtils.escapeObfuscated(this.text);
  2220. }
  2221. toPlaintext(state) {
  2222. return this.text;
  2223. }
  2224. }
  2225. class MDLinkSpan extends MDSpan {
  2226. /** @type {string} */
  2227. link;
  2228. /** @type {string|null} */
  2229. target = null;
  2230. /** @type {MDSpan} */
  2231. content;
  2232. /** @type {string|null} */
  2233. title = null;
  2234. /**
  2235. * @param {string} link
  2236. * @param {MDSpan} content
  2237. * @param {string|null} title
  2238. */
  2239. constructor(link, content, title=null) {
  2240. super();
  2241. this.link = link;
  2242. this.content = content;
  2243. this.title = title;
  2244. }
  2245. toHTML(state) {
  2246. var escapedLink;
  2247. if (this.link.startsWith('mailto:')) {
  2248. escapedLink = 'mailto:' + MDUtils.escapeObfuscated(this.link.substring(7));
  2249. } else {
  2250. escapedLink = MDUtils.escapeHTML(this.link);
  2251. }
  2252. var html = `<a href="${escapedLink}"`;
  2253. if (this.target) {
  2254. html += ` target="${MDUtils.escapeHTML(this.target)}"`;
  2255. }
  2256. if (this.title) {
  2257. html += ` title="${MDUtils.escapeHTML(this.title)}"`;
  2258. }
  2259. html += this.htmlAttributes();
  2260. html += '>' + this.content.toHTML(state) + '</a>';
  2261. return html;
  2262. }
  2263. toPlaintext(state) {
  2264. return this.content.toPlaintext(state);
  2265. }
  2266. visitChildren(fn) {
  2267. fn(this.content);
  2268. this.content.visitChildren(fn);
  2269. }
  2270. }
  2271. class MDReferencedLinkSpan extends MDLinkSpan {
  2272. /** @type {string} */
  2273. ref;
  2274. constructor(ref, content) {
  2275. super(null, content, null);
  2276. this.ref = ref;
  2277. }
  2278. /**
  2279. * @param {MDState} state
  2280. */
  2281. toHTML(state) {
  2282. if (!this.link) {
  2283. let url = state.urls[this.ref.toLowerCase()];
  2284. let title = state.urlTitles[this.ref.toLowerCase()];
  2285. this.link = url;
  2286. this.title = title || this.title;
  2287. }
  2288. if (this.link) {
  2289. return super.toHTML(state);
  2290. } else {
  2291. let contentHTML = this.content.toHTML(state);
  2292. return `[${contentHTML}][${this.ref}]`;
  2293. }
  2294. }
  2295. }
  2296. class MDEmphasisSpan extends MDSpan {
  2297. /** @type {MDSpan[]} */
  2298. content;
  2299. /**
  2300. * @param {MDSpan|MDSpan[]} content
  2301. */
  2302. constructor(content) {
  2303. super();
  2304. this.content = (content instanceof MDSpan) ? [ content ] : content;
  2305. }
  2306. toHTML(state) {
  2307. let contentHTML = MDSpan.toHTML(this.content, state);
  2308. return `<em${this.htmlAttributes()}>${contentHTML}</em>`;
  2309. }
  2310. toPlaintext(state) {
  2311. return MDSpan.toPlaintext(this.content, state);
  2312. }
  2313. visitChildren(fn) {
  2314. for (const span of this.content) {
  2315. fn(span);
  2316. span.visitChildren(fn);
  2317. }
  2318. }
  2319. }
  2320. class MDStrongSpan extends MDSpan {
  2321. /** @type {MDSpan[]} content */
  2322. content;
  2323. /**
  2324. * @param {MDSpan|MDSpan[]} content
  2325. */
  2326. constructor(content) {
  2327. super();
  2328. this.content = (content instanceof MDSpan) ? [content] : content;
  2329. }
  2330. toHTML(state) {
  2331. let contentHTML = MDSpan.toHTML(this.content, state);
  2332. return `<strong${this.htmlAttributes()}>${contentHTML}</strong>`;
  2333. }
  2334. toPlaintext(state) {
  2335. return MDSpan.toPlaintext(this.content, state);
  2336. }
  2337. visitChildren(fn) {
  2338. for (const span of this.content) {
  2339. fn(span);
  2340. span.visitChildren(fn);
  2341. }
  2342. }
  2343. }
  2344. class MDStrikethroughSpan extends MDSpan {
  2345. /** @type {MDSpan[]} content */
  2346. content;
  2347. /**
  2348. * @param {MDSpan|MDSpan[]} content
  2349. */
  2350. constructor(content) {
  2351. super();
  2352. this.content = (content instanceof MDSpan) ? [content] : content;
  2353. }
  2354. toHTML(state) {
  2355. let contentHTML = MDSpan.toHTML(this.content, state);
  2356. return `<strike${this.htmlAttributes()}>${contentHTML}</strike>`;
  2357. }
  2358. toPlaintext(state) {
  2359. return MDSpan.toPlaintext(this.content, state);
  2360. }
  2361. visitChildren(fn) {
  2362. for (const span of this.content) {
  2363. fn(span);
  2364. span.visitChildren(fn);
  2365. }
  2366. }
  2367. }
  2368. class MDCodeSpan extends MDSpan {
  2369. /** @type {String} content */
  2370. content;
  2371. /**
  2372. * @param {String} content
  2373. */
  2374. constructor(content) {
  2375. super();
  2376. if (typeof content == 'string') {
  2377. this.content = content;
  2378. } else {
  2379. throw new Error(`${this.constructor.name} content must be String, got ${typeof content}`);
  2380. }
  2381. }
  2382. toHTML(state) {
  2383. return `<code${this.htmlAttributes()}>${MDUtils.escapeHTML(this.content)}</code>`;
  2384. }
  2385. toPlaintext(state) {
  2386. return this.content;
  2387. }
  2388. }
  2389. class MDImageSpan extends MDSpan {
  2390. /** @type {string} */
  2391. source;
  2392. /** @type {string|null} */
  2393. alt;
  2394. /** @type {string|null} */
  2395. title;
  2396. /**
  2397. * @param {string} source - image URL
  2398. * @param {string} alt - alt text
  2399. * @param {string|null} title - optional title attribute
  2400. */
  2401. constructor(source, alt, title=null) {
  2402. super();
  2403. this.source = source;
  2404. this.alt = alt;
  2405. this.title = title;
  2406. }
  2407. toHTML(state) {
  2408. let html = `<img src="${MDUtils.escapeHTML(this.source)}"`;
  2409. if (this.alt) {
  2410. html += ` alt="${MDUtils.escapeHTML(this.alt)}"`;
  2411. }
  2412. if (this.title) {
  2413. html += ` title="${MDUtils.escapeHTML(this.title)}"`;
  2414. }
  2415. html += this.htmlAttributes();
  2416. html += '>';
  2417. return html;
  2418. }
  2419. toPlaintext(state) {
  2420. return this.alt || '';
  2421. }
  2422. }
  2423. class MDReferencedImageSpan extends MDImageSpan {
  2424. /** @type {string} */
  2425. ref;
  2426. /**
  2427. * @param {string} ref
  2428. * @param {string|null} alt
  2429. */
  2430. constructor(ref, alt) {
  2431. super(null, alt);
  2432. this.ref = ref;
  2433. }
  2434. toHTML(state) {
  2435. if (!this.source) {
  2436. let url = state.urls[this.ref.toLowerCase()];
  2437. let title = state.urlTitles[this.ref.toLowerCase()];
  2438. this.source = url;
  2439. this.title = title || this.title;
  2440. }
  2441. if (this.source) {
  2442. return super.toHTML(state);
  2443. } else {
  2444. return `![${MDUtils.escapeHTML(this.alt)}][${MDUtils.escapeHTML(this.ref)}]`;
  2445. }
  2446. }
  2447. }
  2448. class MDFootnoteReferenceSpan extends MDSpan {
  2449. /** @type {string} */
  2450. symbol;
  2451. /** @type {number|null} */
  2452. differentiator = null;
  2453. /**
  2454. * @param {string} symbol
  2455. */
  2456. constructor(symbol) {
  2457. super();
  2458. this.symbol = symbol;
  2459. }
  2460. toHTML(state) {
  2461. if (this.differentiator !== null) {
  2462. return `<sup id="footnoteref_${this.differentiator}"><a href="#footnote_${this.symbol}">${this.symbol}</a></sup>`;
  2463. }
  2464. return `<!--FNREF:{${this.symbol}}-->`;
  2465. }
  2466. toPlaintext(state) {
  2467. return this.symbol;
  2468. }
  2469. }
  2470. // -- Other -----------------------------------------------------------------
  2471. class MDHTMLTag {
  2472. /** @type {string} */
  2473. fullTag;
  2474. /** @type {string} */
  2475. tagName;
  2476. /** @type {boolean} */
  2477. isCloser;
  2478. /** @type {object} */
  2479. attributes;
  2480. /**
  2481. * @param {string} fullTag
  2482. * @param {string} tagName
  2483. * @param {boolean} isCloser
  2484. * @param {object} attributes
  2485. */
  2486. constructor(fullTag, tagName, isCloser, attributes) {
  2487. this.fullTag = fullTag;
  2488. this.tagName = tagName;
  2489. this.isCloser = isCloser;
  2490. this.attributes = attributes;
  2491. }
  2492. toString() {
  2493. return this.fullTag;
  2494. }
  2495. equals(other) {
  2496. if (!(other instanceof MDHTMLTag)) return false;
  2497. return other.fullTag == this.fullTag;
  2498. }
  2499. static #htmlTagNameFirstRegex = /[a-z]/i;
  2500. static #htmlTagNameMedialRegex = /[a-z0-9]/i;
  2501. static #htmlAttributeNameFirstRegex = /[a-z]/i;
  2502. static #htmlAttributeNameMedialRegex = /[a-z0-9-]/i;
  2503. static #whitespaceCharRegex = /\s/;
  2504. /**
  2505. * @param {string} line
  2506. * @returns {MDHTMLTag|null} HTML tag if possible
  2507. */
  2508. static fromLineStart(line) {
  2509. let expectOpenBracket = 0;
  2510. let expectCloserOrName = 1;
  2511. let expectName = 2;
  2512. let expectAttributeNameOrEnd = 3;
  2513. let expectEqualsOrAttributeOrEnd = 4;
  2514. let expectAttributeValue = 5;
  2515. let expectCloseBracket = 6;
  2516. var isCloser = false;
  2517. var tagName = '';
  2518. var attributeName = '';
  2519. var attributeValue = '';
  2520. var attributeQuote = null;
  2521. var attributes = {};
  2522. var fullTag = null;
  2523. let endAttribute = function() {
  2524. if (attributeName.length > 0) {
  2525. if (attributeValue.length > 0 || attributeQuote) {
  2526. attributes[attributeName] = attributeValue;
  2527. } else {
  2528. attributes[attributeName] = true;
  2529. }
  2530. }
  2531. attributeName = '';
  2532. attributeValue = '';
  2533. attributeQuote = null;
  2534. };
  2535. var expect = expectOpenBracket;
  2536. for (var p = 0; p < line.length && fullTag === null; p++) {
  2537. let ch = line.substring(p, p + 1);
  2538. let isWhitespace = this.#whitespaceCharRegex.exec(ch) !== null;
  2539. switch (expect) {
  2540. case expectOpenBracket:
  2541. if (ch != '<') return null;
  2542. expect = expectCloserOrName;
  2543. break;
  2544. case expectCloserOrName:
  2545. if (ch == '/') {
  2546. isCloser = true;
  2547. } else {
  2548. p--;
  2549. }
  2550. expect = expectName;
  2551. break;
  2552. case expectName:
  2553. if (tagName.length == 0) {
  2554. if (this.#htmlTagNameFirstRegex.exec(ch) === null) return null;
  2555. tagName += ch;
  2556. } else {
  2557. if (this.#htmlTagNameMedialRegex.exec(ch)) {
  2558. tagName += ch;
  2559. } else {
  2560. p--;
  2561. expect = (isCloser) ? expectCloseBracket : expectAttributeNameOrEnd;
  2562. }
  2563. }
  2564. break;
  2565. case expectAttributeNameOrEnd:
  2566. if (attributeName.length == 0) {
  2567. if (isWhitespace) {
  2568. // skip whitespace
  2569. } else if (ch == '/') {
  2570. expect = expectCloseBracket;
  2571. } else if (ch == '>') {
  2572. fullTag = line.substring(0, p + 1);
  2573. break;
  2574. } else if (this.#htmlAttributeNameFirstRegex.exec(ch)) {
  2575. attributeName += ch;
  2576. } else {
  2577. return null;
  2578. }
  2579. } else if (isWhitespace) {
  2580. expect = expectEqualsOrAttributeOrEnd;
  2581. } else if (ch == '/') {
  2582. endAttribute();
  2583. expect = expectCloseBracket;
  2584. } else if (ch == '>') {
  2585. endAttribute();
  2586. fullTag = line.substring(0, p + 1);
  2587. break;
  2588. } else if (ch == '=') {
  2589. expect = expectAttributeValue;
  2590. } else if (this.#htmlAttributeNameMedialRegex.exec(ch)) {
  2591. attributeName += ch;
  2592. } else {
  2593. return null;
  2594. }
  2595. break;
  2596. case expectEqualsOrAttributeOrEnd:
  2597. if (ch == '=') {
  2598. expect = expectAttributeValue;
  2599. } else if (isWhitespace) {
  2600. // skip whitespace
  2601. } else if (ch == '/') {
  2602. expect = expectCloseBracket;
  2603. } else if (ch == '>') {
  2604. fullTag = line.substring(0, p + 1);
  2605. break;
  2606. } else if (this.#htmlAttributeNameFirstRegex.exec(ch)) {
  2607. endAttribute();
  2608. expect = expectAttributeNameOrEnd;
  2609. p--;
  2610. }
  2611. break;
  2612. case expectAttributeValue:
  2613. if (attributeValue.length == 0) {
  2614. if (attributeQuote === null) {
  2615. if (isWhitespace) {
  2616. // skip whitespace
  2617. } else if (ch == '"' || ch == "'") {
  2618. attributeQuote = ch;
  2619. } else {
  2620. attributeQuote = ''; // explicitly unquoted
  2621. p--;
  2622. }
  2623. } else {
  2624. if (ch === attributeQuote) {
  2625. // Empty string
  2626. endAttribute();
  2627. expect = expectAttributeNameOrEnd;
  2628. } else if (attributeQuote === '' && (ch == '/' || ch == '>')) {
  2629. return null;
  2630. } else {
  2631. attributeValue += ch;
  2632. }
  2633. }
  2634. } else {
  2635. if (ch === attributeQuote) {
  2636. endAttribute();
  2637. expect = expectAttributeNameOrEnd;
  2638. } else if (attributeQuote === '' && isWhitespace) {
  2639. endAttribute();
  2640. expect = expectAttributeNameOrEnd;
  2641. } else {
  2642. attributeValue += ch;
  2643. }
  2644. }
  2645. break;
  2646. case expectCloseBracket:
  2647. if (isWhitespace) {
  2648. // ignore whitespace
  2649. } else if (ch == '>') {
  2650. fullTag = line.substring(0, p + 1);
  2651. break;
  2652. }
  2653. break;
  2654. }
  2655. }
  2656. if (fullTag === null) return null;
  2657. endAttribute();
  2658. return new MDHTMLTag(fullTag, tagName, isCloser, attributes);
  2659. }
  2660. }
  2661. class MDTagModifier {
  2662. /** @type {string} */
  2663. original;
  2664. /** @type {string[]} */
  2665. cssClasses = [];
  2666. /** @type {string|null} */
  2667. cssId = null;
  2668. /** @type {object} */
  2669. attributes = {};
  2670. static #baseClassRegex = /\.([a-z_\-][a-z0-9_\-]*?)/i;
  2671. static #baseIdRegex = /#([a-z_\-][a-z0-9_\-]*?)/i;
  2672. static #baseAttributeRegex = /([a-z0-9]+?)=([^\s\}]+?)/i;
  2673. static #baseRegex = /\{([^}]+?)}/i;
  2674. static #leadingClassRegex = new RegExp('^' + this.#baseRegex.source, 'i');
  2675. static #trailingClassRegex = new RegExp('^(.*?)\\s*' + this.#baseRegex.source + '\\s*$', 'i');
  2676. static #classRegex = new RegExp('^' + this.#baseClassRegex.source + '$', 'i'); // 1=classname
  2677. static #idRegex = new RegExp('^' + this.#baseIdRegex.source + '$', 'i'); // 1=id
  2678. static #attributeRegex = new RegExp('^' + this.#baseAttributeRegex.source + '$', 'i'); // 1=attribute name, 2=attribute value
  2679. /**
  2680. * @param {MDBlock|MDSpan} elem
  2681. */
  2682. applyTo(elem) {
  2683. if (elem instanceof MDBlock || elem instanceof MDSpan) {
  2684. elem.cssClasses = elem.cssClasses.concat(this.cssClasses);
  2685. if (this.cssId) elem.cssId = this.cssId;
  2686. for (const name in this.attributes) {
  2687. elem.attributes[name] = this.attributes[name];
  2688. }
  2689. }
  2690. }
  2691. equals(other) {
  2692. if (!(other instanceof MDTagModifier)) return false;
  2693. if (!MDUtils.equal(other.cssClasses, this.cssClasses)) return false;
  2694. if (other.cssId !== this.cssId) return false;
  2695. if (!MDUtils.equal(other.attributes, this.attributes)) return false;
  2696. return true;
  2697. }
  2698. toString() {
  2699. return this.original;
  2700. }
  2701. static #fromContents(contents) {
  2702. let modifierTokens = contents.split(/\s+/);
  2703. let mod = new MDTagModifier();
  2704. mod.original = `{${contents}}`;
  2705. var groups;
  2706. for (const token of modifierTokens) {
  2707. if (token.trim() == '') continue;
  2708. if (groups = this.#classRegex.exec(token)) {
  2709. mod.cssClasses.push(groups[1]);
  2710. } else if (groups = this.#idRegex.exec(token)) {
  2711. mod.cssId = groups[1];
  2712. } else if (groups = this.#attributeRegex.exec(token)) {
  2713. mod.attributes[groups[1]] = groups[2];
  2714. } else {
  2715. return null;
  2716. }
  2717. }
  2718. return mod;
  2719. }
  2720. /**
  2721. * Extracts modifier from line.
  2722. * @param {string} line
  2723. * @returns {Array} Tuple with remaining line and MDTagModifier.
  2724. */
  2725. static fromLine(line) {
  2726. let groups = this.#trailingClassRegex.exec(line);
  2727. if (groups === null) return [ line, null ];
  2728. let bareLine = groups[1];
  2729. let mod = this.#fromContents(groups[2]);
  2730. return [ bareLine, mod ];
  2731. }
  2732. /**
  2733. * Extracts modifier from head of string.
  2734. * @param {string} line
  2735. * @returns {MDTagModifier}
  2736. */
  2737. static fromStart(line) {
  2738. let groups = this.#leadingClassRegex.exec(line);
  2739. if (groups === null) return null;
  2740. return this.#fromContents(groups[1]);
  2741. }
  2742. /**
  2743. * @param {string} line
  2744. * @returns {string}
  2745. */
  2746. static strip(line) {
  2747. let groups = this.#trailingClassRegex.exec(line);
  2748. if (groups === null) return line;
  2749. return groups[1];
  2750. }
  2751. }
  2752. class MDState {
  2753. /** @type {string[]} */
  2754. #lines = [];
  2755. /**
  2756. * Abbreviation string (case sensitive) -> definition string
  2757. * @type {object}
  2758. */
  2759. #abbreviations = {};
  2760. /**
  2761. * Abbreviation string (case sensitive) -> RegExp
  2762. * @type {object}
  2763. */
  2764. #abbreviationRegexes = {};
  2765. /**
  2766. * Footnote symbol string -> content MDBlock
  2767. * @type {object}
  2768. */
  2769. #footnotes = {};
  2770. /**
  2771. * Footnote symbol string -> unique number[]
  2772. * @type {object}
  2773. */
  2774. #footnoteInstances = {};
  2775. /**
  2776. * Reference symbol -> URL string
  2777. * @type {object}
  2778. */
  2779. #urlDefinitions = {};
  2780. /**
  2781. * Reference symbol -> title string
  2782. * @type {object}
  2783. */
  2784. #urlTitles = {};
  2785. /** @type {number} */
  2786. p = 0;
  2787. /** @type {MDState|null} */
  2788. #parent = null;
  2789. /**
  2790. * Block readers sorted by priority.
  2791. * @type {MDBlockReader[]} readers
  2792. */
  2793. #blockReadersByPriority = [];
  2794. /**
  2795. * Tuples of priority:number and MDInlineReader sorted by `tokenizePriority`.
  2796. * @type {Array}
  2797. */
  2798. #inlineReadersByTokenPriority = [];
  2799. /**
  2800. * Tuples of priority:number and MDInlineReader sorted by `substitutePriority`.
  2801. */
  2802. #inlineReadersBySubstitutePriority = [];
  2803. /** @returns {string[]} */
  2804. get lines() { return this.#lines; }
  2805. /** @returns {string|null} */
  2806. get currentLine() { return (this.p < this.#lines.length) ? this.#lines[this.p] : null; }
  2807. /** @returns {object} */
  2808. get abbreviations() {
  2809. return (this.#parent) ? this.#parent.abbreviations : this.#abbreviations;
  2810. }
  2811. /** @returns {object} */
  2812. get abbreviationRegexes() {
  2813. return (this.#parent) ? this.#parent.abbreviationRegexes : this.#abbreviationRegexes;
  2814. }
  2815. /** @returns {object} */
  2816. get footnotes() {
  2817. return (this.#parent) ? this.#parent.footnotes : this.#footnotes;
  2818. }
  2819. /** @returns {object} */
  2820. get footnoteInstances() {
  2821. return (this.#parent) ? this.#parent.footnoteInstances : this.#footnoteInstances;
  2822. }
  2823. /** @returns {object} */
  2824. get urls() {
  2825. return (this.#parent) ? this.#parent.urls : this.#urlDefinitions;
  2826. }
  2827. /** @returns {object} */
  2828. get urlTitles() {
  2829. return (this.#parent) ? this.#parent.urlTitles : this.#urlTitles;
  2830. }
  2831. /**
  2832. * Block readers sorted by priority.
  2833. * @type {MDBlockReader[]} readers
  2834. */
  2835. get blockReadersByPriority() {
  2836. return (this.#parent) ? this.#parent.blockReadersByPriority : this.#blockReadersByPriority;
  2837. }
  2838. set blockReadersByPriority(newValue) {
  2839. this.#blockReadersByPriority = newValue;
  2840. }
  2841. /**
  2842. * Tuples of priority:number and MDInlineReader sorted by `tokenizePriority`.
  2843. * @type {Array}
  2844. */
  2845. get inlineReadersByTokenPriority() {
  2846. return (this.#parent) ? this.#parent.inlineReadersByTokenPriority : this.#inlineReadersByTokenPriority;
  2847. }
  2848. set inlineReadersByTokenPriority(newValue) {
  2849. this.#inlineReadersByTokenPriority = newValue;
  2850. }
  2851. /**
  2852. * Tuples of priority:number and MDInlineReader sorted by `substitutePriority`.
  2853. */
  2854. get inlineReadersBySubstitutePriority() {
  2855. return (this.#parent) ? this.#parent.inlineReadersBySubstitutePriority : this.#inlineReadersBySubstitutePriority;
  2856. }
  2857. set inlineReadersBySubstitutePriority(newValue) {
  2858. this.#inlineReadersBySubstitutePriority = newValue;
  2859. }
  2860. /**
  2861. * @param {string[]} lines
  2862. */
  2863. constructor(lines) {
  2864. this.#lines = lines;
  2865. }
  2866. /**
  2867. * Creates a copy of this state with new lines. Useful for parsing nested
  2868. * content.
  2869. *
  2870. * @param {string[]} lines
  2871. * @returns {MDState} copied sub-state
  2872. */
  2873. copy(lines) {
  2874. let cp = new MDState(lines);
  2875. cp.#parent = this;
  2876. return cp;
  2877. }
  2878. /**
  2879. * Defines an abbreviation.
  2880. *
  2881. * @param {string} abbreviation - case sensitive
  2882. * @param {string} definition - brief definition of the abbreviation
  2883. */
  2884. defineAbbreviation(abbreviation, definition) {
  2885. if (this.#parent) {
  2886. this.#parent.defineAbbreviation(abbreviation, definition);
  2887. return;
  2888. }
  2889. // FIXME: Escape abbreviation
  2890. this.#abbreviations[abbreviation] = definition;
  2891. const regex = new RegExp("\\b(" + abbreviation + ")\\b", "ig");
  2892. this.#abbreviationRegexes[abbreviation] = regex;
  2893. }
  2894. /**
  2895. * Defines content of a footnote.
  2896. *
  2897. * @param {string} symbol - footnote symbol (e.g. "1")
  2898. * @param {MDBlock} footnote - content of the footnote
  2899. */
  2900. defineFootnote(symbol, footnote) {
  2901. if (this.#parent) {
  2902. this.#parent.defineFootnote(symbol, footnote);
  2903. } else {
  2904. this.#footnotes[symbol] = footnote;
  2905. }
  2906. }
  2907. /**
  2908. * @param {string} symbol
  2909. * @param {number} unique
  2910. */
  2911. registerUniqueFootnote(symbol, unique) {
  2912. if (this.#parent) {
  2913. this.#parent.registerUniqueFootnote(symbol, unique);
  2914. } else {
  2915. var uniques = this.#footnoteInstances[symbol] || [];
  2916. uniques.push(unique);
  2917. this.#footnoteInstances[symbol] = uniques;
  2918. }
  2919. }
  2920. /**
  2921. * Defines the URL for a given reference symbol.
  2922. *
  2923. * @param {string} symbol - reference symbol
  2924. * @param {string} url - URL
  2925. * @param {string|null} title - mouseover title attribute for links
  2926. */
  2927. defineURL(symbol, url, title=null) {
  2928. if (this.#parent) {
  2929. this.#parent.defineURL(symbol, url, title);
  2930. } else {
  2931. this.#urlDefinitions[symbol.toLowerCase()] = url;
  2932. if (title !== null) {
  2933. this.#urlTitles[symbol.toLowerCase()] = title;
  2934. }
  2935. }
  2936. }
  2937. /**
  2938. * Tests if there are at least `minCount` lines available to read. If `p`
  2939. * is not provided it will be relative to `this.p`.
  2940. *
  2941. * @param {number} minCount - minimum number of lines
  2942. * @param {number|null} p - line pointer, or `null` to use `this.p`
  2943. * @returns {boolean} whether at least the given number of lines is available
  2944. */
  2945. hasLines(minCount, p=null) {
  2946. let relativeTo = (p === null) ? this.p : p;
  2947. return relativeTo + minCount <= this.lines.length;
  2948. }
  2949. /**
  2950. * Reads and returns an array of blocks from the current line pointer.
  2951. *
  2952. * @returns {MDBlock[]} parsed blocks
  2953. */
  2954. readBlocks() {
  2955. var blocks = [];
  2956. while (this.hasLines(1)) {
  2957. let block = this.#readNextBlock();
  2958. if (block) {
  2959. blocks.push(block);
  2960. } else {
  2961. break;
  2962. }
  2963. }
  2964. return blocks;
  2965. }
  2966. /**
  2967. * Creates a simple `MDInlineBlock` if no other registered blocks match.
  2968. *
  2969. * @returns {MDInlineBlock|null} fallback block
  2970. */
  2971. #readFallbackBlock() {
  2972. if (this.p >= this.lines.length) return null;
  2973. const lines = MDUtils.withoutTrailingBlankLines(this.lines.slice(this.p));
  2974. if (lines.length == 0) return null;
  2975. this.p = this.lines.length;
  2976. return new MDInlineBlock(this.inlineMarkdownToSpans(lines.join("\n")));
  2977. }
  2978. /**
  2979. * Attempts to read one block from the current line pointer. The pointer
  2980. * will be positioned just after the end of the block.
  2981. *
  2982. * @param {MDState} state
  2983. * @returns {MDBlock}
  2984. */
  2985. #readNextBlock() {
  2986. while (this.hasLines(1) && this.lines[this.p].trim().length == 0) {
  2987. this.p++;
  2988. }
  2989. if (!this.hasLines(1)) return null;
  2990. for (const reader of this.blockReadersByPriority) {
  2991. const startP = this.p;
  2992. const block = reader.readBlock(this);
  2993. if (block) {
  2994. if (this.p == startP) {
  2995. throw new Error(`${reader.constructor.name} returned an ${block.constructor.name} without incrementing MDState.p. This could lead to an infinite loop.`);
  2996. }
  2997. return block;
  2998. }
  2999. }
  3000. const fallback = this.#readFallbackBlock();
  3001. return fallback;
  3002. }
  3003. static #textWhitespaceRegex = /^(\s*)(?:(\S|\S.*\S)(\s*?))?$/; // 1=leading WS, 2=text, 3=trailing WS
  3004. /**
  3005. * @param {string} line
  3006. * @returns {MDToken[]}
  3007. */
  3008. #inlineMarkdownToTokens(line) {
  3009. if (this.#parent) return this.#parent.#inlineMarkdownToTokens(line);
  3010. var tokens = [];
  3011. var text = '';
  3012. var expectLiteral = false;
  3013. /**
  3014. * Flushes accumulated content in `text` to `tokens`.
  3015. */
  3016. const endText = function() {
  3017. if (text.length == 0) return;
  3018. const textGroups = MDState.#textWhitespaceRegex.exec(text);
  3019. if (textGroups !== null) {
  3020. if (textGroups[1].length > 0) {
  3021. tokens.push(new MDToken(textGroups[1], MDTokenType.Whitespace, textGroups[1]));
  3022. }
  3023. if (textGroups[2] !== undefined && textGroups[2].length > 0) {
  3024. tokens.push(new MDToken(textGroups[2], MDTokenType.Text, textGroups[2]));
  3025. }
  3026. if (textGroups[3] !== undefined && textGroups[3].length > 0) {
  3027. tokens.push(new MDToken(textGroups[3], MDTokenType.Whitespace, textGroups[3]));
  3028. }
  3029. } else {
  3030. tokens.push(new MDToken(text, MDTokenType.Text, text));
  3031. }
  3032. text = '';
  3033. }
  3034. for (var p = 0; p < line.length; p++) {
  3035. const ch = line.substring(p, p + 1);
  3036. const remainder = line.substring(p);
  3037. if (expectLiteral) {
  3038. text += ch;
  3039. expectLiteral = false;
  3040. continue;
  3041. }
  3042. if (ch == '\\') {
  3043. expectLiteral = true;
  3044. continue;
  3045. }
  3046. var found = false;
  3047. for (const readerTuple of this.inlineReadersByTokenPriority) {
  3048. /** @type {number} */
  3049. const priority = readerTuple[0];
  3050. /** @type {MDInlineReader} */
  3051. const reader = readerTuple[1];
  3052. const token = reader.readFirstToken(this, priority, remainder);
  3053. if (token === null) continue;
  3054. endText();
  3055. tokens.push(token);
  3056. if (token.original == null || token.original.length == 0) {
  3057. throw new Error(`${reader.constructor.name} returned a token with an empty .original. This would cause an infinite loop.`);
  3058. }
  3059. p += token.original.length - 1;
  3060. found = true;
  3061. break;
  3062. }
  3063. if (!found) {
  3064. text += ch;
  3065. }
  3066. }
  3067. endText();
  3068. return tokens;
  3069. }
  3070. /**
  3071. * Converts a line of markdown to an MDSpan.
  3072. *
  3073. * @param {string|string[]} line
  3074. * @returns {MDSpan}
  3075. */
  3076. inlineMarkdownToSpan(line) {
  3077. let spans = this.inlineMarkdownToSpans(line);
  3078. return (spans.length == 1) ? spans[0] : new MDMultiSpan(spans);
  3079. }
  3080. /**
  3081. * Converts a line of markdown to an array of MDSpan.
  3082. *
  3083. * @param {string|string[]} line
  3084. * @returns {MDSpan[]}
  3085. */
  3086. inlineMarkdownToSpans(line) {
  3087. var tokens = this.#inlineMarkdownToTokens((line instanceof Array) ? line.join('\n') : line);
  3088. return this.tokensToSpans(tokens);
  3089. }
  3090. /**
  3091. * Converts a mixed array of `MDToken` and `MDSpan` elements into an array
  3092. * of only `MDSpan`.
  3093. *
  3094. * @param {MDToken[]|MDSpan[]} tokens
  3095. * @returns {MDSpan[]}
  3096. */
  3097. tokensToSpans(tokens) {
  3098. var spans = tokens.slice();
  3099. // Perform repeated substitutions, converting sequences of tokens into
  3100. // spans, until no more substitutions can be made.
  3101. var anyChanges = false;
  3102. do {
  3103. anyChanges = false;
  3104. for (const readerTuple of this.inlineReadersBySubstitutePriority) {
  3105. /** @type {number} */
  3106. const priority = readerTuple[0];
  3107. /** @type {MDInlineReader} */
  3108. const reader = readerTuple[1];
  3109. const changed = reader.substituteTokens(this, priority, spans);
  3110. if (!changed) continue;
  3111. anyChanges = true;
  3112. break;
  3113. }
  3114. } while (anyChanges);
  3115. // Convert any remaining tokens to spans, apply CSS modifiers.
  3116. var lastSpan = null;
  3117. spans = spans.map(function(span) {
  3118. if (span instanceof MDToken) {
  3119. if (span.type == MDTokenType.Modifier && lastSpan) {
  3120. span.modifier.applyTo(lastSpan);
  3121. lastSpan = null;
  3122. return new MDTextSpan('');
  3123. }
  3124. lastSpan = null;
  3125. return new MDTextSpan(span.original);
  3126. } else if (span instanceof MDSpan) {
  3127. lastSpan = (span instanceof MDTextSpan) ? null : span;
  3128. return span;
  3129. } else {
  3130. throw new Error(`Unexpected span type ${span.constructor.name}`);
  3131. }
  3132. });
  3133. return spans;
  3134. }
  3135. }
  3136. class Markdown {
  3137. /**
  3138. * Set of standard block readers.
  3139. * @type {MDBlockReader[]}
  3140. */
  3141. static standardBlockReaders = [
  3142. new MDUnderlinedHeaderBlockReader(10.0),
  3143. new MDHashHeaderBlockReader(15.0),
  3144. new MDBlockQuoteBlockReader(20.0),
  3145. new MDHorizontalRuleBlockReader(25.0),
  3146. new MDFencedCodeBlockReader(30.0),
  3147. new MDIndentedCodeBlockReader(40.0),
  3148. new MDOrderedListBlockReader(45.0),
  3149. new MDUnorderedListBlockReader(50.0),
  3150. new MDURLDefinitionBlockReader(95.0),
  3151. new MDParagraphBlockReader(100.0),
  3152. ];
  3153. /**
  3154. * All supported block readers.
  3155. * @type {MDBlockReader[]}
  3156. */
  3157. static allBlockReaders = [
  3158. ...this.standardBlockReaders,
  3159. new MDTableBlockReader(55.0),
  3160. new MDDefinitionListBlockReader(60.0),
  3161. new MDAbbreviationDefinitionBlockReader(90.0),
  3162. new MDFootnoteDefinitionBlockReader(91.0),
  3163. ];
  3164. /**
  3165. * Set of standard inline readers.
  3166. * @type {MDInlineReader[]}
  3167. */
  3168. static standardInlineReaders = [
  3169. new MDStrongInlineReader(10.0, [ 0.0, 2.0 ]),
  3170. new MDEmphasisInlineReader(15.0, [ 5.0, 55.0 ]),
  3171. new MDCodeInlineReader(20.0, [ 10.0, 60.0 ]),
  3172. new MDImageInlineReader(25.0, 15.0),
  3173. new MDLinkInlineReader(30.0, 20.0),
  3174. new MDSimpleLinkInlineReader(35.0, 25.0),
  3175. new MDHTMLTagInlineReader(80.0, 30.0),
  3176. ];
  3177. /**
  3178. * All supported inline readers.
  3179. * @type {MDInlineReader[]}
  3180. */
  3181. static allInlineReaders = [
  3182. ...this.standardInlineReaders,
  3183. new MDStrikethroughInlineReader(21.0, [ 12.0, 50.0 ]),
  3184. new MDFootnoteInlineReader(5.0, 40.0),
  3185. new MDModifierInlineReader(90.0, 45.0),
  3186. ];
  3187. /**
  3188. * Shared instance of a parser with standard syntax.
  3189. */
  3190. static standardParser = new Markdown(this.standardBlockReaders, this.standardInlineReaders);
  3191. /**
  3192. * Shared instance of a parser with all supported syntax.
  3193. */
  3194. static completeParser = new Markdown(this.allBlockReaders, this.allInlineReaders);
  3195. #blockReaders;
  3196. #inlineReaders;
  3197. #blockReadersByPriority;
  3198. #inlineReadersByTokenPriority;
  3199. #inlineReadersBySubstitutePriority;
  3200. /**
  3201. * @param {MDBlockReader[]} blockReaders
  3202. * @param {MDInlineReader[]} inlineReaders
  3203. */
  3204. constructor(blockReaders=Markdown.allBlockReaders, inlineReaders=Markdown.allInlineReaders) {
  3205. this.#blockReaders = blockReaders;
  3206. this.#inlineReaders = inlineReaders;
  3207. this.#blockReadersByPriority = blockReaders.slice();
  3208. this.#blockReadersByPriority.sort((a, b) => a.priority - b.priority);
  3209. const duplicateAndSort = function(priorityFn) {
  3210. var readers = [];
  3211. for (const reader of inlineReaders) {
  3212. const p = priorityFn(reader);
  3213. const priorities = (p instanceof Array) ? p : [ p ];
  3214. for (const priority of priorities) {
  3215. readers.push([priority, reader]);
  3216. }
  3217. }
  3218. readers.sort((a, b) => a[0] - b[0]);
  3219. return readers;
  3220. }
  3221. this.#inlineReadersByTokenPriority = duplicateAndSort((reader) => reader.tokenizePriority);
  3222. this.#inlineReadersBySubstitutePriority = duplicateAndSort((reader) => reader.substitutePriority);
  3223. }
  3224. /**
  3225. * @param {string} markdown
  3226. * @returns {string} HTML
  3227. */
  3228. toHTML(markdown) {
  3229. const lines = markdown.split(/(?:\n|\r|\r\n)/);
  3230. const state = new MDState(lines);
  3231. state.blockReadersByPriority = this.#blockReadersByPriority;
  3232. state.inlineReadersByTokenPriority = this.#inlineReadersByTokenPriority;
  3233. state.inlineReadersBySubstitutePriority = this.#inlineReadersBySubstitutePriority;
  3234. const blocks = state.readBlocks();
  3235. for (const reader of this.#blockReaders) {
  3236. reader.postProcess(state, blocks);
  3237. }
  3238. for (const reader of this.#inlineReaders) {
  3239. reader.postProcess(state, blocks);
  3240. }
  3241. return MDBlock.toHTML(blocks, state);
  3242. }
  3243. }