PHP and Javascript implementations of a simple markdown parser
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

markdown.js 93KB

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