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

markdown.js 94KB

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