statum-markdown.js 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184
  1. /*!
  2. * Statum - client-side state library (markdown module).
  3. *
  4. * The CommonMark 0.31.2 engine (escape-first: raw source HTML is always
  5. * neutralised — see the security note above the engine) plus the
  6. * `stm-markdown` and `stm-h-demotion` bindings and the programmatic
  7. * `statum.markdown` API. The engine itself has no DOM references; only the
  8. * bindings touch elements.
  9. *
  10. * Load order: THIRD - requires statum-core.js (`window.statum._bridge`); the
  11. * `stm-markdown` handler orders itself after statum-document.js's `stm-html`.
  12. * Like core: an IIFE, no dependencies, no build step, plain script tag.
  13. */
  14. (function () {
  15. 'use strict';
  16. if (!window.statum || !window.statum._bridge) {
  17. console.error('[statum] statum-markdown.js requires statum-core.js');
  18. return;
  19. }
  20. var bridge = window.statum._bridge;
  21. var evalExpr = bridge.evalExpr;
  22. // ---------------------------------------------------------------------------
  23. // Markdown rendering (CommonMark 0.31.2)
  24. // ---------------------------------------------------------------------------
  25. //
  26. // A two-pass CommonMark engine: block structure first (paragraphs, ATX and
  27. // setext headings, thematic breaks, indented and fenced code blocks, block
  28. // quotes with lazy continuation, lists with tight/loose rendering and link
  29. // reference definitions), then inline parsing inside the leaf blocks
  30. // (delimiter-run emphasis, links and images, code spans, autolinks,
  31. // backslash escapes, entity references, hard/soft line breaks).
  32. //
  33. // SECURITY: the markdown source is untrusted text. Raw HTML is never passed
  34. // through — inline HTML and HTML-block-looking constructs render as escaped
  35. // text, which intentionally diverges from the CommonMark HTML output for
  36. // those examples. Link and image destinations are scheme-filtered by
  37. // safeMarkdownUrl() and everything is escaped before it reaches the output.
  38. function safeMarkdownUrl(url) {
  39. var u = url.trim();
  40. var m = u.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
  41. if (!m) return u;
  42. var scheme = m[1].toLowerCase();
  43. if (scheme === 'http' || scheme === 'https' || scheme === 'mailto' || scheme === 'ftp') return u;
  44. return '#';
  45. }
  46. /**
  47. * Packed HTML5 named-entity table (WHATWG `entities.json`, 2125 entries).
  48. * Each record is "name cp[,cp...]" on one line; multi-codepoint entities
  49. * carry comma-separated codepoints. Line breaks are escaped so the whole
  50. * table stays one string literal. Parsed lazily into a name -> text map the
  51. * first time an entity reference is looked up.
  52. */
  53. var MD_ENTITIES_PACKED = ''
  54. + "AElig 198\nAMP 38\nAacute 193\nAbreve 258\nAcirc 194\nAcy 1040\nAfr 120068\nAgrave 192\n"
  55. + "Alpha 913\nAmacr 256\nAnd 10835\nAogon 260\nAopf 120120\nApplyFunction 8289\nAring 197\n"
  56. + "Ascr 119964\nAssign 8788\nAtilde 195\nAuml 196\nBackslash 8726\nBarv 10983\nBarwed 8966\n"
  57. + "Bcy 1041\nBecause 8757\nBernoullis 8492\nBeta 914\nBfr 120069\nBopf 120121\nBreve 728\n"
  58. + "Bscr 8492\nBumpeq 8782\nCHcy 1063\nCOPY 169\nCacute 262\nCap 8914\n"
  59. + "CapitalDifferentialD 8517\nCayleys 8493\nCcaron 268\nCcedil 199\nCcirc 264\nCconint 8752\n"
  60. + "Cdot 266\nCedilla 184\nCenterDot 183\nCfr 8493\nChi 935\nCircleDot 8857\n"
  61. + "CircleMinus 8854\nCirclePlus 8853\nCircleTimes 8855\nClockwiseContourIntegral 8754\n"
  62. + "CloseCurlyDoubleQuote 8221\nCloseCurlyQuote 8217\nColon 8759\nColone 10868\n"
  63. + "Congruent 8801\nConint 8751\nContourIntegral 8750\nCopf 8450\nCoproduct 8720\n"
  64. + "CounterClockwiseContourIntegral 8755\nCross 10799\nCscr 119966\nCup 8915\nCupCap 8781\n"
  65. + "DD 8517\nDDotrahd 10513\nDJcy 1026\nDScy 1029\nDZcy 1039\nDagger 8225\nDarr 8609\n"
  66. + "Dashv 10980\nDcaron 270\nDcy 1044\nDel 8711\nDelta 916\nDfr 120071\nDiacriticalAcute 180\n"
  67. + "DiacriticalDot 729\nDiacriticalDoubleAcute 733\nDiacriticalGrave 96\n"
  68. + "DiacriticalTilde 732\nDiamond 8900\nDifferentialD 8518\nDopf 120123\nDot 168\n"
  69. + "DotDot 8412\nDotEqual 8784\nDoubleContourIntegral 8751\nDoubleDot 168\n"
  70. + "DoubleDownArrow 8659\nDoubleLeftArrow 8656\nDoubleLeftRightArrow 8660\n"
  71. + "DoubleLeftTee 10980\nDoubleLongLeftArrow 10232\nDoubleLongLeftRightArrow 10234\n"
  72. + "DoubleLongRightArrow 10233\nDoubleRightArrow 8658\nDoubleRightTee 8872\n"
  73. + "DoubleUpArrow 8657\nDoubleUpDownArrow 8661\nDoubleVerticalBar 8741\nDownArrow 8595\n"
  74. + "DownArrowBar 10515\nDownArrowUpArrow 8693\nDownBreve 785\nDownLeftRightVector 10576\n"
  75. + "DownLeftTeeVector 10590\nDownLeftVector 8637\nDownLeftVectorBar 10582\n"
  76. + "DownRightTeeVector 10591\nDownRightVector 8641\nDownRightVectorBar 10583\nDownTee 8868\n"
  77. + "DownTeeArrow 8615\nDownarrow 8659\nDscr 119967\nDstrok 272\nENG 330\nETH 208\nEacute 201\n"
  78. + "Ecaron 282\nEcirc 202\nEcy 1069\nEdot 278\nEfr 120072\nEgrave 200\nElement 8712\n"
  79. + "Emacr 274\nEmptySmallSquare 9723\nEmptyVerySmallSquare 9643\nEogon 280\nEopf 120124\n"
  80. + "Epsilon 917\nEqual 10869\nEqualTilde 8770\nEquilibrium 8652\nEscr 8496\nEsim 10867\n"
  81. + "Eta 919\nEuml 203\nExists 8707\nExponentialE 8519\nFcy 1060\nFfr 120073\n"
  82. + "FilledSmallSquare 9724\nFilledVerySmallSquare 9642\nFopf 120125\nForAll 8704\n"
  83. + "Fouriertrf 8497\nFscr 8497\nGJcy 1027\nGT 62\nGamma 915\nGammad 988\nGbreve 286\n"
  84. + "Gcedil 290\nGcirc 284\nGcy 1043\nGdot 288\nGfr 120074\nGg 8921\nGopf 120126\n"
  85. + "GreaterEqual 8805\nGreaterEqualLess 8923\nGreaterFullEqual 8807\nGreaterGreater 10914\n"
  86. + "GreaterLess 8823\nGreaterSlantEqual 10878\nGreaterTilde 8819\nGscr 119970\nGt 8811\n"
  87. + "HARDcy 1066\nHacek 711\nHat 94\nHcirc 292\nHfr 8460\nHilbertSpace 8459\nHopf 8461\n"
  88. + "HorizontalLine 9472\nHscr 8459\nHstrok 294\nHumpDownHump 8782\nHumpEqual 8783\nIEcy 1045\n"
  89. + "IJlig 306\nIOcy 1025\nIacute 205\nIcirc 206\nIcy 1048\nIdot 304\nIfr 8465\nIgrave 204\n"
  90. + "Im 8465\nImacr 298\nImaginaryI 8520\nImplies 8658\nInt 8748\nIntegral 8747\n"
  91. + "Intersection 8898\nInvisibleComma 8291\nInvisibleTimes 8290\nIogon 302\nIopf 120128\n"
  92. + "Iota 921\nIscr 8464\nItilde 296\nIukcy 1030\nIuml 207\nJcirc 308\nJcy 1049\nJfr 120077\n"
  93. + "Jopf 120129\nJscr 119973\nJsercy 1032\nJukcy 1028\nKHcy 1061\nKJcy 1036\nKappa 922\n"
  94. + "Kcedil 310\nKcy 1050\nKfr 120078\nKopf 120130\nKscr 119974\nLJcy 1033\nLT 60\nLacute 313\n"
  95. + "Lambda 923\nLang 10218\nLaplacetrf 8466\nLarr 8606\nLcaron 317\nLcedil 315\nLcy 1051\n"
  96. + "LeftAngleBracket 10216\nLeftArrow 8592\nLeftArrowBar 8676\nLeftArrowRightArrow 8646\n"
  97. + "LeftCeiling 8968\nLeftDoubleBracket 10214\nLeftDownTeeVector 10593\nLeftDownVector 8643\n"
  98. + "LeftDownVectorBar 10585\nLeftFloor 8970\nLeftRightArrow 8596\nLeftRightVector 10574\n"
  99. + "LeftTee 8867\nLeftTeeArrow 8612\nLeftTeeVector 10586\nLeftTriangle 8882\n"
  100. + "LeftTriangleBar 10703\nLeftTriangleEqual 8884\nLeftUpDownVector 10577\n"
  101. + "LeftUpTeeVector 10592\nLeftUpVector 8639\nLeftUpVectorBar 10584\nLeftVector 8636\n"
  102. + "LeftVectorBar 10578\nLeftarrow 8656\nLeftrightarrow 8660\nLessEqualGreater 8922\n"
  103. + "LessFullEqual 8806\nLessGreater 8822\nLessLess 10913\nLessSlantEqual 10877\n"
  104. + "LessTilde 8818\nLfr 120079\nLl 8920\nLleftarrow 8666\nLmidot 319\nLongLeftArrow 10229\n"
  105. + "LongLeftRightArrow 10231\nLongRightArrow 10230\nLongleftarrow 10232\n"
  106. + "Longleftrightarrow 10234\nLongrightarrow 10233\nLopf 120131\nLowerLeftArrow 8601\n"
  107. + "LowerRightArrow 8600\nLscr 8466\nLsh 8624\nLstrok 321\nLt 8810\nMap 10501\nMcy 1052\n"
  108. + "MediumSpace 8287\nMellintrf 8499\nMfr 120080\nMinusPlus 8723\nMopf 120132\nMscr 8499\n"
  109. + "Mu 924\nNJcy 1034\nNacute 323\nNcaron 327\nNcedil 325\nNcy 1053\n"
  110. + "NegativeMediumSpace 8203\nNegativeThickSpace 8203\nNegativeThinSpace 8203\n"
  111. + "NegativeVeryThinSpace 8203\nNestedGreaterGreater 8811\nNestedLessLess 8810\nNewLine 10\n"
  112. + "Nfr 120081\nNoBreak 8288\nNonBreakingSpace 160\nNopf 8469\nNot 10988\nNotCongruent 8802\n"
  113. + "NotCupCap 8813\nNotDoubleVerticalBar 8742\nNotElement 8713\nNotEqual 8800\n"
  114. + "NotEqualTilde 8770,824\nNotExists 8708\nNotGreater 8815\nNotGreaterEqual 8817\n"
  115. + "NotGreaterFullEqual 8807,824\nNotGreaterGreater 8811,824\nNotGreaterLess 8825\n"
  116. + "NotGreaterSlantEqual 10878,824\nNotGreaterTilde 8821\nNotHumpDownHump 8782,824\n"
  117. + "NotHumpEqual 8783,824\nNotLeftTriangle 8938\nNotLeftTriangleBar 10703,824\n"
  118. + "NotLeftTriangleEqual 8940\nNotLess 8814\nNotLessEqual 8816\nNotLessGreater 8824\n"
  119. + "NotLessLess 8810,824\nNotLessSlantEqual 10877,824\nNotLessTilde 8820\n"
  120. + "NotNestedGreaterGreater 10914,824\nNotNestedLessLess 10913,824\nNotPrecedes 8832\n"
  121. + "NotPrecedesEqual 10927,824\nNotPrecedesSlantEqual 8928\nNotReverseElement 8716\n"
  122. + "NotRightTriangle 8939\nNotRightTriangleBar 10704,824\nNotRightTriangleEqual 8941\n"
  123. + "NotSquareSubset 8847,824\nNotSquareSubsetEqual 8930\nNotSquareSuperset 8848,824\n"
  124. + "NotSquareSupersetEqual 8931\nNotSubset 8834,8402\nNotSubsetEqual 8840\nNotSucceeds 8833\n"
  125. + "NotSucceedsEqual 10928,824\nNotSucceedsSlantEqual 8929\nNotSucceedsTilde 8831,824\n"
  126. + "NotSuperset 8835,8402\nNotSupersetEqual 8841\nNotTilde 8769\nNotTildeEqual 8772\n"
  127. + "NotTildeFullEqual 8775\nNotTildeTilde 8777\nNotVerticalBar 8740\nNscr 119977\nNtilde 209\n"
  128. + "Nu 925\nOElig 338\nOacute 211\nOcirc 212\nOcy 1054\nOdblac 336\nOfr 120082\nOgrave 210\n"
  129. + "Omacr 332\nOmega 937\nOmicron 927\nOopf 120134\nOpenCurlyDoubleQuote 8220\n"
  130. + "OpenCurlyQuote 8216\nOr 10836\nOscr 119978\nOslash 216\nOtilde 213\nOtimes 10807\n"
  131. + "Ouml 214\nOverBar 8254\nOverBrace 9182\nOverBracket 9140\nOverParenthesis 9180\n"
  132. + "PartialD 8706\nPcy 1055\nPfr 120083\nPhi 934\nPi 928\nPlusMinus 177\nPoincareplane 8460\n"
  133. + "Popf 8473\nPr 10939\nPrecedes 8826\nPrecedesEqual 10927\nPrecedesSlantEqual 8828\n"
  134. + "PrecedesTilde 8830\nPrime 8243\nProduct 8719\nProportion 8759\nProportional 8733\n"
  135. + "Pscr 119979\nPsi 936\nQUOT 34\nQfr 120084\nQopf 8474\nQscr 119980\nRBarr 10512\nREG 174\n"
  136. + "Racute 340\nRang 10219\nRarr 8608\nRarrtl 10518\nRcaron 344\nRcedil 342\nRcy 1056\n"
  137. + "Re 8476\nReverseElement 8715\nReverseEquilibrium 8651\nReverseUpEquilibrium 10607\n"
  138. + "Rfr 8476\nRho 929\nRightAngleBracket 10217\nRightArrow 8594\nRightArrowBar 8677\n"
  139. + "RightArrowLeftArrow 8644\nRightCeiling 8969\nRightDoubleBracket 10215\n"
  140. + "RightDownTeeVector 10589\nRightDownVector 8642\nRightDownVectorBar 10581\n"
  141. + "RightFloor 8971\nRightTee 8866\nRightTeeArrow 8614\nRightTeeVector 10587\n"
  142. + "RightTriangle 8883\nRightTriangleBar 10704\nRightTriangleEqual 8885\n"
  143. + "RightUpDownVector 10575\nRightUpTeeVector 10588\nRightUpVector 8638\n"
  144. + "RightUpVectorBar 10580\nRightVector 8640\nRightVectorBar 10579\nRightarrow 8658\n"
  145. + "Ropf 8477\nRoundImplies 10608\nRrightarrow 8667\nRscr 8475\nRsh 8625\nRuleDelayed 10740\n"
  146. + "SHCHcy 1065\nSHcy 1064\nSOFTcy 1068\nSacute 346\nSc 10940\nScaron 352\nScedil 350\n"
  147. + "Scirc 348\nScy 1057\nSfr 120086\nShortDownArrow 8595\nShortLeftArrow 8592\n"
  148. + "ShortRightArrow 8594\nShortUpArrow 8593\nSigma 931\nSmallCircle 8728\nSopf 120138\n"
  149. + "Sqrt 8730\nSquare 9633\nSquareIntersection 8851\nSquareSubset 8847\n"
  150. + "SquareSubsetEqual 8849\nSquareSuperset 8848\nSquareSupersetEqual 8850\nSquareUnion 8852\n"
  151. + "Sscr 119982\nStar 8902\nSub 8912\nSubset 8912\nSubsetEqual 8838\nSucceeds 8827\n"
  152. + "SucceedsEqual 10928\nSucceedsSlantEqual 8829\nSucceedsTilde 8831\nSuchThat 8715\n"
  153. + "Sum 8721\nSup 8913\nSuperset 8835\nSupersetEqual 8839\nSupset 8913\nTHORN 222\n"
  154. + "TRADE 8482\nTSHcy 1035\nTScy 1062\nTab 9\nTau 932\nTcaron 356\nTcedil 354\nTcy 1058\n"
  155. + "Tfr 120087\nTherefore 8756\nTheta 920\nThickSpace 8287,8202\nThinSpace 8201\nTilde 8764\n"
  156. + "TildeEqual 8771\nTildeFullEqual 8773\nTildeTilde 8776\nTopf 120139\nTripleDot 8411\n"
  157. + "Tscr 119983\nTstrok 358\nUacute 218\nUarr 8607\nUarrocir 10569\nUbrcy 1038\nUbreve 364\n"
  158. + "Ucirc 219\nUcy 1059\nUdblac 368\nUfr 120088\nUgrave 217\nUmacr 362\nUnderBar 95\n"
  159. + "UnderBrace 9183\nUnderBracket 9141\nUnderParenthesis 9181\nUnion 8899\nUnionPlus 8846\n"
  160. + "Uogon 370\nUopf 120140\nUpArrow 8593\nUpArrowBar 10514\nUpArrowDownArrow 8645\n"
  161. + "UpDownArrow 8597\nUpEquilibrium 10606\nUpTee 8869\nUpTeeArrow 8613\nUparrow 8657\n"
  162. + "Updownarrow 8661\nUpperLeftArrow 8598\nUpperRightArrow 8599\nUpsi 978\nUpsilon 933\n"
  163. + "Uring 366\nUscr 119984\nUtilde 360\nUuml 220\nVDash 8875\nVbar 10987\nVcy 1042\n"
  164. + "Vdash 8873\nVdashl 10982\nVee 8897\nVerbar 8214\nVert 8214\nVerticalBar 8739\n"
  165. + "VerticalLine 124\nVerticalSeparator 10072\nVerticalTilde 8768\nVeryThinSpace 8202\n"
  166. + "Vfr 120089\nVopf 120141\nVscr 119985\nVvdash 8874\nWcirc 372\nWedge 8896\nWfr 120090\n"
  167. + "Wopf 120142\nWscr 119986\nXfr 120091\nXi 926\nXopf 120143\nXscr 119987\nYAcy 1071\n"
  168. + "YIcy 1031\nYUcy 1070\nYacute 221\nYcirc 374\nYcy 1067\nYfr 120092\nYopf 120144\n"
  169. + "Yscr 119988\nYuml 376\nZHcy 1046\nZacute 377\nZcaron 381\nZcy 1047\nZdot 379\n"
  170. + "ZeroWidthSpace 8203\nZeta 918\nZfr 8488\nZopf 8484\nZscr 119989\naacute 225\nabreve 259\n"
  171. + "ac 8766\nacE 8766,819\nacd 8767\nacirc 226\nacute 180\nacy 1072\naelig 230\naf 8289\n"
  172. + "afr 120094\nagrave 224\nalefsym 8501\naleph 8501\nalpha 945\namacr 257\namalg 10815\n"
  173. + "amp 38\nand 8743\nandand 10837\nandd 10844\nandslope 10840\nandv 10842\nang 8736\n"
  174. + "ange 10660\nangle 8736\nangmsd 8737\nangmsdaa 10664\nangmsdab 10665\nangmsdac 10666\n"
  175. + "angmsdad 10667\nangmsdae 10668\nangmsdaf 10669\nangmsdag 10670\nangmsdah 10671\n"
  176. + "angrt 8735\nangrtvb 8894\nangrtvbd 10653\nangsph 8738\nangst 197\nangzarr 9084\n"
  177. + "aogon 261\naopf 120146\nap 8776\napE 10864\napacir 10863\nape 8778\napid 8779\napos 39\n"
  178. + "approx 8776\napproxeq 8778\naring 229\nascr 119990\nast 42\nasymp 8776\nasympeq 8781\n"
  179. + "atilde 227\nauml 228\nawconint 8755\nawint 10769\nbNot 10989\nbackcong 8780\n"
  180. + "backepsilon 1014\nbackprime 8245\nbacksim 8765\nbacksimeq 8909\nbarvee 8893\nbarwed 8965\n"
  181. + "barwedge 8965\nbbrk 9141\nbbrktbrk 9142\nbcong 8780\nbcy 1073\nbdquo 8222\nbecaus 8757\n"
  182. + "because 8757\nbemptyv 10672\nbepsi 1014\nbernou 8492\nbeta 946\nbeth 8502\nbetween 8812\n"
  183. + "bfr 120095\nbigcap 8898\nbigcirc 9711\nbigcup 8899\nbigodot 10752\nbigoplus 10753\n"
  184. + "bigotimes 10754\nbigsqcup 10758\nbigstar 9733\nbigtriangledown 9661\nbigtriangleup 9651\n"
  185. + "biguplus 10756\nbigvee 8897\nbigwedge 8896\nbkarow 10509\nblacklozenge 10731\n"
  186. + "blacksquare 9642\nblacktriangle 9652\nblacktriangledown 9662\nblacktriangleleft 9666\n"
  187. + "blacktriangleright 9656\nblank 9251\nblk12 9618\nblk14 9617\nblk34 9619\nblock 9608\n"
  188. + "bne 61,8421\nbnequiv 8801,8421\nbnot 8976\nbopf 120147\nbot 8869\nbottom 8869\n"
  189. + "bowtie 8904\nboxDL 9559\nboxDR 9556\nboxDl 9558\nboxDr 9555\nboxH 9552\nboxHD 9574\n"
  190. + "boxHU 9577\nboxHd 9572\nboxHu 9575\nboxUL 9565\nboxUR 9562\nboxUl 9564\nboxUr 9561\n"
  191. + "boxV 9553\nboxVH 9580\nboxVL 9571\nboxVR 9568\nboxVh 9579\nboxVl 9570\nboxVr 9567\n"
  192. + "boxbox 10697\nboxdL 9557\nboxdR 9554\nboxdl 9488\nboxdr 9484\nboxh 9472\nboxhD 9573\n"
  193. + "boxhU 9576\nboxhd 9516\nboxhu 9524\nboxminus 8863\nboxplus 8862\nboxtimes 8864\n"
  194. + "boxuL 9563\nboxuR 9560\nboxul 9496\nboxur 9492\nboxv 9474\nboxvH 9578\nboxvL 9569\n"
  195. + "boxvR 9566\nboxvh 9532\nboxvl 9508\nboxvr 9500\nbprime 8245\nbreve 728\nbrvbar 166\n"
  196. + "bscr 119991\nbsemi 8271\nbsim 8765\nbsime 8909\nbsol 92\nbsolb 10693\nbsolhsub 10184\n"
  197. + "bull 8226\nbullet 8226\nbump 8782\nbumpE 10926\nbumpe 8783\nbumpeq 8783\ncacute 263\n"
  198. + "cap 8745\ncapand 10820\ncapbrcup 10825\ncapcap 10827\ncapcup 10823\ncapdot 10816\n"
  199. + "caps 8745,65024\ncaret 8257\ncaron 711\nccaps 10829\nccaron 269\nccedil 231\nccirc 265\n"
  200. + "ccups 10828\nccupssm 10832\ncdot 267\ncedil 184\ncemptyv 10674\ncent 162\ncenterdot 183\n"
  201. + "cfr 120096\nchcy 1095\ncheck 10003\ncheckmark 10003\nchi 967\ncir 9675\ncirE 10691\n"
  202. + "circ 710\ncirceq 8791\ncirclearrowleft 8634\ncirclearrowright 8635\ncircledR 174\n"
  203. + "circledS 9416\ncircledast 8859\ncircledcirc 8858\ncircleddash 8861\ncire 8791\n"
  204. + "cirfnint 10768\ncirmid 10991\ncirscir 10690\nclubs 9827\nclubsuit 9827\ncolon 58\n"
  205. + "colone 8788\ncoloneq 8788\ncomma 44\ncommat 64\ncomp 8705\ncompfn 8728\ncomplement 8705\n"
  206. + "complexes 8450\ncong 8773\ncongdot 10861\nconint 8750\ncopf 120148\ncoprod 8720\n"
  207. + "copy 169\ncopysr 8471\ncrarr 8629\ncross 10007\ncscr 119992\ncsub 10959\ncsube 10961\n"
  208. + "csup 10960\ncsupe 10962\nctdot 8943\ncudarrl 10552\ncudarrr 10549\ncuepr 8926\n"
  209. + "cuesc 8927\ncularr 8630\ncularrp 10557\ncup 8746\ncupbrcap 10824\ncupcap 10822\n"
  210. + "cupcup 10826\ncupdot 8845\ncupor 10821\ncups 8746,65024\ncurarr 8631\ncurarrm 10556\n"
  211. + "curlyeqprec 8926\ncurlyeqsucc 8927\ncurlyvee 8910\ncurlywedge 8911\ncurren 164\n"
  212. + "curvearrowleft 8630\ncurvearrowright 8631\ncuvee 8910\ncuwed 8911\ncwconint 8754\n"
  213. + "cwint 8753\ncylcty 9005\ndArr 8659\ndHar 10597\ndagger 8224\ndaleth 8504\ndarr 8595\n"
  214. + "dash 8208\ndashv 8867\ndbkarow 10511\ndblac 733\ndcaron 271\ndcy 1076\ndd 8518\n"
  215. + "ddagger 8225\nddarr 8650\nddotseq 10871\ndeg 176\ndelta 948\ndemptyv 10673\ndfisht 10623\n"
  216. + "dfr 120097\ndharl 8643\ndharr 8642\ndiam 8900\ndiamond 8900\ndiamondsuit 9830\n"
  217. + "diams 9830\ndie 168\ndigamma 989\ndisin 8946\ndiv 247\ndivide 247\ndivideontimes 8903\n"
  218. + "divonx 8903\ndjcy 1106\ndlcorn 8990\ndlcrop 8973\ndollar 36\ndopf 120149\ndot 729\n"
  219. + "doteq 8784\ndoteqdot 8785\ndotminus 8760\ndotplus 8724\ndotsquare 8865\n"
  220. + "doublebarwedge 8966\ndownarrow 8595\ndowndownarrows 8650\ndownharpoonleft 8643\n"
  221. + "downharpoonright 8642\ndrbkarow 10512\ndrcorn 8991\ndrcrop 8972\ndscr 119993\ndscy 1109\n"
  222. + "dsol 10742\ndstrok 273\ndtdot 8945\ndtri 9663\ndtrif 9662\nduarr 8693\nduhar 10607\n"
  223. + "dwangle 10662\ndzcy 1119\ndzigrarr 10239\neDDot 10871\neDot 8785\neacute 233\n"
  224. + "easter 10862\necaron 283\necir 8790\necirc 234\necolon 8789\necy 1101\nedot 279\nee 8519\n"
  225. + "efDot 8786\nefr 120098\neg 10906\negrave 232\negs 10902\negsdot 10904\nel 10905\n"
  226. + "elinters 9191\nell 8467\nels 10901\nelsdot 10903\nemacr 275\nempty 8709\nemptyset 8709\n"
  227. + "emptyv 8709\nemsp 8195\nemsp13 8196\nemsp14 8197\neng 331\nensp 8194\neogon 281\n"
  228. + "eopf 120150\nepar 8917\neparsl 10723\neplus 10865\nepsi 949\nepsilon 949\nepsiv 1013\n"
  229. + "eqcirc 8790\neqcolon 8789\neqsim 8770\neqslantgtr 10902\neqslantless 10901\nequals 61\n"
  230. + "equest 8799\nequiv 8801\nequivDD 10872\neqvparsl 10725\nerDot 8787\nerarr 10609\n"
  231. + "escr 8495\nesdot 8784\nesim 8770\neta 951\neth 240\neuml 235\neuro 8364\nexcl 33\n"
  232. + "exist 8707\nexpectation 8496\nexponentiale 8519\nfallingdotseq 8786\nfcy 1092\n"
  233. + "female 9792\nffilig 64259\nfflig 64256\nffllig 64260\nffr 120099\nfilig 64257\n"
  234. + "fjlig 102,106\nflat 9837\nfllig 64258\nfltns 9649\nfnof 402\nfopf 120151\nforall 8704\n"
  235. + "fork 8916\nforkv 10969\nfpartint 10765\nfrac12 189\nfrac13 8531\nfrac14 188\nfrac15 8533\n"
  236. + "frac16 8537\nfrac18 8539\nfrac23 8532\nfrac25 8534\nfrac34 190\nfrac35 8535\nfrac38 8540\n"
  237. + "frac45 8536\nfrac56 8538\nfrac58 8541\nfrac78 8542\nfrasl 8260\nfrown 8994\nfscr 119995\n"
  238. + "gE 8807\ngEl 10892\ngacute 501\ngamma 947\ngammad 989\ngap 10886\ngbreve 287\ngcirc 285\n"
  239. + "gcy 1075\ngdot 289\nge 8805\ngel 8923\ngeq 8805\ngeqq 8807\ngeqslant 10878\nges 10878\n"
  240. + "gescc 10921\ngesdot 10880\ngesdoto 10882\ngesdotol 10884\ngesl 8923,65024\ngesles 10900\n"
  241. + "gfr 120100\ngg 8811\nggg 8921\ngimel 8503\ngjcy 1107\ngl 8823\nglE 10898\ngla 10917\n"
  242. + "glj 10916\ngnE 8809\ngnap 10890\ngnapprox 10890\ngne 10888\ngneq 10888\ngneqq 8809\n"
  243. + "gnsim 8935\ngopf 120152\ngrave 96\ngscr 8458\ngsim 8819\ngsime 10894\ngsiml 10896\ngt 62\n"
  244. + "gtcc 10919\ngtcir 10874\ngtdot 8919\ngtlPar 10645\ngtquest 10876\ngtrapprox 10886\n"
  245. + "gtrarr 10616\ngtrdot 8919\ngtreqless 8923\ngtreqqless 10892\ngtrless 8823\ngtrsim 8819\n"
  246. + "gvertneqq 8809,65024\ngvnE 8809,65024\nhArr 8660\nhairsp 8202\nhalf 189\nhamilt 8459\n"
  247. + "hardcy 1098\nharr 8596\nharrcir 10568\nharrw 8621\nhbar 8463\nhcirc 293\nhearts 9829\n"
  248. + "heartsuit 9829\nhellip 8230\nhercon 8889\nhfr 120101\nhksearow 10533\nhkswarow 10534\n"
  249. + "hoarr 8703\nhomtht 8763\nhookleftarrow 8617\nhookrightarrow 8618\nhopf 120153\n"
  250. + "horbar 8213\nhscr 119997\nhslash 8463\nhstrok 295\nhybull 8259\nhyphen 8208\niacute 237\n"
  251. + "ic 8291\nicirc 238\nicy 1080\niecy 1077\niexcl 161\niff 8660\nifr 120102\nigrave 236\n"
  252. + "ii 8520\niiiint 10764\niiint 8749\niinfin 10716\niiota 8489\nijlig 307\nimacr 299\n"
  253. + "image 8465\nimagline 8464\nimagpart 8465\nimath 305\nimof 8887\nimped 437\nin 8712\n"
  254. + "incare 8453\ninfin 8734\ninfintie 10717\ninodot 305\nint 8747\nintcal 8890\n"
  255. + "integers 8484\nintercal 8890\nintlarhk 10775\nintprod 10812\niocy 1105\niogon 303\n"
  256. + "iopf 120154\niota 953\niprod 10812\niquest 191\niscr 119998\nisin 8712\nisinE 8953\n"
  257. + "isindot 8949\nisins 8948\nisinsv 8947\nisinv 8712\nit 8290\nitilde 297\niukcy 1110\n"
  258. + "iuml 239\njcirc 309\njcy 1081\njfr 120103\njmath 567\njopf 120155\njscr 119999\n"
  259. + "jsercy 1112\njukcy 1108\nkappa 954\nkappav 1008\nkcedil 311\nkcy 1082\nkfr 120104\n"
  260. + "kgreen 312\nkhcy 1093\nkjcy 1116\nkopf 120156\nkscr 120000\nlAarr 8666\nlArr 8656\n"
  261. + "lAtail 10523\nlBarr 10510\nlE 8806\nlEg 10891\nlHar 10594\nlacute 314\nlaemptyv 10676\n"
  262. + "lagran 8466\nlambda 955\nlang 10216\nlangd 10641\nlangle 10216\nlap 10885\nlaquo 171\n"
  263. + "larr 8592\nlarrb 8676\nlarrbfs 10527\nlarrfs 10525\nlarrhk 8617\nlarrlp 8619\n"
  264. + "larrpl 10553\nlarrsim 10611\nlarrtl 8610\nlat 10923\nlatail 10521\nlate 10925\n"
  265. + "lates 10925,65024\nlbarr 10508\nlbbrk 10098\nlbrace 123\nlbrack 91\nlbrke 10635\n"
  266. + "lbrksld 10639\nlbrkslu 10637\nlcaron 318\nlcedil 316\nlceil 8968\nlcub 123\nlcy 1083\n"
  267. + "ldca 10550\nldquo 8220\nldquor 8222\nldrdhar 10599\nldrushar 10571\nldsh 8626\nle 8804\n"
  268. + "leftarrow 8592\nleftarrowtail 8610\nleftharpoondown 8637\nleftharpoonup 8636\n"
  269. + "leftleftarrows 8647\nleftrightarrow 8596\nleftrightarrows 8646\nleftrightharpoons 8651\n"
  270. + "leftrightsquigarrow 8621\nleftthreetimes 8907\nleg 8922\nleq 8804\nleqq 8806\n"
  271. + "leqslant 10877\nles 10877\nlescc 10920\nlesdot 10879\nlesdoto 10881\nlesdotor 10883\n"
  272. + "lesg 8922,65024\nlesges 10899\nlessapprox 10885\nlessdot 8918\nlesseqgtr 8922\n"
  273. + "lesseqqgtr 10891\nlessgtr 8822\nlesssim 8818\nlfisht 10620\nlfloor 8970\nlfr 120105\n"
  274. + "lg 8822\nlgE 10897\nlhard 8637\nlharu 8636\nlharul 10602\nlhblk 9604\nljcy 1113\nll 8810\n"
  275. + "llarr 8647\nllcorner 8990\nllhard 10603\nlltri 9722\nlmidot 320\nlmoust 9136\n"
  276. + "lmoustache 9136\nlnE 8808\nlnap 10889\nlnapprox 10889\nlne 10887\nlneq 10887\nlneqq 8808\n"
  277. + "lnsim 8934\nloang 10220\nloarr 8701\nlobrk 10214\nlongleftarrow 10229\n"
  278. + "longleftrightarrow 10231\nlongmapsto 10236\nlongrightarrow 10230\nlooparrowleft 8619\n"
  279. + "looparrowright 8620\nlopar 10629\nlopf 120157\nloplus 10797\nlotimes 10804\nlowast 8727\n"
  280. + "lowbar 95\nloz 9674\nlozenge 9674\nlozf 10731\nlpar 40\nlparlt 10643\nlrarr 8646\n"
  281. + "lrcorner 8991\nlrhar 8651\nlrhard 10605\nlrm 8206\nlrtri 8895\nlsaquo 8249\nlscr 120001\n"
  282. + "lsh 8624\nlsim 8818\nlsime 10893\nlsimg 10895\nlsqb 91\nlsquo 8216\nlsquor 8218\n"
  283. + "lstrok 322\nlt 60\nltcc 10918\nltcir 10873\nltdot 8918\nlthree 8907\nltimes 8905\n"
  284. + "ltlarr 10614\nltquest 10875\nltrPar 10646\nltri 9667\nltrie 8884\nltrif 9666\n"
  285. + "lurdshar 10570\nluruhar 10598\nlvertneqq 8808,65024\nlvnE 8808,65024\nmDDot 8762\n"
  286. + "macr 175\nmale 9794\nmalt 10016\nmaltese 10016\nmap 8614\nmapsto 8614\nmapstodown 8615\n"
  287. + "mapstoleft 8612\nmapstoup 8613\nmarker 9646\nmcomma 10793\nmcy 1084\nmdash 8212\n"
  288. + "measuredangle 8737\nmfr 120106\nmho 8487\nmicro 181\nmid 8739\nmidast 42\nmidcir 10992\n"
  289. + "middot 183\nminus 8722\nminusb 8863\nminusd 8760\nminusdu 10794\nmlcp 10971\nmldr 8230\n"
  290. + "mnplus 8723\nmodels 8871\nmopf 120158\nmp 8723\nmscr 120002\nmstpos 8766\nmu 956\n"
  291. + "multimap 8888\nmumap 8888\nnGg 8921,824\nnGt 8811,8402\nnGtv 8811,824\nnLeftarrow 8653\n"
  292. + "nLeftrightarrow 8654\nnLl 8920,824\nnLt 8810,8402\nnLtv 8810,824\nnRightarrow 8655\n"
  293. + "nVDash 8879\nnVdash 8878\nnabla 8711\nnacute 324\nnang 8736,8402\nnap 8777\n"
  294. + "napE 10864,824\nnapid 8779,824\nnapos 329\nnapprox 8777\nnatur 9838\nnatural 9838\n"
  295. + "naturals 8469\nnbsp 160\nnbump 8782,824\nnbumpe 8783,824\nncap 10819\nncaron 328\n"
  296. + "ncedil 326\nncong 8775\nncongdot 10861,824\nncup 10818\nncy 1085\nndash 8211\nne 8800\n"
  297. + "neArr 8663\nnearhk 10532\nnearr 8599\nnearrow 8599\nnedot 8784,824\nnequiv 8802\n"
  298. + "nesear 10536\nnesim 8770,824\nnexist 8708\nnexists 8708\nnfr 120107\nngE 8807,824\n"
  299. + "nge 8817\nngeq 8817\nngeqq 8807,824\nngeqslant 10878,824\nnges 10878,824\nngsim 8821\n"
  300. + "ngt 8815\nngtr 8815\nnhArr 8654\nnharr 8622\nnhpar 10994\nni 8715\nnis 8956\nnisd 8954\n"
  301. + "niv 8715\nnjcy 1114\nnlArr 8653\nnlE 8806,824\nnlarr 8602\nnldr 8229\nnle 8816\n"
  302. + "nleftarrow 8602\nnleftrightarrow 8622\nnleq 8816\nnleqq 8806,824\nnleqslant 10877,824\n"
  303. + "nles 10877,824\nnless 8814\nnlsim 8820\nnlt 8814\nnltri 8938\nnltrie 8940\nnmid 8740\n"
  304. + "nopf 120159\nnot 172\nnotin 8713\nnotinE 8953,824\nnotindot 8949,824\nnotinva 8713\n"
  305. + "notinvb 8951\nnotinvc 8950\nnotni 8716\nnotniva 8716\nnotnivb 8958\nnotnivc 8957\n"
  306. + "npar 8742\nnparallel 8742\nnparsl 11005,8421\nnpart 8706,824\nnpolint 10772\nnpr 8832\n"
  307. + "nprcue 8928\nnpre 10927,824\nnprec 8832\nnpreceq 10927,824\nnrArr 8655\nnrarr 8603\n"
  308. + "nrarrc 10547,824\nnrarrw 8605,824\nnrightarrow 8603\nnrtri 8939\nnrtrie 8941\nnsc 8833\n"
  309. + "nsccue 8929\nnsce 10928,824\nnscr 120003\nnshortmid 8740\nnshortparallel 8742\nnsim 8769\n"
  310. + "nsime 8772\nnsimeq 8772\nnsmid 8740\nnspar 8742\nnsqsube 8930\nnsqsupe 8931\nnsub 8836\n"
  311. + "nsubE 10949,824\nnsube 8840\nnsubset 8834,8402\nnsubseteq 8840\nnsubseteqq 10949,824\n"
  312. + "nsucc 8833\nnsucceq 10928,824\nnsup 8837\nnsupE 10950,824\nnsupe 8841\nnsupset 8835,8402\n"
  313. + "nsupseteq 8841\nnsupseteqq 10950,824\nntgl 8825\nntilde 241\nntlg 8824\n"
  314. + "ntriangleleft 8938\nntrianglelefteq 8940\nntriangleright 8939\nntrianglerighteq 8941\n"
  315. + "nu 957\nnum 35\nnumero 8470\nnumsp 8199\nnvDash 8877\nnvHarr 10500\nnvap 8781,8402\n"
  316. + "nvdash 8876\nnvge 8805,8402\nnvgt 62,8402\nnvinfin 10718\nnvlArr 10498\nnvle 8804,8402\n"
  317. + "nvlt 60,8402\nnvltrie 8884,8402\nnvrArr 10499\nnvrtrie 8885,8402\nnvsim 8764,8402\n"
  318. + "nwArr 8662\nnwarhk 10531\nnwarr 8598\nnwarrow 8598\nnwnear 10535\noS 9416\noacute 243\n"
  319. + "oast 8859\nocir 8858\nocirc 244\nocy 1086\nodash 8861\nodblac 337\nodiv 10808\nodot 8857\n"
  320. + "odsold 10684\noelig 339\nofcir 10687\nofr 120108\nogon 731\nograve 242\nogt 10689\n"
  321. + "ohbar 10677\nohm 937\noint 8750\nolarr 8634\nolcir 10686\nolcross 10683\noline 8254\n"
  322. + "olt 10688\nomacr 333\nomega 969\nomicron 959\nomid 10678\nominus 8854\noopf 120160\n"
  323. + "opar 10679\noperp 10681\noplus 8853\nor 8744\norarr 8635\nord 10845\norder 8500\n"
  324. + "orderof 8500\nordf 170\nordm 186\norigof 8886\noror 10838\norslope 10839\norv 10843\n"
  325. + "oscr 8500\noslash 248\nosol 8856\notilde 245\notimes 8855\notimesas 10806\nouml 246\n"
  326. + "ovbar 9021\npar 8741\npara 182\nparallel 8741\nparsim 10995\nparsl 11005\npart 8706\n"
  327. + "pcy 1087\npercnt 37\nperiod 46\npermil 8240\nperp 8869\npertenk 8241\npfr 120109\n"
  328. + "phi 966\nphiv 981\nphmmat 8499\nphone 9742\npi 960\npitchfork 8916\npiv 982\nplanck 8463\n"
  329. + "planckh 8462\nplankv 8463\nplus 43\nplusacir 10787\nplusb 8862\npluscir 10786\n"
  330. + "plusdo 8724\nplusdu 10789\npluse 10866\nplusmn 177\nplussim 10790\nplustwo 10791\npm 177\n"
  331. + "pointint 10773\npopf 120161\npound 163\npr 8826\nprE 10931\nprap 10935\nprcue 8828\n"
  332. + "pre 10927\nprec 8826\nprecapprox 10935\npreccurlyeq 8828\npreceq 10927\n"
  333. + "precnapprox 10937\nprecneqq 10933\nprecnsim 8936\nprecsim 8830\nprime 8242\nprimes 8473\n"
  334. + "prnE 10933\nprnap 10937\nprnsim 8936\nprod 8719\nprofalar 9006\nprofline 8978\n"
  335. + "profsurf 8979\nprop 8733\npropto 8733\nprsim 8830\nprurel 8880\npscr 120005\npsi 968\n"
  336. + "puncsp 8200\nqfr 120110\nqint 10764\nqopf 120162\nqprime 8279\nqscr 120006\n"
  337. + "quaternions 8461\nquatint 10774\nquest 63\nquesteq 8799\nquot 34\nrAarr 8667\nrArr 8658\n"
  338. + "rAtail 10524\nrBarr 10511\nrHar 10596\nrace 8765,817\nracute 341\nradic 8730\n"
  339. + "raemptyv 10675\nrang 10217\nrangd 10642\nrange 10661\nrangle 10217\nraquo 187\nrarr 8594\n"
  340. + "rarrap 10613\nrarrb 8677\nrarrbfs 10528\nrarrc 10547\nrarrfs 10526\nrarrhk 8618\n"
  341. + "rarrlp 8620\nrarrpl 10565\nrarrsim 10612\nrarrtl 8611\nrarrw 8605\nratail 10522\n"
  342. + "ratio 8758\nrationals 8474\nrbarr 10509\nrbbrk 10099\nrbrace 125\nrbrack 93\nrbrke 10636\n"
  343. + "rbrksld 10638\nrbrkslu 10640\nrcaron 345\nrcedil 343\nrceil 8969\nrcub 125\nrcy 1088\n"
  344. + "rdca 10551\nrdldhar 10601\nrdquo 8221\nrdquor 8221\nrdsh 8627\nreal 8476\nrealine 8475\n"
  345. + "realpart 8476\nreals 8477\nrect 9645\nreg 174\nrfisht 10621\nrfloor 8971\nrfr 120111\n"
  346. + "rhard 8641\nrharu 8640\nrharul 10604\nrho 961\nrhov 1009\nrightarrow 8594\n"
  347. + "rightarrowtail 8611\nrightharpoondown 8641\nrightharpoonup 8640\nrightleftarrows 8644\n"
  348. + "rightleftharpoons 8652\nrightrightarrows 8649\nrightsquigarrow 8605\n"
  349. + "rightthreetimes 8908\nring 730\nrisingdotseq 8787\nrlarr 8644\nrlhar 8652\nrlm 8207\n"
  350. + "rmoust 9137\nrmoustache 9137\nrnmid 10990\nroang 10221\nroarr 8702\nrobrk 10215\n"
  351. + "ropar 10630\nropf 120163\nroplus 10798\nrotimes 10805\nrpar 41\nrpargt 10644\n"
  352. + "rppolint 10770\nrrarr 8649\nrsaquo 8250\nrscr 120007\nrsh 8625\nrsqb 93\nrsquo 8217\n"
  353. + "rsquor 8217\nrthree 8908\nrtimes 8906\nrtri 9657\nrtrie 8885\nrtrif 9656\nrtriltri 10702\n"
  354. + "ruluhar 10600\nrx 8478\nsacute 347\nsbquo 8218\nsc 8827\nscE 10932\nscap 10936\n"
  355. + "scaron 353\nsccue 8829\nsce 10928\nscedil 351\nscirc 349\nscnE 10934\nscnap 10938\n"
  356. + "scnsim 8937\nscpolint 10771\nscsim 8831\nscy 1089\nsdot 8901\nsdotb 8865\nsdote 10854\n"
  357. + "seArr 8664\nsearhk 10533\nsearr 8600\nsearrow 8600\nsect 167\nsemi 59\nseswar 10537\n"
  358. + "setminus 8726\nsetmn 8726\nsext 10038\nsfr 120112\nsfrown 8994\nsharp 9839\nshchcy 1097\n"
  359. + "shcy 1096\nshortmid 8739\nshortparallel 8741\nshy 173\nsigma 963\nsigmaf 962\nsigmav 962\n"
  360. + "sim 8764\nsimdot 10858\nsime 8771\nsimeq 8771\nsimg 10910\nsimgE 10912\nsiml 10909\n"
  361. + "simlE 10911\nsimne 8774\nsimplus 10788\nsimrarr 10610\nslarr 8592\nsmallsetminus 8726\n"
  362. + "smashp 10803\nsmeparsl 10724\nsmid 8739\nsmile 8995\nsmt 10922\nsmte 10924\n"
  363. + "smtes 10924,65024\nsoftcy 1100\nsol 47\nsolb 10692\nsolbar 9023\nsopf 120164\n"
  364. + "spades 9824\nspadesuit 9824\nspar 8741\nsqcap 8851\nsqcaps 8851,65024\nsqcup 8852\n"
  365. + "sqcups 8852,65024\nsqsub 8847\nsqsube 8849\nsqsubset 8847\nsqsubseteq 8849\nsqsup 8848\n"
  366. + "sqsupe 8850\nsqsupset 8848\nsqsupseteq 8850\nsqu 9633\nsquare 9633\nsquarf 9642\n"
  367. + "squf 9642\nsrarr 8594\nsscr 120008\nssetmn 8726\nssmile 8995\nsstarf 8902\nstar 9734\n"
  368. + "starf 9733\nstraightepsilon 1013\nstraightphi 981\nstrns 175\nsub 8834\nsubE 10949\n"
  369. + "subdot 10941\nsube 8838\nsubedot 10947\nsubmult 10945\nsubnE 10955\nsubne 8842\n"
  370. + "subplus 10943\nsubrarr 10617\nsubset 8834\nsubseteq 8838\nsubseteqq 10949\n"
  371. + "subsetneq 8842\nsubsetneqq 10955\nsubsim 10951\nsubsub 10965\nsubsup 10963\nsucc 8827\n"
  372. + "succapprox 10936\nsucccurlyeq 8829\nsucceq 10928\nsuccnapprox 10938\nsuccneqq 10934\n"
  373. + "succnsim 8937\nsuccsim 8831\nsum 8721\nsung 9834\nsup 8835\nsup1 185\nsup2 178\nsup3 179\n"
  374. + "supE 10950\nsupdot 10942\nsupdsub 10968\nsupe 8839\nsupedot 10948\nsuphsol 10185\n"
  375. + "suphsub 10967\nsuplarr 10619\nsupmult 10946\nsupnE 10956\nsupne 8843\nsupplus 10944\n"
  376. + "supset 8835\nsupseteq 8839\nsupseteqq 10950\nsupsetneq 8843\nsupsetneqq 10956\n"
  377. + "supsim 10952\nsupsub 10964\nsupsup 10966\nswArr 8665\nswarhk 10534\nswarr 8601\n"
  378. + "swarrow 8601\nswnwar 10538\nszlig 223\ntarget 8982\ntau 964\ntbrk 9140\ntcaron 357\n"
  379. + "tcedil 355\ntcy 1090\ntdot 8411\ntelrec 8981\ntfr 120113\nthere4 8756\ntherefore 8756\n"
  380. + "theta 952\nthetasym 977\nthetav 977\nthickapprox 8776\nthicksim 8764\nthinsp 8201\n"
  381. + "thkap 8776\nthksim 8764\nthorn 254\ntilde 732\ntimes 215\ntimesb 8864\ntimesbar 10801\n"
  382. + "timesd 10800\ntint 8749\ntoea 10536\ntop 8868\ntopbot 9014\ntopcir 10993\ntopf 120165\n"
  383. + "topfork 10970\ntosa 10537\ntprime 8244\ntrade 8482\ntriangle 9653\ntriangledown 9663\n"
  384. + "triangleleft 9667\ntrianglelefteq 8884\ntriangleq 8796\ntriangleright 9657\n"
  385. + "trianglerighteq 8885\ntridot 9708\ntrie 8796\ntriminus 10810\ntriplus 10809\ntrisb 10701\n"
  386. + "tritime 10811\ntrpezium 9186\ntscr 120009\ntscy 1094\ntshcy 1115\ntstrok 359\ntwixt 8812\n"
  387. + "twoheadleftarrow 8606\ntwoheadrightarrow 8608\nuArr 8657\nuHar 10595\nuacute 250\n"
  388. + "uarr 8593\nubrcy 1118\nubreve 365\nucirc 251\nucy 1091\nudarr 8645\nudblac 369\n"
  389. + "udhar 10606\nufisht 10622\nufr 120114\nugrave 249\nuharl 8639\nuharr 8638\nuhblk 9600\n"
  390. + "ulcorn 8988\nulcorner 8988\nulcrop 8975\nultri 9720\numacr 363\numl 168\nuogon 371\n"
  391. + "uopf 120166\nuparrow 8593\nupdownarrow 8597\nupharpoonleft 8639\nupharpoonright 8638\n"
  392. + "uplus 8846\nupsi 965\nupsih 978\nupsilon 965\nupuparrows 8648\nurcorn 8989\n"
  393. + "urcorner 8989\nurcrop 8974\nuring 367\nurtri 9721\nuscr 120010\nutdot 8944\nutilde 361\n"
  394. + "utri 9653\nutrif 9652\nuuarr 8648\nuuml 252\nuwangle 10663\nvArr 8661\nvBar 10984\n"
  395. + "vBarv 10985\nvDash 8872\nvangrt 10652\nvarepsilon 1013\nvarkappa 1008\nvarnothing 8709\n"
  396. + "varphi 981\nvarpi 982\nvarpropto 8733\nvarr 8597\nvarrho 1009\nvarsigma 962\n"
  397. + "varsubsetneq 8842,65024\nvarsubsetneqq 10955,65024\nvarsupsetneq 8843,65024\n"
  398. + "varsupsetneqq 10956,65024\nvartheta 977\nvartriangleleft 8882\nvartriangleright 8883\n"
  399. + "vcy 1074\nvdash 8866\nvee 8744\nveebar 8891\nveeeq 8794\nvellip 8942\nverbar 124\n"
  400. + "vert 124\nvfr 120115\nvltri 8882\nvnsub 8834,8402\nvnsup 8835,8402\nvopf 120167\n"
  401. + "vprop 8733\nvrtri 8883\nvscr 120011\nvsubnE 10955,65024\nvsubne 8842,65024\n"
  402. + "vsupnE 10956,65024\nvsupne 8843,65024\nvzigzag 10650\nwcirc 373\nwedbar 10847\n"
  403. + "wedge 8743\nwedgeq 8793\nweierp 8472\nwfr 120116\nwopf 120168\nwp 8472\nwr 8768\n"
  404. + "wreath 8768\nwscr 120012\nxcap 8898\nxcirc 9711\nxcup 8899\nxdtri 9661\nxfr 120117\n"
  405. + "xhArr 10234\nxharr 10231\nxi 958\nxlArr 10232\nxlarr 10229\nxmap 10236\nxnis 8955\n"
  406. + "xodot 10752\nxopf 120169\nxoplus 10753\nxotime 10754\nxrArr 10233\nxrarr 10230\n"
  407. + "xscr 120013\nxsqcup 10758\nxuplus 10756\nxutri 9651\nxvee 8897\nxwedge 8896\nyacute 253\n"
  408. + "yacy 1103\nycirc 375\nycy 1099\nyen 165\nyfr 120118\nyicy 1111\nyopf 120170\nyscr 120014\n"
  409. + "yucy 1102\nyuml 255\nzacute 378\nzcaron 382\nzcy 1079\nzdot 380\nzeetrf 8488\nzeta 950\n"
  410. + "zfr 120119\nzhcy 1078\nzigrarr 8669\nzopf 120171\nzscr 120015\nzwj 8205\nzwnj 8204\n"
  411. ;
  412. // ---------------------------------------------------------------------------
  413. // Markdown block structure (CommonMark 0.31.2, section 3)
  414. // ---------------------------------------------------------------------------
  415. //
  416. // A cmark-style line scanner: each line is matched against the stack of
  417. // open "container" blocks (document > blockquote > list > item > ...),
  418. // consuming their prefixes, then new blocks are attempted in order
  419. // (blockquote, ATX heading, fenced code, setext underline, thematic break,
  420. // list item, indented code). Whatever remains is appended to the deepest
  421. // open leaf, or becomes a lazy paragraph continuation.
  422. //
  423. // We do not implement HTML blocks as containers: raw HTML is a security
  424. // hazard for `innerHTML`, so HTML-block-looking paragraphs stay paragraphs
  425. // and get escaped by the inline pass like any other text. That also means
  426. // `<script>` cannot interrupt a paragraph the way the spec allows.
  427. /** Number of columns that count as an indented code block. */
  428. var MD_CODE_INDENT = 4;
  429. /** Characters that can begin a non-paragraph block (fast bail-out). */
  430. var MD_MAYBE_SPECIAL_RE = /^[#`~*+_=<>0-9\-]/;
  431. var MD_THEMATIC_RE = /^(?:\*[ \t]*){3,}$|^(?:_[ \t]*){3,}$|^(?:-[ \t]*){3,}$/;
  432. var MD_BULLET_RE = /^[*+\-]/;
  433. var MD_ORDERED_RE = /^(\d{1,9})([.)])/;
  434. var MD_ATX_RE = /^#{1,6}(?:[ \t]+|$)/;
  435. var MD_FENCE_RE = /^`{3,}(?!.*`)|^~{3,}/;
  436. var MD_CLOSE_FENCE_RE = /^(?:`{3,}|~{3,})(?=[ \t]*$)/;
  437. var MD_SETEXT_RE = /^(?:=+|-+)[ \t]*$/;
  438. var MD_NON_SPACE_RE = /[^ \t\f\v\r\n]/;
  439. /**
  440. * Create a block node of the given type.
  441. * @param {string} type document|blockquote|list|item|paragraph|heading|code|thematic
  442. */
  443. function mdNode(type) {
  444. return {
  445. type: type, parent: null, children: [], strings: [],
  446. open: true, info: '', literal: '',
  447. fenced: false, fenceChar: '', fenceLength: 0, fenceOffset: 0,
  448. level: 1, listData: null, tight: true, headingSetext: false,
  449. sourceLine: 0
  450. };
  451. }
  452. function mdParser() {
  453. var doc = mdNode('document');
  454. return {
  455. doc: doc, tip: doc, oldtip: doc,
  456. offset: 0, column: 0, nextNonspace: 0, nextNonspaceColumn: 0,
  457. indent: 0, indented: false, blank: false, partiallyConsumedTab: false,
  458. allClosed: true, lastMatchedContainer: doc,
  459. currentLine: '', lineNumber: 0, lastLineLength: 0,
  460. refmap: {}, lineOffsets: []
  461. };
  462. }
  463. /** Normalise endings and split into lines (trailing blank from final \n dropped). */
  464. function mdSplitInput(raw) {
  465. var text = String(raw).replace(/\r\n|\r(?!\n)/g, '\n').replace(/\r/g, '\n');
  466. var out = text.split('\n');
  467. if (out.length && out[out.length - 1] === '') out.pop();
  468. return out;
  469. }
  470. // --- parser cursor helpers ------------------------------------------------
  471. /** Find the next non-space/tab char; sets blank/indent/indented on p. */
  472. function mdFindNextNonspace(p) {
  473. var ln = p.currentLine, i = p.offset, cols = p.column, c;
  474. while ((c = ln.charAt(i)) !== '') {
  475. if (c === ' ') { i++; cols++; }
  476. else if (c === '\t') { i++; cols += 4 - (cols % 4); }
  477. else break;
  478. }
  479. p.blank = c === '' ;
  480. p.nextNonspace = i;
  481. p.nextNonspaceColumn = cols;
  482. p.indent = p.nextNonspaceColumn - p.column;
  483. p.indented = p.indent >= MD_CODE_INDENT;
  484. }
  485. /**
  486. * Advance the cursor by `count` columns (or characters when `columns` is
  487. * false). Handles partially consumed tabs, which stay in the line as the
  488. * equivalent spaces.
  489. */
  490. function mdAdvanceOffset(p, count, columns) {
  491. var ln = p.currentLine, charsToTab, advance, c;
  492. while (count > 0 && (c = ln.charAt(p.offset)) !== '') {
  493. if (c === '\t') {
  494. charsToTab = 4 - (p.column % 4);
  495. if (columns) {
  496. p.partiallyConsumedTab = charsToTab > count;
  497. advance = charsToTab > count ? count : charsToTab;
  498. p.column += advance;
  499. if (!p.partiallyConsumedTab) p.offset += 1;
  500. count -= advance;
  501. } else {
  502. p.partiallyConsumedTab = false;
  503. p.column += charsToTab;
  504. p.offset += 1;
  505. count -= 1;
  506. }
  507. } else {
  508. p.partiallyConsumedTab = false;
  509. p.offset += 1;
  510. p.column += 1;
  511. count -= 1;
  512. }
  513. }
  514. }
  515. function mdAdvanceNextNonspace(p) {
  516. p.offset = p.nextNonspace;
  517. p.column = p.nextNonspaceColumn;
  518. p.partiallyConsumedTab = false;
  519. }
  520. /**
  521. * Append the rest of the current line (from p.offset) to the tip. When a
  522. * tab was only partially consumed, the surviving columns are re-emitted as
  523. * spaces, exactly like cmark.
  524. */
  525. function mdAddLine(p) {
  526. var s = '';
  527. if (p.partiallyConsumedTab) {
  528. p.offset += 1; // skip the tab character itself
  529. var charsToTab = 4 - (p.column % 4);
  530. while (s.length < charsToTab) s += ' ';
  531. }
  532. p.tip.strings.push(s + p.currentLine.slice(p.offset));
  533. }
  534. function mdCanContain(type, child) {
  535. if (type === 'item' || type === 'blockquote' ||
  536. type === 'document' || type === 'list') {
  537. if (type === 'list') return child === 'item';
  538. return child !== 'item';
  539. }
  540. return false;
  541. }
  542. function mdAcceptsLines(type) {
  543. return type === 'paragraph' || type === 'code';
  544. }
  545. /** Close every block from tip down to (excluding) `lastMatched`. */
  546. function mdCloseUnmatched(p) {
  547. if (p.allClosed) return;
  548. while (p.oldtip !== p.lastMatchedContainer) {
  549. mdFinalize(p, p.oldtip, p.lineNumber - 1);
  550. p.oldtip = p.oldtip.parent;
  551. }
  552. p.allClosed = true;
  553. }
  554. /**
  555. * Add a child block of `tag` under the tip, finalising any tip that cannot
  556. * contain it first.
  557. */
  558. function mdAddChild(p, tag) {
  559. while (!mdCanContain(p.tip.type, tag)) mdFinalize(p, p.tip, p.lineNumber - 1);
  560. var node = mdNode(tag);
  561. node.parent = p.tip;
  562. node.sourceLine = p.lineNumber;
  563. p.tip.children.push(node);
  564. p.tip = node;
  565. return node;
  566. }
  567. // --- container continue checks -------------------------------------------
  568. // 0 = matched, 1 = not matched, 2 = line fully handled (fence close)
  569. function mdContinueBlock(p, container) {
  570. var ln = p.currentLine, t = container.type;
  571. if (t === 'document' || t === 'list') return 0;
  572. if (t === 'blockquote') {
  573. if (!p.indented && ln.charAt(p.nextNonspace) === '>') {
  574. mdAdvanceNextNonspace(p);
  575. mdAdvanceOffset(p, 1, false);
  576. if (ln.charAt(p.offset) === ' ' || ln.charAt(p.offset) === '\t') {
  577. mdAdvanceOffset(p, 1, true);
  578. }
  579. return 0;
  580. }
  581. return 1;
  582. }
  583. if (t === 'item') {
  584. if (p.blank) {
  585. if (!container.children.length) return 1; // blank after empty item
  586. mdAdvanceNextNonspace(p);
  587. return 0;
  588. }
  589. var need = container.listData.markerOffset + container.listData.padding;
  590. if (p.indent >= need) {
  591. mdAdvanceOffset(p, need, true);
  592. return 0;
  593. }
  594. return 1;
  595. }
  596. if (t === 'code') {
  597. if (container.fenced) {
  598. var rest = ln.slice(p.nextNonspace);
  599. if (p.indent <= 3 && ln.charAt(p.nextNonspace) === container.fenceChar &&
  600. MD_CLOSE_FENCE_RE.test(rest) && rest.match(MD_CLOSE_FENCE_RE)[0].length >= container.fenceLength) {
  601. mdFinalize(p, container, p.lineNumber);
  602. return 2;
  603. }
  604. // skip up to fenceOffset leading spaces
  605. var i = container.fenceOffset;
  606. while (i > 0 && (ln.charAt(p.offset) === ' ' || ln.charAt(p.offset) === '\t')) {
  607. mdAdvanceOffset(p, 1, true);
  608. i--;
  609. }
  610. return 0;
  611. }
  612. if (p.indent >= MD_CODE_INDENT) { mdAdvanceOffset(p, MD_CODE_INDENT, true); return 0; }
  613. if (p.blank) { mdAdvanceNextNonspace(p); return 0; }
  614. return 1;
  615. }
  616. if (t === 'heading' || t === 'thematic') return 1;
  617. if (t === 'paragraph') return p.blank ? 1 : 0;
  618. return 1;
  619. }
  620. /**
  621. * True when a blank line separates `node` from its following sibling (used
  622. * for the tight/loose list decision).
  623. */
  624. function mdEndsWithBlank(node) {
  625. if (!node.parent) return false;
  626. var idx = node.parent.children.indexOf(node);
  627. var next = node.parent.children[idx + 1];
  628. if (!next) return false;
  629. return mdNodeEndLine(node) !== next.sourceLine - 1;
  630. }
  631. /** Last source line number consumed by a node (tracked during the scan). */
  632. function mdNodeEndLine(node) {
  633. return node.endLine == null ? node.sourceLine : node.endLine;
  634. }
  635. // --- block starts ----------------------------------------------------------
  636. /**
  637. * Parse a list marker at the cursor. Returns the marker data or null.
  638. * Mirrors cmark: the marker itself, then 1-4 spaces (5+ or a blank rest
  639. * means "content starts one space after the marker").
  640. */
  641. function mdParseListMarker(p, container) {
  642. var rest = p.currentLine.slice(p.nextNonspace);
  643. var data = { type: null, tight: true, bulletChar: null, start: null,
  644. delimiter: null, padding: null, markerOffset: p.indent };
  645. var m, nextc;
  646. if (p.indent >= 4) return null;
  647. if ((m = rest.match(MD_BULLET_RE))) {
  648. data.type = 'bullet';
  649. data.bulletChar = m[0].charAt(0);
  650. } else if ((m = rest.match(MD_ORDERED_RE)) &&
  651. (container.type !== 'paragraph' || Number(m[1]) === 1)) {
  652. data.type = 'ordered';
  653. data.start = parseInt(m[1], 10);
  654. data.delimiter = m[2];
  655. } else {
  656. return null;
  657. }
  658. nextc = p.currentLine.charAt(p.nextNonspace + m[0].length);
  659. if (!(nextc === '' || nextc === ' ' || nextc === '\t')) return null;
  660. if (container.type === 'paragraph' &&
  661. !MD_NON_SPACE_RE.test(p.currentLine.slice(p.nextNonspace + m[0].length))) {
  662. return null;
  663. }
  664. mdAdvanceNextNonspace(p);
  665. mdAdvanceOffset(p, m[0].length, true);
  666. var spacesStartCol = p.column, spacesStartOffset = p.offset;
  667. do {
  668. mdAdvanceOffset(p, 1, true);
  669. nextc = p.currentLine.charAt(p.offset);
  670. } while (p.column - spacesStartCol < 5 && (nextc === ' ' || nextc === '\t'));
  671. var blankItem = p.currentLine.charAt(p.offset) === '' && p.offset >= p.currentLine.length;
  672. var spacesAfterMarker = p.column - spacesStartCol;
  673. if (spacesAfterMarker >= 5 || spacesAfterMarker < 1 || blankItem) {
  674. data.padding = m[0].length + 1;
  675. p.column = spacesStartCol;
  676. p.offset = spacesStartOffset;
  677. var c2 = p.currentLine.charAt(p.offset);
  678. if (c2 === ' ' || c2 === '\t') mdAdvanceOffset(p, 1, true);
  679. } else {
  680. data.padding = m[0].length + spacesAfterMarker;
  681. }
  682. return data;
  683. }
  684. function mdListsMatch(a, b) {
  685. return a.type === b.type && a.delimiter === b.delimiter &&
  686. a.bulletChar === b.bulletChar;
  687. }
  688. /**
  689. * Try to start a new block at the cursor. Returns 0 (no match), 1 (opened a
  690. * container, keep trying), or 2 (opened a leaf; the line is spent).
  691. */
  692. function mdTryBlockStart(p, container) {
  693. var ln = p.currentLine, m, node;
  694. // block quote
  695. if (!p.indented && ln.charAt(p.nextNonspace) === '>') {
  696. mdAdvanceNextNonspace(p);
  697. mdAdvanceOffset(p, 1, false);
  698. if (ln.charAt(p.offset) === ' ' || ln.charAt(p.offset) === '\t') {
  699. mdAdvanceOffset(p, 1, true);
  700. }
  701. mdCloseUnmatched(p);
  702. mdAddChild(p, 'blockquote');
  703. return 1;
  704. }
  705. // ATX heading
  706. if (!p.indented && (m = ln.slice(p.nextNonspace).match(MD_ATX_RE))) {
  707. mdAdvanceNextNonspace(p);
  708. mdAdvanceOffset(p, m[0].length, false);
  709. mdCloseUnmatched(p);
  710. node = mdAddChild(p, 'heading');
  711. node.level = m[0].replace(/[ \t]/g, '').length;
  712. node.strings.push(
  713. ln.slice(p.offset)
  714. .replace(/^[ \t]*#+[ \t]*$/, '')
  715. .replace(/[ \t]+#+[ \t]*$/, ''));
  716. mdAdvanceOffset(p, ln.length - p.offset, false);
  717. return 2;
  718. }
  719. // fenced code block
  720. if (!p.indented && (m = ln.slice(p.nextNonspace).match(MD_FENCE_RE))) {
  721. mdCloseUnmatched(p);
  722. node = mdAddChild(p, 'code');
  723. node.fenced = true;
  724. node.fenceLength = m[0].length;
  725. node.fenceChar = m[0].charAt(0);
  726. node.fenceOffset = p.indent;
  727. mdAdvanceNextNonspace(p);
  728. mdAdvanceOffset(p, m[0].length, false);
  729. return 2;
  730. }
  731. // setext heading underline
  732. if (!p.indented && container.type === 'paragraph' &&
  733. (m = ln.slice(p.nextNonspace).match(MD_SETEXT_RE))) {
  734. mdCloseUnmatched(p);
  735. var pos;
  736. var joined = container.strings.join('\n');
  737. while (joined.charAt(0) === '[' && (pos = mdParseReference(joined, p.refmap)) > 0) {
  738. joined = joined.slice(pos);
  739. }
  740. container.strings = joined.length ? [joined] : [];
  741. var content = container.strings.join('\n');
  742. if (content.length > 0) {
  743. node = mdNode('heading');
  744. node.level = m[0].charAt(0) === '=' ? 1 : 2;
  745. node.headingSetext = true;
  746. node.strings = container.strings.slice();
  747. node.sourceLine = container.sourceLine;
  748. node.endLine = p.lineNumber;
  749. node.parent = container.parent;
  750. var ci = container.parent.children.indexOf(container);
  751. container.parent.children[ci] = node;
  752. p.tip = node;
  753. mdAdvanceOffset(p, ln.length - p.offset, false);
  754. return 2;
  755. }
  756. return 0;
  757. }
  758. // thematic break
  759. if (!p.indented && MD_THEMATIC_RE.test(ln.slice(p.nextNonspace))) {
  760. mdCloseUnmatched(p);
  761. mdAddChild(p, 'thematic');
  762. mdAdvanceOffset(p, ln.length - p.offset, false);
  763. return 2;
  764. }
  765. // list item
  766. var data;
  767. if ((!p.indented || container.type === 'list') && (data = mdParseListMarker(p, container))) {
  768. mdCloseUnmatched(p);
  769. if (p.tip.type !== 'list' || !mdListsMatch(container.listData, data)) {
  770. var list = mdAddChild(p, 'list');
  771. list.listData = data;
  772. container = list;
  773. }
  774. var item = mdAddChild(p, 'item');
  775. item.listData = data;
  776. return 1;
  777. }
  778. // indented code block
  779. if (p.indented && p.tip.type !== 'paragraph' && !p.blank) {
  780. mdAdvanceOffset(p, MD_CODE_INDENT, true);
  781. mdCloseUnmatched(p);
  782. mdAddChild(p, 'code');
  783. return 2;
  784. }
  785. return 0;
  786. }
  787. // --- line incorporation and finalisation -----------------------------------
  788. /**
  789. * Process one source line into the open block tree: match container
  790. * prefixes, try to open new blocks, then hand the remainder to a leaf.
  791. */
  792. function mdIncorporateLine(p, ln) {
  793. var container = p.doc, lastChild, allMatched = true, res;
  794. p.oldtip = p.tip;
  795. p.offset = 0;
  796. p.column = 0;
  797. p.blank = false;
  798. p.partiallyConsumedTab = false;
  799. p.lineNumber += 1;
  800. p.currentLine = ln.indexOf('\u0000') >= 0 ? ln.replace(/\u0000/g, '\uFFFD') : ln;
  801. // 1. Match the open containers' prefixes, deepest first.
  802. while (container.children.length) {
  803. lastChild = container.children[container.children.length - 1];
  804. if (!lastChild.open) break;
  805. container = lastChild;
  806. mdFindNextNonspace(p);
  807. res = mdContinueBlock(p, container);
  808. if (res === 2) { p.lastLineLength = ln.length; return; }
  809. if (res === 1) { allMatched = false; container = container.parent; break; }
  810. }
  811. p.allClosed = container === p.oldtip;
  812. p.lastMatchedContainer = container;
  813. // 2. Unless we already sit in a leaf that accepts lines, try block starts.
  814. var matchedLeaf = container.type !== 'paragraph' && mdAcceptsLines(container.type);
  815. while (!matchedLeaf) {
  816. mdFindNextNonspace(p);
  817. if (!p.indented && !MD_MAYBE_SPECIAL_RE.test(p.currentLine.slice(p.nextNonspace))) {
  818. mdAdvanceNextNonspace(p);
  819. break;
  820. }
  821. res = mdTryBlockStart(p, container);
  822. if (res === 1) { container = p.tip; continue; }
  823. if (res === 2) { container = p.tip; matchedLeaf = true; break; }
  824. mdAdvanceNextNonspace(p);
  825. break;
  826. }
  827. // 3. The remainder is line content for the tip.
  828. if (!p.allClosed && !p.blank && p.tip.type === 'paragraph') {
  829. mdAddLine(p); // lazy paragraph continuation
  830. } else {
  831. mdCloseUnmatched(p);
  832. if (mdAcceptsLines(container.type)) {
  833. mdAddLine(p);
  834. } else if (p.offset < p.currentLine.length && !p.blank) {
  835. mdAddChild(p, 'paragraph');
  836. mdAdvanceNextNonspace(p);
  837. mdAddLine(p);
  838. }
  839. }
  840. p.lastLineLength = ln.length;
  841. }
  842. /**
  843. * Close a block: extract fenced info strings / indented-code literals, work
  844. * out list tightness, peel link reference definitions off paragraphs and
  845. * record which source line the block ended on.
  846. */
  847. function mdFinalize(p, block, endLine) {
  848. var above = block.parent;
  849. block.open = false;
  850. block.endLine = endLine == null ? p.lineNumber : endLine;
  851. if (block.type === 'code') {
  852. if (block.fenced) {
  853. var content = block.strings.join('\n');
  854. var nl = content.indexOf('\n');
  855. var firstLine = nl >= 0 ? content.slice(0, nl) : content;
  856. var rest = nl >= 0 ? content.slice(nl + 1) : '';
  857. block.info = mdUnescapeString(firstLine.replace(/^[ \t]+/, '').replace(/[ \t]+$/, ''));
  858. // cmark keeps the final newline of the block's content
  859. block.literal = rest.length ? rest + '\n' : (block.strings.length > 1 ? '\n' : '');
  860. } else {
  861. var lines = block.strings.slice();
  862. while (lines.length && !MD_NON_SPACE_RE.test(lines[lines.length - 1])) lines.pop();
  863. block.literal = lines.join('\n') + '\n';
  864. }
  865. block.strings = [];
  866. }
  867. if (block.type === 'paragraph') {
  868. // Reference definitions live at the start of paragraphs only; each
  869. // consumed definition must advance or we stop.
  870. var txt = block.strings.join('\n');
  871. var pos;
  872. while (txt.charAt(0) === '[' && (pos = mdParseReference(txt, p.refmap)) > 0) {
  873. txt = txt.slice(pos);
  874. }
  875. block.strings = txt.length ? [txt] : [];
  876. if (!txt.length) mdRemoveFromParent(block);
  877. }
  878. if ((block.type === 'item' || block.type === 'list') && block.children.length) {
  879. // items and lists end where their last child ends (a trailing blank
  880. // line is not part of them) — this drives the tight/loose rule.
  881. // Blockquotes deliberately keep the line their `>` marker last
  882. // appeared on: ` >` is not a blank line for these purposes.
  883. block.endLine = block.children[block.children.length - 1].endLine;
  884. }
  885. if (block.type === 'list') {
  886. block.tight = true;
  887. for (var i = 0; i < block.children.length; i++) {
  888. var item = block.children[i];
  889. if (i < block.children.length - 1 && mdEndsWithBlank(item)) { block.tight = false; break; }
  890. for (var j = 0; j < item.children.length; j++) {
  891. if (j < item.children.length - 1 && mdEndsWithBlank(item.children[j])) { block.tight = false; break; }
  892. }
  893. if (!block.tight) break;
  894. }
  895. }
  896. p.tip = above;
  897. }
  898. /** Detach a node (used when a paragraph turns out to be all references). */
  899. function mdRemoveFromParent(node) {
  900. if (!node.parent) return;
  901. var i = node.parent.children.indexOf(node);
  902. if (i >= 0) node.parent.children.splice(i, 1);
  903. }
  904. /** Parse the whole input into a block tree. */
  905. function mdParseDocument(raw) {
  906. var p = mdParser();
  907. var lines = mdSplitInput(raw);
  908. for (var i = 0; i < lines.length; i++) mdIncorporateLine(p, lines[i]);
  909. while (p.tip && p.tip.type !== 'document') mdFinalize(p, p.tip, lines.length);
  910. return p;
  911. }
  912. // --- shared inline regexes / URI handling -----------------------------------
  913. var MD_LINK_TITLE_RE = /(?:")([^"]*)(?:")|(?:')([^']*)(?:')/;
  914. /**
  915. * Scan a link title at `subject[pos]` without regex backtracking: a quoted
  916. * run (with `\"`-style escapes) or a parenthesised run. Returns
  917. * `{ text, len }` or null.
  918. * @param {string} subject
  919. * @param {number} pos
  920. * @returns {?{text: string, len: number}}
  921. */
  922. function mdScanLinkTitle(subject, pos) {
  923. var start = pos, q = subject.charAt(pos);
  924. if (q !== '"' && q !== "'" && q !== '(') return null;
  925. var close = q === '(' ? ')' : q;
  926. var i = pos + 1;
  927. while (i < subject.length) {
  928. var ch = subject.charAt(i);
  929. if (ch === '\\' && subject.charAt(i + 1) !== '' &&
  930. MD_ESCAPABLE.indexOf(subject.charAt(i + 1)) >= 0) { i += 2; continue; }
  931. if (ch === close) {
  932. return { text: subject.slice(start + 1, i), len: i + 1 - start };
  933. }
  934. if (ch === '\n' && subject.charAt(i + 1) === '\n') return null; // blank line ends it
  935. i++;
  936. }
  937. return null;
  938. }
  939. var MD_LINK_DEST_BRACES_RE = /^<(?:[^<>\n\\\x00]|\\.)*>/;
  940. /**
  941. * End bound for scanning a construct that cannot contain whitespace, '<' or
  942. * '>' from `pos` (autolinks; raw HTML tags scan themselves linearly).
  943. * Slicing to this index instead of the end of the subject keeps the inline
  944. * parser linear on pathological input (many unmatched '<' or '&'): the
  945. * anchored construct regexes cannot match past the bound anyway.
  946. * @param {string} subject
  947. * @param {number} pos
  948. * @returns {number}
  949. */
  950. function mdBoundScan(subject, pos) {
  951. var i = pos + 1, c;
  952. while (i < subject.length) {
  953. c = subject.charCodeAt(i);
  954. if (c <= 0x20 || c === 0x3C || c === 0x3E) break;
  955. i++;
  956. }
  957. return i < subject.length ? i + 1 : subject.length;
  958. }
  959. /**
  960. * Match a raw HTML open/close tag at subject[pos] using a linear scan
  961. * (the equivalent regex backtracks catastrophically on malformed input).
  962. * Returns the matched text or null. SECURITY: callers render this escaped.
  963. * @param {string} subject
  964. * @param {number} pos
  965. * @returns {?string}
  966. */
  967. function mdScanHtmlTag(subject, pos) {
  968. var i = pos;
  969. if (subject.charAt(i) !== '<') return null;
  970. i++;
  971. var closing = subject.charAt(i) === '/';
  972. if (closing) i++;
  973. if (!/[A-Za-z]/.test(subject.charAt(i))) return null;
  974. var start = i;
  975. while (i < subject.length && /[A-Za-z0-9-]/.test(subject.charAt(i))) i++;
  976. if (i === start) return null;
  977. if (closing) {
  978. while (i < subject.length && /[ \t\n]/.test(subject.charAt(i))) i++;
  979. if (subject.charAt(i) === '>') return subject.slice(pos, i + 1);
  980. return null;
  981. }
  982. // attributes
  983. while (i < subject.length) {
  984. var wsStart = i;
  985. while (i < subject.length && /[ \t\n]/.test(subject.charAt(i))) i++;
  986. if (subject.charAt(i) === '>') return subject.slice(pos, i + 1);
  987. if (subject.charAt(i) === '/' && subject.charAt(i + 1) === '>') return subject.slice(pos, i + 2);
  988. if (i === wsStart) return null; // attribute must be preceded by space
  989. var an = i;
  990. while (i < subject.length && !/[\s/=><]/.test(subject.charAt(i))) i++;
  991. if (i === an) return null;
  992. var eq = i;
  993. while (i < subject.length && /[ \t\n]/.test(subject.charAt(i))) i++;
  994. if (subject.charAt(i) !== '=') { i = eq; continue; }
  995. i++;
  996. while (i < subject.length && /[ \t\n]/.test(subject.charAt(i))) i++;
  997. var q = subject.charAt(i);
  998. if (q === '"' || q === "'") {
  999. i++;
  1000. var endq = subject.indexOf(q, i);
  1001. if (endq < 0) return null;
  1002. i = endq + 1;
  1003. } else {
  1004. var v = i;
  1005. while (i < subject.length && !/[\s>]/.test(subject.charAt(i))) i++;
  1006. if (i === v) return null;
  1007. }
  1008. }
  1009. return null;
  1010. }
  1011. /**
  1012. * CommonMark's URL normalisation: percent-encode every character that is
  1013. * not in the RFC 3986 "unreserved + reserved + '#' escape" set. Non-ASCII
  1014. * characters become UTF-8 percent-escapes (like encodeURIComponent).
  1015. * @param {string} uri
  1016. * @returns {string}
  1017. */
  1018. function mdNormalizeUri(uri) {
  1019. if (!uri) return '';
  1020. var out = '', ch, i;
  1021. for (i = 0; i < uri.length; i++) {
  1022. ch = uri.charAt(i);
  1023. if (MD_URI_SAFE_RE.test(ch)) { out += ch; continue; }
  1024. // encode one code point (surrogate pairs together)
  1025. var cp = uri.charCodeAt(i);
  1026. var str = ch;
  1027. if (cp >= 0xD800 && cp <= 0xDBFF && i + 1 < uri.length) {
  1028. str += uri.charAt(i + 1);
  1029. i++;
  1030. }
  1031. out += encodeURIComponent(str);
  1032. }
  1033. return out;
  1034. }
  1035. /** URI characters kept literally (unreserved, reserved and '%'). */
  1036. var MD_URI_SAFE_RE = /^[A-Za-z0-9;,\/?:@&=+\$\-_\.!~\*'\(\)%#]$/;
  1037. /**
  1038. * Normalise a link label for reference lookup: strip brackets, trim,
  1039. * collapse internal whitespace, case-fold.
  1040. * @param {string} label raw `[...]` including brackets
  1041. * @returns {string}
  1042. */
  1043. function mdNormalizeReference(label) {
  1044. return label.slice(1, label.length - 1).trim()
  1045. .replace(/[ \t\r\n]+/g, ' ')
  1046. .toLowerCase().toUpperCase();
  1047. }
  1048. /**
  1049. * Parse one link reference definition from the start of `s`. Returns the
  1050. * number of characters consumed, or 0.
  1051. * @param {string} s
  1052. * @param {Object} refmap
  1053. * @returns {number}
  1054. */
  1055. function mdParseReference(s, refmap) {
  1056. var subject = s, pos = 0, rawlabel, dest, title = null, startpos = 0;
  1057. function peek2() { return pos < subject.length ? subject.charAt(pos) : ''; }
  1058. function match2(re) {
  1059. var m = re.exec(subject.slice(pos));
  1060. if (m) pos += m[0].length;
  1061. return m;
  1062. }
  1063. function spnl2() { match2(/^ *(?:\n *)?/); }
  1064. // label: one bracketed run, no nested brackets, no blank line
  1065. var depth = 0, i = 0, ch;
  1066. while (i < subject.length) {
  1067. ch = subject.charAt(i);
  1068. if (ch === '\\') { i += 2; continue; }
  1069. if (ch === '[') { depth++; if (depth > 1) return 0; }
  1070. else if (ch === ']') break;
  1071. i++;
  1072. }
  1073. if (depth !== 1 || subject.charAt(i) !== ']') return 0;
  1074. rawlabel = subject.slice(0, i + 1);
  1075. if (rawlabel.length > 1001) return 0;
  1076. pos = i + 1;
  1077. if (peek2() !== ':') return 0;
  1078. pos++;
  1079. spnl2();
  1080. // destination
  1081. var m2 = match2(MD_LINK_DEST_BRACES_RE);
  1082. if (m2) {
  1083. dest = mdNormalizeUri(mdUnescapeString(m2[0].slice(1, -1)));
  1084. } else {
  1085. var save = pos, openparens = 0, c;
  1086. while ((c = peek2()) !== '') {
  1087. if (c === '\\' && subject.charAt(pos + 1) !== '' &&
  1088. MD_ESCAPABLE.indexOf(subject.charAt(pos + 1)) >= 0) {
  1089. pos += 1;
  1090. if (peek2() !== '') pos += 1;
  1091. } else if (c === '(') { pos++; openparens++; }
  1092. else if (c === ')') { if (openparens < 1) break; pos++; openparens--; }
  1093. else if (MD_WS_CHAR_RE.test(c)) break;
  1094. else pos++;
  1095. }
  1096. if (pos === save && c !== ')') return 0;
  1097. if (openparens !== 0) return 0;
  1098. dest = mdNormalizeUri(mdUnescapeString(subject.slice(save, pos)));
  1099. }
  1100. var beforetitle = pos;
  1101. spnl2();
  1102. if (pos !== beforetitle) {
  1103. var t = mdScanLinkTitle(subject, pos);
  1104. if (t) { title = mdUnescapeString(t.text); pos += t.len; }
  1105. }
  1106. if (title === null) pos = beforetitle;
  1107. // must be at end of line
  1108. var atLineEnd = match2(/^ *(?:\n|$)/) !== null;
  1109. if (!atLineEnd) {
  1110. if (title !== null) {
  1111. title = null;
  1112. pos = beforetitle;
  1113. atLineEnd = match2(/^ *(?:\n|$)/) !== null;
  1114. }
  1115. if (!atLineEnd) return 0;
  1116. }
  1117. var normlabel = mdNormalizeReference(rawlabel);
  1118. if (normlabel === '') return 0;
  1119. if (!refmap[normlabel]) {
  1120. refmap[normlabel] = { destination: dest, title: title == null ? '' : title };
  1121. }
  1122. return pos;
  1123. }
  1124. // ---------------------------------------------------------------------------
  1125. // Markdown inline parsing (CommonMark 0.31.2, section 6)
  1126. // ---------------------------------------------------------------------------
  1127. //
  1128. // A hand-rolled scanner over paragraph/heading content: plain text runs are
  1129. // copied until a special character (\n ` [ ] \ ! < & * _), then that
  1130. // character's handler runs. Emphasis is resolved afterwards with the
  1131. // delimiter-run algorithm from the spec: openers are searched bottom-up
  1132. // with the "rule of 3" and openers_bottom optimisation; leftover delimiter
  1133. // text stays literal. Links and images share a bracket stack; links may
  1134. // not contain links.
  1135. //
  1136. // Inline nodes form a doubly-linked list (firstChild/lastChild/next/prev on
  1137. // the parent) exactly like the block tree: process_emphasis has to splice
  1138. // nodes out of the middle, which is painful with arrays.
  1139. var MD_ESCAPABLE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';
  1140. var MD_ASCII_PUNCT_TEST_RE = /^[!-/:-@[-`{-~]$/;
  1141. var MD_ENTITY_HERE_RE = /^&(?:#x[a-f0-9]{1,6}|#[0-9]{1,7}|[a-z][a-z0-9]{1,31});/i;
  1142. var MD_TICKS_HERE_RE = /^`+/;
  1143. var MD_WS_CHAR_RE = /[ \t\n\x0b\x0c\x0d]/;
  1144. var MD_FINAL_SPACE_RE = / *$/;
  1145. /**
  1146. * Unicode punctuation/symbol code points (categories P* and S*) above the
  1147. * ASCII range, as "lo-hi" hex ranges (binary-searched). Needed for the
  1148. * left/right-flanking rules on non-ASCII text; ES5 has no \p{P}.
  1149. */
  1150. var MD_UNICODE_PUNCT_RANGES = [
  1151. 'A1-A9','AB-AC','AE-B1','B4','B6-B8','BB','BF','D7','F7','2C2-2C5','2D2-2DF','2E5-2EB',
  1152. '2ED','2EF-2FF','375','37E','384-385','387','3F6','482','55A-55F','589-58A','58D-58F','5BE',
  1153. '5C0','5C3','5C6','5F3-5F4','606-60F','61B','61D-61F','66A-66D','6D4','6DE','6E9','6FD-6FE',
  1154. '700-70D','7F6-7F9','7FE-7FF','830-83E','85E','888','964-965','970','9F2-9F3','9FA-9FB',
  1155. '9FD','A76','AF0-AF1','B70','BF3-BFA','C77','C7F','C84','D4F','D79','DF4','E3F','E4F',
  1156. 'E5A-E5B','F01-F17','F1A-F1F','F34','F36','F38','F3A-F3D','F85','FBE-FC5','FC7-FCC',
  1157. 'FCE-FDA','104A-104F','109E-109F','10FB','1360-1368','1390-1399','1400','166D-166E',
  1158. '169B-169C','16EB-16ED','1735-1736','17D4-17D6','17D8-17DB','1800-180A','1940','1944-1945',
  1159. '19DE-19FF','1A1E-1A1F','1AA0-1AA6','1AA8-1AAD','1B4E-1B4F','1B5A-1B6A','1B74-1B7F',
  1160. '1BFC-1BFF','1C3B-1C3F','1C7E-1C7F','1CC0-1CC7','1CD3','1FBD','1FBF-1FC1','1FCD-1FCF',
  1161. '1FDD-1FDF','1FED-1FEF','1FFD-1FFE','2010-2027','2030-205E','207A-207E','208A-208E',
  1162. '20A0-20C0','2100-2101','2103-2106','2108-2109','2114','2116-2118','211E-2123','2125',
  1163. '2127','2129','212E','213A-213B','2140-2144','214A-214D','214F','218A-218B','2190-2429',
  1164. '2440-244A','249C-24E9','2500-2775','2794-2B73','2B76-2B95','2B97-2BFF','2CE5-2CEA',
  1165. '2CF9-2CFC','2CFE-2CFF','2D70','2E00-2E2E','2E30-2E5D','2E80-2E99','2E9B-2EF3','2F00-2FD5',
  1166. '2FF0-2FFF','3001-3004','3008-3020','3030','3036-3037','303D-303F','309B-309C','30A0',
  1167. '30FB','3190-3191','3196-319F','31C0-31E5','31EF','3200-321E','322A-3247','3250',
  1168. '3260-327F','328A-32B0','32C0-33FF','4DC0-4DFF','A490-A4C6','A4FE-A4FF','A60D-A60F','A673',
  1169. 'A67E','A6F2-A6F7','A700-A716','A720-A721','A789-A78A','A828-A82B','A836-A839','A874-A877',
  1170. 'A8CE-A8CF','A8F8-A8FA','A8FC','A92E-A92F','A95F','A9C1-A9CD','A9DE-A9DF','AA5C-AA5F',
  1171. 'AA77-AA79','AADE-AADF','AAF0-AAF1','AB5B','AB6A-AB6B','ABEB','FB29','FBB2-FBC2',
  1172. 'FD3E-FD4F','FDCF','FDFC-FDFF','FE10-FE19','FE30-FE52','FE54-FE66','FE68-FE6B','FF01-FF0F',
  1173. 'FF1A-FF20','FF3B-FF40','FF5B-FF65','FFE0-FFE6','FFE8-FFEE','FFFC-FFFD','10100-10102',
  1174. '10137-1013F','10179-10189','1018C-1018E','10190-1019C','101A0','101D0-101FC','1039F',
  1175. '103D0','1056F','10857','10877-10878','1091F','1093F','10A50-10A58','10A7F','10AC8',
  1176. '10AF0-10AF6','10B39-10B3F','10B99-10B9C','10D6E','10D8E-10D8F','10EAD','10F55-10F59',
  1177. '10F86-10F89','11047-1104D','110BB-110BC','110BE-110C1','11140-11143','11174-11175',
  1178. '111C5-111C8','111CD','111DB','111DD-111DF','11238-1123D','112A9','113D4-113D5',
  1179. '113D7-113D8','1144B-1144F','1145A-1145B','1145D','114C6','115C1-115D7','11641-11643',
  1180. '11660-1166C','116B9','1173C-1173F','1183B','11944-11946','119E2','11A3F-11A46',
  1181. '11A9A-11A9C','11A9E-11AA2','11B00-11B09','11BE1','11C41-11C45','11C70-11C71','11EF7-11EF8',
  1182. '11F43-11F4F','11FD5-11FF1','11FFF','12470-12474','12FF1-12FF2','16A6E-16A6F','16AF5',
  1183. '16B37-16B3F','16B44-16B45','16D6D-16D6F','16E97-16E9A','16FE2','1BC9C','1BC9F',
  1184. '1CC00-1CCEF','1CD00-1CEB3','1CF50-1CFC3','1D000-1D0F5','1D100-1D126','1D129-1D164',
  1185. '1D16A-1D16C','1D183-1D184','1D18C-1D1A9','1D1AE-1D1EA','1D200-1D241','1D245','1D300-1D356',
  1186. '1D6C1','1D6DB','1D6FB','1D715','1D735','1D74F','1D76F','1D789','1D7A9','1D7C3',
  1187. '1D800-1D9FF','1DA37-1DA3A','1DA6D-1DA74','1DA76-1DA83','1DA85-1DA8B','1E14F','1E2FF',
  1188. '1E5FF','1E95E-1E95F','1ECAC','1ECB0','1ED2E','1EEF0-1EEF1','1F000-1F02B','1F030-1F093',
  1189. '1F0A0-1F0AE','1F0B1-1F0BF','1F0C1-1F0CF','1F0D1-1F0F5','1F10D-1F1AD','1F1E6-1F202',
  1190. '1F210-1F23B','1F240-1F248','1F250-1F251','1F260-1F265','1F300-1F6D7','1F6DC-1F6EC',
  1191. '1F6F0-1F6FC','1F700-1F776','1F77B-1F7D9','1F7E0-1F7EB','1F7F0','1F800-1F80B','1F810-1F847',
  1192. '1F850-1F859','1F860-1F887','1F890-1F8AD','1F8B0-1F8BB','1F8C0-1F8C1','1F900-1FA53',
  1193. '1FA60-1FA6D','1FA70-1FA7C','1FA80-1FA89','1FA8F-1FAC6','1FACE-1FADC','1FADF-1FAE9',
  1194. '1FAF0-1FAF8','1FB00-1FB92','1FB94-1FBEF',
  1195. ];
  1196. function mdIsUnicodePunct(cp) {
  1197. var lo = 0, hi = MD_UNICODE_PUNCT_RANGES.length - 1;
  1198. while (lo <= hi) {
  1199. var mid = (lo + hi) >> 1;
  1200. var dash = MD_UNICODE_PUNCT_RANGES[mid].indexOf('-');
  1201. var a, b;
  1202. if (dash < 0) { a = b = parseInt(MD_UNICODE_PUNCT_RANGES[mid], 16); }
  1203. else {
  1204. a = parseInt(MD_UNICODE_PUNCT_RANGES[mid].slice(0, dash), 16);
  1205. b = parseInt(MD_UNICODE_PUNCT_RANGES[mid].slice(dash + 1), 16);
  1206. }
  1207. if (cp < a) hi = mid - 1;
  1208. else if (cp > b) lo = mid + 1;
  1209. else return true;
  1210. }
  1211. return false;
  1212. }
  1213. function mdIsPunct(ch) {
  1214. if (ch === '' || ch == null) return false;
  1215. if (MD_ASCII_PUNCT_TEST_RE.test(ch)) return true;
  1216. var cp = ch.charCodeAt(0);
  1217. if (cp < 0xA1) return false;
  1218. // combine a surrogate pair into one code point
  1219. if (cp >= 0xD800 && cp <= 0xDBFF && ch.length > 1) {
  1220. var lo = ch.charCodeAt(1);
  1221. if (lo >= 0xDC00 && lo <= 0xDFFF) cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
  1222. }
  1223. return mdIsUnicodePunct(cp);
  1224. }
  1225. /**
  1226. * String.fromCharCode with surrogate-pair support.
  1227. * @param {number} cp
  1228. * @returns {string}
  1229. */
  1230. function mdFromCodePoint(cp) {
  1231. if (cp == null || cp < 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) return '\uFFFD';
  1232. if (cp <= 0xFFFF) return String.fromCharCode(cp);
  1233. var c = cp - 0x10000;
  1234. return String.fromCharCode(0xD800 + (c >> 10), 0xDC00 + (c & 0x3FF));
  1235. }
  1236. var mdEntityMap = null;
  1237. /** Parse MD_ENTITIES_PACKED into a name -> string map (once). */
  1238. function mdGetEntityMap() {
  1239. if (mdEntityMap) return mdEntityMap;
  1240. var map = {}, recs = MD_ENTITIES_PACKED.split('\n');
  1241. for (var i = 0; i < recs.length; i++) {
  1242. var sp = recs[i].indexOf(' ');
  1243. if (sp < 0) continue;
  1244. var cps = recs[i].slice(sp + 1).split(',');
  1245. var s = '';
  1246. for (var j = 0; j < cps.length; j++) s += mdFromCodePoint(parseInt(cps[j], 10));
  1247. map[recs[i].slice(0, sp)] = s;
  1248. }
  1249. mdEntityMap = map;
  1250. return map;
  1251. }
  1252. /**
  1253. * Resolve an entity reference at the start of `s`; null when invalid.
  1254. * @param {string} s
  1255. * @returns {?string}
  1256. */
  1257. function mdReplaceEntity(s) {
  1258. var m = s.match(MD_ENTITY_HERE_RE);
  1259. if (!m) return null;
  1260. var body = m[0].slice(1, -1);
  1261. if (body.charAt(0) === '#') {
  1262. var num = body.charAt(1) === 'x' || body.charAt(1) === 'X'
  1263. ? parseInt(body.slice(2), 16)
  1264. : parseInt(body.slice(1), 10);
  1265. if (isNaN(num) || num === 0 || num > 0x10FFFF) return '\uFFFD';
  1266. return mdFromCodePoint(num);
  1267. }
  1268. var map = mdGetEntityMap();
  1269. return Object.prototype.hasOwnProperty.call(map, body) ? map[body] : null;
  1270. }
  1271. /**
  1272. * Replace backslash escapes and entity references (spec 2.2/2.3). Used on
  1273. * link destinations, titles, labels and code info strings.
  1274. * @param {string} s
  1275. * @returns {string}
  1276. */
  1277. function mdUnescapeString(s) {
  1278. if (s.indexOf('\\') < 0 && s.indexOf('&') < 0) return s;
  1279. var out = '', i = 0, ch, rep, m;
  1280. while (i < s.length) {
  1281. ch = s.charAt(i);
  1282. if (ch === '\\' && MD_ESCAPABLE.indexOf(s.charAt(i + 1)) >= 0) {
  1283. out += s.charAt(i + 1);
  1284. i += 2;
  1285. continue;
  1286. }
  1287. if (ch === '&') {
  1288. // entity references are at most 34 characters long (spec 2.3), so a
  1289. // bounded window is enough and keeps this loop linear in s.length
  1290. rep = mdReplaceEntity(s.slice(i, i + 34));
  1291. if (rep !== null) {
  1292. m = s.slice(i, i + 34).match(MD_ENTITY_HERE_RE);
  1293. out += rep;
  1294. i += m[0].length;
  1295. continue;
  1296. }
  1297. }
  1298. out += ch;
  1299. i++;
  1300. }
  1301. return out;
  1302. }
  1303. // --- inline nodes -----------------------------------------------------------
  1304. /**
  1305. * Create an inline node. Types: text, softbreak, code, emph, strong,
  1306. * link, image, html (escaped text).
  1307. */
  1308. function mdInlineNode(type, literal) {
  1309. return { type: type, literal: literal == null ? '' : literal,
  1310. parent: null, next: null, prev: null,
  1311. firstChild: null, lastChild: null,
  1312. destination: null, title: null, hardBreak: false };
  1313. }
  1314. function mdAppendChild(parent, node) {
  1315. node.parent = parent;
  1316. node.prev = parent.lastChild;
  1317. if (parent.lastChild) parent.lastChild.next = node;
  1318. else parent.firstChild = node;
  1319. parent.lastChild = node;
  1320. return node;
  1321. }
  1322. function mdUnlink(node) {
  1323. if (node.prev) node.prev.next = node.next;
  1324. else if (node.parent) node.parent.firstChild = node.next;
  1325. if (node.next) node.next.prev = node.prev;
  1326. else if (node.parent) node.parent.lastChild = node.prev;
  1327. node.parent = null;
  1328. node.next = null;
  1329. node.prev = null;
  1330. }
  1331. function mdInsertAfter(node, sibling) {
  1332. sibling.parent = node.parent;
  1333. sibling.next = node.next;
  1334. sibling.prev = node;
  1335. if (node.next) node.next.prev = sibling;
  1336. else if (node.parent) node.parent.lastChild = sibling;
  1337. node.next = sibling;
  1338. }
  1339. /** Collect a node's children into an array (for rendering). */
  1340. function mdChildren(node) {
  1341. var out = [], c = node.firstChild;
  1342. while (c) { out.push(c); c = c.next; }
  1343. return out;
  1344. }
  1345. // --- the subject scanner ----------------------------------------------------
  1346. /**
  1347. * Parse the inline content of one leaf block.
  1348. * @param {string} subject already-trimmed paragraph/heading text
  1349. * @param {Object} refmap normalised-label -> { destination, title }
  1350. * @returns {Object} a synthetic parent whose children are the inlines
  1351. */
  1352. function mdParseInlines(subject, refmap) {
  1353. var block = { parent: null, next: null, prev: null,
  1354. firstChild: null, lastChild: null, type: 'root' };
  1355. var pos = 0;
  1356. var delimiters = null; // linked list, newest first
  1357. var brackets = null; // linked list, newest first
  1358. function text(s) { return mdAppendChild(block, mdInlineNode('text', s)); }
  1359. function peek() { return pos < subject.length ? subject.charAt(pos) : ''; }
  1360. function match(re) {
  1361. var m = re.exec(subject.slice(pos));
  1362. if (m) pos += m[0].length;
  1363. return m;
  1364. }
  1365. function spnl() {
  1366. match(/^ *(?:\n *)?/);
  1367. return true;
  1368. }
  1369. // -- emphasis delimiter bookkeeping --
  1370. function scanDelims(cc) {
  1371. var numdelims = 0, startpos = pos;
  1372. while (peek() === cc) { numdelims++; pos++; }
  1373. // adjacent characters, taking surrogate pairs as one character
  1374. var charBefore = startpos === 0 ? '\n'
  1375. : (mdIsHighSurrogate(subject.charAt(startpos - 1))
  1376. ? subject.slice(startpos - 2, startpos)
  1377. : subject.charAt(startpos - 1));
  1378. var nextCh = peek();
  1379. var charAfter = nextCh === '' ? '\n'
  1380. : (mdIsHighSurrogate(nextCh) ? subject.substr(pos, 2) : nextCh);
  1381. var afterWs = /^\s/.test(charAfter);
  1382. var beforeWs = /^\s/.test(charBefore);
  1383. var afterPunct = mdIsPunct(charAfter);
  1384. var beforePunct = mdIsPunct(charBefore);
  1385. var leftFlanking = !afterWs && (!afterPunct || beforeWs || beforePunct);
  1386. var rightFlanking = !beforeWs && (!beforePunct || afterWs || afterPunct);
  1387. var canOpen, canClose;
  1388. if (cc === '_') {
  1389. canOpen = leftFlanking && (!rightFlanking || beforePunct);
  1390. canClose = rightFlanking && (!leftFlanking || afterPunct);
  1391. } else {
  1392. canOpen = leftFlanking;
  1393. canClose = rightFlanking;
  1394. }
  1395. pos = startpos;
  1396. return { numdelims: numdelims, canOpen: canOpen, canClose: canClose };
  1397. }
  1398. function handleDelim(cc) {
  1399. var res = scanDelims(cc);
  1400. if (!res || res.numdelims === 0) return false;
  1401. var node = text(subject.slice(pos, pos + res.numdelims));
  1402. pos += res.numdelims;
  1403. if (res.canOpen || res.canClose) {
  1404. var d = { cc: cc, numdelims: res.numdelims, origdelims: res.numdelims,
  1405. node: node, previous: delimiters, next: null,
  1406. canOpen: res.canOpen, canClose: res.canClose };
  1407. if (delimiters) delimiters.next = d;
  1408. delimiters = d;
  1409. }
  1410. return true;
  1411. }
  1412. function removeDelimiter(d) {
  1413. if (d.previous) d.previous.next = d.next;
  1414. if (d.next === null) delimiters = d.previous;
  1415. else d.next.previous = d.previous;
  1416. }
  1417. function removeDelimitersBetween(bottom, top) {
  1418. if (bottom.next !== top) { bottom.next = top; top.previous = bottom; }
  1419. }
  1420. /** True for the high half of a UTF-16 surrogate pair. */
  1421. function mdIsHighSurrogate(ch) {
  1422. var c = ch.charCodeAt(0);
  1423. return c >= 0xD800 && c <= 0xDBFF;
  1424. }
  1425. /** Emphasis resolution over the delimiter stack (spec 6.2). */
  1426. function processEmphasis(stackBottom) {
  1427. var openersBottom = new Array(8);
  1428. for (var i = 0; i < 8; i++) openersBottom[i] = stackBottom;
  1429. var closer = delimiters;
  1430. while (closer !== null && closer.previous !== stackBottom) closer = closer.previous;
  1431. var opener, openerInl, closerInl, useDelims, tmp, next, openerFound, oddMatch;
  1432. while (closer !== null) {
  1433. if (!closer.canClose) { closer = closer.next; continue; }
  1434. opener = closer.previous;
  1435. openerFound = false;
  1436. // openers_bottom index: 0..3 for '_', 4..7 for '*' — see rule of 3
  1437. var idx = (closer.cc === '_' ? 0 : 4) + (closer.canOpen ? 2 : 0) + (closer.origdelims % 3 === 0 ? 0 : 1);
  1438. while (opener !== null && opener !== stackBottom && opener !== openersBottom[idx]) {
  1439. oddMatch = (closer.canOpen || opener.canClose) &&
  1440. closer.origdelims % 3 !== 0 &&
  1441. (opener.origdelims + closer.origdelims) % 3 === 0;
  1442. if (opener.cc === closer.cc && opener.canOpen && !oddMatch) { openerFound = true; break; }
  1443. opener = opener.previous;
  1444. }
  1445. var oldCloser = closer;
  1446. if (!openerFound) {
  1447. openersBottom[idx] = oldCloser.previous;
  1448. if (!oldCloser.canOpen) removeDelimiter(oldCloser);
  1449. closer = closer.next;
  1450. continue;
  1451. }
  1452. useDelims = closer.numdelims >= 2 && opener.numdelims >= 2 ? 2 : 1;
  1453. openerInl = opener.node;
  1454. closerInl = closer.node;
  1455. opener.numdelims -= useDelims;
  1456. closer.numdelims -= useDelims;
  1457. openerInl.literal = openerInl.literal.slice(0, openerInl.literal.length - useDelims);
  1458. closerInl.literal = closerInl.literal.slice(0, closerInl.literal.length - useDelims);
  1459. var emph = mdInlineNode(useDelims === 1 ? 'emph' : 'strong');
  1460. tmp = openerInl.next;
  1461. while (tmp && tmp !== closerInl) {
  1462. next = tmp.next;
  1463. mdUnlink(tmp);
  1464. mdAppendChild(emph, tmp);
  1465. tmp = next;
  1466. }
  1467. mdInsertAfter(openerInl, emph);
  1468. removeDelimitersBetween(opener, closer);
  1469. if (opener.numdelims === 0) { mdUnlink(openerInl); removeDelimiter(opener); }
  1470. if (closer.numdelims === 0) {
  1471. mdUnlink(closerInl);
  1472. var after = closer.next;
  1473. removeDelimiter(closer);
  1474. closer = after;
  1475. }
  1476. // when the closer still has delimiters left, stay on it: the next
  1477. // iteration searches for another opener further left
  1478. }
  1479. while (delimiters !== null && delimiters !== stackBottom) removeDelimiter(delimiters);
  1480. }
  1481. // -- link / image machinery --
  1482. /**
  1483. * Parse a link title at pos; returns the unescaped title or null.
  1484. * Uses the linear scanner (no regex backtracking).
  1485. */
  1486. function parseLinkTitle() {
  1487. var res = mdScanLinkTitle(subject, pos);
  1488. if (!res) return null;
  1489. pos += res.len;
  1490. return mdUnescapeString(res.text);
  1491. }
  1492. /** Parse `<dest>` or a bare destination; returns normalised URI or null. */
  1493. function parseLinkDestination() {
  1494. var m = match(MD_LINK_DEST_BRACES_RE);
  1495. if (m) return mdNormalizeUri(mdUnescapeString(m[0].slice(1, -1)));
  1496. if (peek() === '<') return null;
  1497. var savepos = pos, openparens = 0, c;
  1498. while ((c = peek()) !== '') {
  1499. if (c === '\\' && subject.charAt(pos + 1) !== '' &&
  1500. MD_ESCAPABLE.indexOf(subject.charAt(pos + 1)) >= 0) {
  1501. pos += 1;
  1502. if (peek() !== '') pos += 1;
  1503. } else if (c === '(') { pos++; openparens++; }
  1504. else if (c === ')') { if (openparens < 1) break; pos++; openparens--; }
  1505. else if (MD_WS_CHAR_RE.test(c)) break;
  1506. else pos++;
  1507. }
  1508. if (pos === savepos && c !== ')') return null;
  1509. if (openparens !== 0) { pos = savepos; return null; }
  1510. return mdNormalizeUri(mdUnescapeString(subject.slice(savepos, pos)));
  1511. }
  1512. /**
  1513. * Parse `[...]` at pos; returns the consumed length (including both
  1514. * brackets), or 0 when there is no well-formed label. A label may not
  1515. * contain a blank line and is capped at 1000 characters.
  1516. */
  1517. function parseLinkLabel() {
  1518. if (subject.charAt(pos) !== '[') return 0;
  1519. var i = pos + 1, ch;
  1520. while (i < subject.length) {
  1521. ch = subject.charAt(i);
  1522. if (ch === '\\') { i += 2; continue; }
  1523. if (ch === '[') return 0; // nested brackets are not labels
  1524. if (ch === ']') break;
  1525. i++;
  1526. }
  1527. if (subject.charAt(i) !== ']') return 0;
  1528. var len = i + 1 - pos;
  1529. var label = subject.slice(pos, i + 1);
  1530. if (len > 1001) return 0;
  1531. if (/\n[ \t]*\n/.test(label)) return 0; // no blank lines inside
  1532. return len;
  1533. }
  1534. function addBracket(node, index, image) {
  1535. if (brackets) brackets.bracketAfter = true;
  1536. brackets = { node: node, previous: brackets, previousDelimiter: delimiters,
  1537. index: index, image: image, active: true, bracketAfter: false };
  1538. }
  1539. function removeBracket() { brackets = brackets.previous; }
  1540. function parseCloseBracket() {
  1541. var startpos = pos, isImage, dest, title, matched = false, reflabel;
  1542. pos += 1;
  1543. var opener = brackets;
  1544. if (opener === null) { text(']'); return true; }
  1545. if (!opener.active) { text(']'); removeBracket(); return true; }
  1546. isImage = opener.image;
  1547. var savepos = pos;
  1548. if (peek() === '(') {
  1549. pos++;
  1550. if (spnl() && (dest = parseLinkDestination()) !== null) {
  1551. var beforeTitle = pos;
  1552. spnl();
  1553. // A title is only allowed when whitespace separated it from the
  1554. // destination (spec: "optional... preceded by a space").
  1555. if (pos !== beforeTitle) {
  1556. var tryTitle = parseLinkTitle();
  1557. if (tryTitle !== null) {
  1558. title = tryTitle;
  1559. spnl();
  1560. } else {
  1561. pos = beforeTitle;
  1562. }
  1563. }
  1564. if (peek() === ')') {
  1565. pos += 1;
  1566. matched = true;
  1567. } else {
  1568. pos = savepos;
  1569. }
  1570. } else {
  1571. pos = savepos;
  1572. }
  1573. }
  1574. if (!matched) {
  1575. var beforelabel = pos;
  1576. var n = parseLinkLabel();
  1577. if (n > 2) {
  1578. // full reference: [text][label]
  1579. reflabel = subject.slice(beforelabel, beforelabel + n);
  1580. pos = beforelabel + n;
  1581. } else if (n === 2 && !opener.bracketAfter) {
  1582. // collapsed reference: [text][] — consume the empty label
  1583. reflabel = '[' + subject.slice(opener.index, startpos) + ']';
  1584. pos = beforelabel + n;
  1585. } else if (!opener.bracketAfter) {
  1586. // shortcut reference: [text]
  1587. reflabel = '[' + subject.slice(opener.index, startpos) + ']';
  1588. }
  1589. if (n === 0) pos = savepos;
  1590. if (reflabel) {
  1591. var link = refmap[mdNormalizeReference(reflabel)];
  1592. if (link) { dest = link.destination; title = link.title; matched = true; }
  1593. }
  1594. }
  1595. if (matched) {
  1596. var node = mdInlineNode(isImage ? 'image' : 'link');
  1597. node.destination = dest == null ? '' : dest;
  1598. node.title = title == null ? '' : title;
  1599. var tmp = opener.node.next, next;
  1600. while (tmp) {
  1601. next = tmp.next;
  1602. mdUnlink(tmp);
  1603. mdAppendChild(node, tmp);
  1604. tmp = next;
  1605. }
  1606. // the link takes the opener's position in the parent's child list
  1607. mdInsertAfter(opener.node, node);
  1608. processEmphasis(opener.previousDelimiter);
  1609. removeBracket();
  1610. mdUnlink(opener.node);
  1611. if (!isImage) {
  1612. var b = brackets;
  1613. while (b !== null) { if (!b.image) b.active = false; b = b.previous; }
  1614. }
  1615. return true;
  1616. }
  1617. removeBracket();
  1618. // NB: `startpos` was captured before consuming ']', so pos now sits
  1619. // just after it — do not rewind onto the bracket again.
  1620. pos = startpos + 1;
  1621. text(']');
  1622. return true;
  1623. }
  1624. // -- autolinks and raw HTML (neutralised) --
  1625. var MD_EMAIL_AUTOLINK_RE = /^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/;
  1626. var MD_AUTOLINK_RE = /^<[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*>/i;
  1627. /**
  1628. * Try an autolink at pos. Returns the node or null.
  1629. */
  1630. function parseAutolink() {
  1631. // Autolinks cannot contain whitespace or '<'/'>' (MD_AUTOLINK_RE), so
  1632. // slicing to the next such character bounds the scan without changing
  1633. // what can match. Without this bound the slice+match was quadratic in
  1634. // pathological input (thousands of unmatched '<').
  1635. var rest = subject.slice(pos, mdBoundScan(subject, pos));
  1636. var m = rest.match(MD_AUTOLINK_RE);
  1637. var node;
  1638. if (m) {
  1639. node = mdInlineNode('link');
  1640. node.destination = mdNormalizeUri(m[0].slice(1, -1));
  1641. node.autolinkText = m[0].slice(1, -1);
  1642. mdAppendChild(block, node);
  1643. mdAppendChild(node, mdInlineNode('text', m[0].slice(1, -1)));
  1644. pos += m[0].length;
  1645. return node;
  1646. }
  1647. m = rest.match(MD_EMAIL_AUTOLINK_RE);
  1648. if (m) {
  1649. node = mdInlineNode('link');
  1650. node.destination = 'mailto:' + m[1];
  1651. node.autolinkText = m[1];
  1652. mdAppendChild(block, node);
  1653. mdAppendChild(node, mdInlineNode('text', m[1]));
  1654. pos += m[0].length;
  1655. return node;
  1656. }
  1657. return null;
  1658. }
  1659. /**
  1660. * Match a raw HTML tag at pos. SECURITY: the matched text is returned so
  1661. * the caller can render it escaped — it is never emitted as markup.
  1662. */
  1663. function parseHtmlTag() {
  1664. var raw = mdScanHtmlTag(subject, pos);
  1665. if (!raw) return null;
  1666. var node = mdAppendChild(block, mdInlineNode('html'));
  1667. node.literal = raw;
  1668. pos += raw.length;
  1669. return node;
  1670. }
  1671. // -- the main dispatch loop --
  1672. while (pos < subject.length) {
  1673. var c = peek();
  1674. var res = false;
  1675. switch (c) {
  1676. case '\n':
  1677. pos++;
  1678. {
  1679. var lastc = block.lastChild;
  1680. if (lastc && lastc.type === 'text' && / $/.test(lastc.literal)) {
  1681. var hard = / {2}$/.test(lastc.literal);
  1682. lastc.literal = lastc.literal.replace(MD_FINAL_SPACE_RE, '');
  1683. var sb = mdAppendChild(block, mdInlineNode('softbreak'));
  1684. sb.hardBreak = hard;
  1685. } else {
  1686. mdAppendChild(block, mdInlineNode('softbreak'));
  1687. }
  1688. match(/^ */);
  1689. }
  1690. break;
  1691. case '\\':
  1692. if (subject.charAt(pos + 1) === '\n') {
  1693. pos += 2;
  1694. var hb = mdAppendChild(block, mdInlineNode('softbreak'));
  1695. hb.hardBreak = true;
  1696. match(/^ */);
  1697. } else if (subject.charAt(pos + 1) !== '' &&
  1698. MD_ESCAPABLE.indexOf(subject.charAt(pos + 1)) >= 0) {
  1699. text(subject.charAt(pos + 1));
  1700. pos += 2;
  1701. } else {
  1702. text('\\');
  1703. pos++;
  1704. }
  1705. break;
  1706. case '`':
  1707. {
  1708. // opening run, then the next run of backticks of the SAME length
  1709. var ticks = subject.slice(pos).match(MD_TICKS_HERE_RE)[0];
  1710. var afterOpen = pos + ticks.length;
  1711. var searchPos = afterOpen, run;
  1712. var codeNode = null;
  1713. while ((run = subject.slice(searchPos).match(/^[\s\S]*?(`+)/)) && run[1]) {
  1714. var runStart = searchPos + run[0].length - run[1].length;
  1715. if (run[1].length === ticks.length) {
  1716. // newline -> space; spaces *before* a newline are dropped
  1717. // (spec: "line endings are replaced by spaces... preceded
  1718. // by a space are removed")
  1719. var content = subject.slice(afterOpen, runStart)
  1720. .replace(/ *\n/g, '\n').replace(/\n/g, ' ');
  1721. if (/^ /.test(content) && / $/.test(content) && content.replace(/ /g, '') !== '') {
  1722. content = content.slice(1, content.length - 1);
  1723. }
  1724. codeNode = mdAppendChild(block, mdInlineNode('code', content));
  1725. pos = runStart + run[1].length;
  1726. break;
  1727. }
  1728. searchPos = runStart + run[1].length;
  1729. }
  1730. if (!codeNode) {
  1731. text(ticks);
  1732. pos = afterOpen;
  1733. }
  1734. }
  1735. break;
  1736. case '*':
  1737. case '_':
  1738. handleDelim(c);
  1739. break;
  1740. case '[':
  1741. {
  1742. var node = text('[');
  1743. addBracket(node, pos + 1, false);
  1744. pos++;
  1745. }
  1746. break;
  1747. case '!':
  1748. if (subject.charAt(pos + 1) === '[') {
  1749. var n2 = text('![');
  1750. addBracket(n2, pos + 2, true);
  1751. pos += 2;
  1752. } else {
  1753. text('!');
  1754. pos++;
  1755. }
  1756. break;
  1757. case ']':
  1758. parseCloseBracket();
  1759. break;
  1760. case '<':
  1761. if (parseAutolink()) break;
  1762. if (parseHtmlTag()) break;
  1763. text('<');
  1764. pos++;
  1765. break;
  1766. case '&':
  1767. {
  1768. var rep = mdReplaceEntity(subject.slice(pos, pos + 34));
  1769. if (rep !== null) {
  1770. text(rep);
  1771. pos += subject.slice(pos, pos + 34).match(MD_ENTITY_HERE_RE)[0].length;
  1772. } else {
  1773. text('&');
  1774. pos++;
  1775. }
  1776. }
  1777. break;
  1778. default:
  1779. {
  1780. var m = subject.slice(pos).match(/^[^\n`\\[\]!<&*_]+/);
  1781. if (!m) { text(c); pos++; }
  1782. else { text(m[0]); pos += m[0].length; }
  1783. }
  1784. }
  1785. }
  1786. processEmphasis(null);
  1787. return block;
  1788. }
  1789. // ---------------------------------------------------------------------------
  1790. // Markdown HTML rendering
  1791. // ---------------------------------------------------------------------------
  1792. /**
  1793. * Escape the five HTML-significant characters. `"` becomes `&quot;` (also
  1794. * safe inside double-quoted attributes), matching cmark.
  1795. * @param {string} s
  1796. * @returns {string}
  1797. */
  1798. function mdEscape(s) {
  1799. return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
  1800. .replace(/"/g, '&quot;');
  1801. }
  1802. /**
  1803. * Parse (once) and render a leaf block's inline content. The parsed inline
  1804. * tree is cached on the block so image alt text can reuse it.
  1805. */
  1806. function mdLeafInlines(node, refmap) {
  1807. if (!node._inlines) {
  1808. node._inlines = mdParseInlines(node.strings.join('\n').trim(), refmap);
  1809. }
  1810. return node._inlines;
  1811. }
  1812. /** Render inline nodes to HTML (children of a paragraph/heading). */
  1813. function mdRenderInlines(node) {
  1814. var out = '', c = node.firstChild;
  1815. while (c) {
  1816. switch (c.type) {
  1817. case 'text':
  1818. out += mdEscape(c.literal);
  1819. break;
  1820. case 'softbreak':
  1821. out += c.hardBreak ? '<br />\n' : '\n';
  1822. break;
  1823. case 'code':
  1824. out += '<code>' + mdEscape(c.literal) + '</code>';
  1825. break;
  1826. case 'emph':
  1827. out += '<em>' + mdRenderInlines(c) + '</em>';
  1828. break;
  1829. case 'strong':
  1830. out += '<strong>' + mdRenderInlines(c) + '</strong>';
  1831. break;
  1832. case 'link':
  1833. out += '<a href="' + safeMarkdownUrl(mdEscapeAttr(c.destination)) + '"' +
  1834. (c.title ? ' title="' + mdEscapeAttr(c.title) + '"' : '') + '>' +
  1835. mdRenderInlines(c) + '</a>';
  1836. break;
  1837. case 'image':
  1838. out += '<img src="' + safeMarkdownUrl(mdEscapeAttr(c.destination)) + '"' +
  1839. ' alt="' + mdImageAlt(c) + '"' +
  1840. (c.title ? ' title="' + mdEscapeAttr(c.title) + '"' : '') + ' />';
  1841. break;
  1842. case 'html':
  1843. out += mdEscape(c.literal);
  1844. break;
  1845. default:
  1846. out += mdEscape(c.literal || '');
  1847. }
  1848. c = c.next;
  1849. }
  1850. return out;
  1851. }
  1852. /** Plain-text rendering of image alt text (markdown stripped). */
  1853. function mdImageAlt(node) {
  1854. var out = '', c = node.firstChild;
  1855. while (c) {
  1856. if (c.type === 'text' || c.type === 'code' || c.type === 'html') out += c.literal;
  1857. else if (c.type === 'softbreak') out += c.hardBreak ? '\n' : '\n';
  1858. else if (c.firstChild) out += mdImageAlt(c);
  1859. c = c.next;
  1860. }
  1861. return mdEscapeAttr(out);
  1862. }
  1863. /** Escape for a double-quoted attribute value. */
  1864. function mdEscapeAttr(s) {
  1865. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;')
  1866. .replace(/</g, '&lt;').replace(/>/g, '&gt;');
  1867. }
  1868. /**
  1869. * Output buffer that suppresses repeated newlines (cmark's `cr`).
  1870. */
  1871. function mdOut() {
  1872. // `last` starts as a newline so the very first cr() is a no-op
  1873. return { s: '', last: '\n' };
  1874. }
  1875. /** Append a literal string. */
  1876. function mdLit(out, s) {
  1877. if (!s) return;
  1878. out.s += s;
  1879. out.last = s.charAt(s.length - 1);
  1880. }
  1881. /** Append a newline unless the output already ends with one. */
  1882. function mdCr(out) {
  1883. if (out.last !== '\n') mdLit(out, '\n');
  1884. }
  1885. /**
  1886. * Render one block node (and its children) to HTML. `tight` is the
  1887. * enclosing list's tightness: tight lists suppress `<p>` wrappers.
  1888. */
  1889. function mdRenderBlocks(node, tight, out, refmap) {
  1890. var i, child;
  1891. switch (node.type) {
  1892. case 'document':
  1893. for (i = 0; i < node.children.length; i++) mdRenderBlocks(node.children[i], tight, out, refmap);
  1894. break;
  1895. case 'paragraph':
  1896. // in a tight list the paragraph renders bare
  1897. if (tight) { mdLit(out, mdRenderInlines(mdLeafInlines(node, refmap))); }
  1898. else {
  1899. mdCr(out);
  1900. mdLit(out, '<p>');
  1901. mdLit(out, mdRenderInlines(mdLeafInlines(node, refmap)));
  1902. mdLit(out, '</p>');
  1903. mdCr(out);
  1904. }
  1905. break;
  1906. case 'heading':
  1907. mdCr(out);
  1908. mdLit(out, '<h' + node.level + '>');
  1909. mdLit(out, mdRenderInlines(mdLeafInlines(node, refmap)));
  1910. mdLit(out, '</h' + node.level + '>');
  1911. mdCr(out);
  1912. break;
  1913. case 'thematic':
  1914. mdCr(out);
  1915. mdLit(out, '<hr />');
  1916. mdCr(out);
  1917. break;
  1918. case 'code':
  1919. mdCr(out);
  1920. var info = node.info ? node.info.split(/\s+/)[0] : '';
  1921. var attrs = '';
  1922. if (info) attrs = ' class="language-' + mdEscapeAttr(info) + '"';
  1923. mdLit(out, '<pre><code' + attrs + '>' + mdEscape(node.literal) + '</code></pre>');
  1924. mdCr(out);
  1925. break;
  1926. case 'blockquote':
  1927. mdCr(out);
  1928. mdLit(out, '<blockquote>');
  1929. mdCr(out);
  1930. // cmark unwraps paragraphs only when their grandparent is a tight
  1931. // list; inside a blockquote they always keep their <p>.
  1932. for (i = 0; i < node.children.length; i++) mdRenderBlocks(node.children[i], false, out, refmap);
  1933. mdCr(out);
  1934. mdLit(out, '</blockquote>');
  1935. mdCr(out);
  1936. break;
  1937. case 'list':
  1938. mdCr(out);
  1939. var tag = node.listData.type === 'ordered' ? 'ol' : 'ul';
  1940. var start = '';
  1941. if (tag === 'ol' && node.listData.start != null && node.listData.start !== 1) {
  1942. start = ' start="' + node.listData.start + '"';
  1943. }
  1944. mdLit(out, '<' + tag + start + '>');
  1945. mdCr(out);
  1946. for (i = 0; i < node.children.length; i++) mdRenderBlocks(node.children[i], node.tight, out, refmap);
  1947. mdCr(out);
  1948. mdLit(out, '</' + tag + '>');
  1949. mdCr(out);
  1950. break;
  1951. case 'item':
  1952. mdLit(out, '<li>');
  1953. for (i = 0; i < node.children.length; i++) {
  1954. // tightness applies to the item's own paragraphs and lists;
  1955. // blockquote contents are always loose.
  1956. mdRenderBlocks(node.children[i], node.children[i].type === 'blockquote' ? false : tight, out, refmap);
  1957. }
  1958. mdLit(out, '</li>');
  1959. mdCr(out);
  1960. break;
  1961. default:
  1962. break;
  1963. }
  1964. }
  1965. /**
  1966. * Render markdown to safe HTML.
  1967. *
  1968. * CommonMark 0.31.2 minus raw HTML (escaped instead, see the note at the
  1969. * top of the markdown section) and minus HTML-block constructs that only
  1970. * exist to feed raw HTML through.
  1971. * @param {string} raw markdown source
  1972. * @returns {string} HTML safe for `innerHTML`
  1973. */
  1974. function renderMarkdown(raw) {
  1975. var parser = mdParseDocument(raw);
  1976. var out = mdOut();
  1977. mdRenderBlocks(parser.doc, false, out, parser.refmap);
  1978. return out.s;
  1979. }
  1980. /**
  1981. * Demote child header tags by N levels (h1 → h2, etc.), capping at h6.
  1982. */
  1983. function handleHDemotion(el) {
  1984. var attr = el.getAttribute('stm-h-demotion');
  1985. if (!attr) return;
  1986. var n = parseInt(attr, 10);
  1987. if (isNaN(n) || n <= 0) return;
  1988. el.querySelectorAll('h1,h2,h3,h4,h5,h6').forEach(function (h) {
  1989. var level = parseInt(h.tagName.charAt(1), 10);
  1990. var newLevel = Math.min(level + n, 6);
  1991. if (newLevel === level) return;
  1992. var replacement = document.createElement('h' + newLevel);
  1993. for (var i = 0; i < h.attributes.length; i++)
  1994. replacement.setAttribute(h.attributes[i].name, h.attributes[i].value);
  1995. while (h.firstChild) replacement.appendChild(h.firstChild);
  1996. h.replaceWith(replacement);
  1997. });
  1998. }
  1999. // ---------------------------------------------------------------------------
  2000. // Bindings (module seam) + programmatic API
  2001. // ---------------------------------------------------------------------------
  2002. /** Normalise a binding value to markdown source (`null`/`undefined` -> ''). */
  2003. function mdSource(value) {
  2004. return value === null || value === undefined ? '' : String(value);
  2005. }
  2006. /**
  2007. * Apply a markdown value to an element: the single code path shared by the
  2008. * `stm-markdown` handler and `statum.markdown.renderTo`. Per the "leave
  2009. * original DOM content" policy, an unresolved value (`undefined`) leaves
  2010. * the element untouched.
  2011. */
  2012. function applyMarkdown(el, value) {
  2013. if (value === undefined) return;
  2014. el.innerHTML = renderMarkdown(mdSource(value));
  2015. }
  2016. /** Bind `stm-markdown`: render the expression's value as markdown. */
  2017. function handleMarkdown(el, scope) {
  2018. if (el.hasAttribute('stm-markdown')) {
  2019. var md = evalExpr(el.getAttribute('stm-markdown'), scope);
  2020. applyMarkdown(el, md);
  2021. }
  2022. }
  2023. /**
  2024. * Bind `stm-h-demotion`: demote the element's headers. Registered after
  2025. * `stm-markdown` (and therefore also after `stm-html`) so the rendered
  2026. * headers are present in the DOM when it runs.
  2027. */
  2028. function handleDemotion(el) {
  2029. if (el.hasAttribute('stm-h-demotion')) handleHDemotion(el);
  2030. }
  2031. /**
  2032. * Programmatic markdown API, sharing the binding's code path.
  2033. */
  2034. window.statum.markdown = {
  2035. /** Render markdown source to safe HTML. @param {string} src */
  2036. render: function (src) { return renderMarkdown(mdSource(src)); },
  2037. /** Render markdown source into an element (replaces its content). */
  2038. renderTo: function (el, src) { applyMarkdown(el, src); }
  2039. };
  2040. // Ordering constraints: markdown renders before demotion so the headers it
  2041. // produces exist when demotion runs.
  2042. bridge.registerAttribute('stm-markdown', handleMarkdown, { after: 'stm-html' });
  2043. bridge.registerAttribute('stm-h-demotion', handleDemotion, { after: 'stm-markdown' });
  2044. // Test-only escape hatch: tests/markdown and tests/split load these module
  2045. // files under QuickJS with `window.__STATUM_TEST__` set beforehand and
  2046. // reach the engine through statum._testMarkdown. Shipped pages never set
  2047. // the flag, so this adds no surface to the public API.
  2048. if (window.__STATUM_TEST__) window.statum._testMarkdown = renderMarkdown;
  2049. })();