marked.umd.js 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684
  1. /**
  2. * marked v7.0.3 - a markdown parser
  3. * Copyright (c) 2011-2023, Christopher Jeffrey. (MIT Licensed)
  4. * https://github.com/markedjs/marked
  5. */
  6. /**
  7. * DO NOT EDIT THIS FILE
  8. * The code in this file is generated from files in ./src/
  9. */
  10. (function (global, factory) {
  11. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  12. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  13. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.marked = {}));
  14. })(this, (function (exports) { 'use strict';
  15. /**
  16. * Gets the original marked default options.
  17. */
  18. function _getDefaults() {
  19. return {
  20. async: false,
  21. baseUrl: null,
  22. breaks: false,
  23. extensions: null,
  24. gfm: true,
  25. headerIds: false,
  26. headerPrefix: '',
  27. highlight: null,
  28. hooks: null,
  29. langPrefix: 'language-',
  30. mangle: false,
  31. pedantic: false,
  32. renderer: null,
  33. sanitize: false,
  34. sanitizer: null,
  35. silent: false,
  36. smartypants: false,
  37. tokenizer: null,
  38. walkTokens: null,
  39. xhtml: false
  40. };
  41. }
  42. exports.defaults = _getDefaults();
  43. function changeDefaults(newDefaults) {
  44. exports.defaults = newDefaults;
  45. }
  46. /**
  47. * Helpers
  48. */
  49. const escapeTest = /[&<>"']/;
  50. const escapeReplace = new RegExp(escapeTest.source, 'g');
  51. const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
  52. const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');
  53. const escapeReplacements = {
  54. '&': '&amp;',
  55. '<': '&lt;',
  56. '>': '&gt;',
  57. '"': '&quot;',
  58. "'": '&#39;'
  59. };
  60. const getEscapeReplacement = (ch) => escapeReplacements[ch];
  61. function escape(html, encode) {
  62. if (encode) {
  63. if (escapeTest.test(html)) {
  64. return html.replace(escapeReplace, getEscapeReplacement);
  65. }
  66. }
  67. else {
  68. if (escapeTestNoEncode.test(html)) {
  69. return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
  70. }
  71. }
  72. return html;
  73. }
  74. const unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
  75. function unescape(html) {
  76. // explicitly match decimal, hex, and named HTML entities
  77. return html.replace(unescapeTest, (_, n) => {
  78. n = n.toLowerCase();
  79. if (n === 'colon')
  80. return ':';
  81. if (n.charAt(0) === '#') {
  82. return n.charAt(1) === 'x'
  83. ? String.fromCharCode(parseInt(n.substring(2), 16))
  84. : String.fromCharCode(+n.substring(1));
  85. }
  86. return '';
  87. });
  88. }
  89. const caret = /(^|[^\[])\^/g;
  90. function edit(regex, opt) {
  91. regex = typeof regex === 'string' ? regex : regex.source;
  92. opt = opt || '';
  93. const obj = {
  94. replace: (name, val) => {
  95. val = typeof val === 'object' && 'source' in val ? val.source : val;
  96. val = val.replace(caret, '$1');
  97. regex = regex.replace(name, val);
  98. return obj;
  99. },
  100. getRegex: () => {
  101. return new RegExp(regex, opt);
  102. }
  103. };
  104. return obj;
  105. }
  106. const nonWordAndColonTest = /[^\w:]/g;
  107. const originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
  108. function cleanUrl(sanitize, base, href) {
  109. if (sanitize) {
  110. let prot;
  111. try {
  112. prot = decodeURIComponent(unescape(href))
  113. .replace(nonWordAndColonTest, '')
  114. .toLowerCase();
  115. }
  116. catch (e) {
  117. return null;
  118. }
  119. if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
  120. return null;
  121. }
  122. }
  123. if (base && !originIndependentUrl.test(href)) {
  124. href = resolveUrl(base, href);
  125. }
  126. try {
  127. href = encodeURI(href).replace(/%25/g, '%');
  128. }
  129. catch (e) {
  130. return null;
  131. }
  132. return href;
  133. }
  134. const baseUrls = {};
  135. const justDomain = /^[^:]+:\/*[^/]*$/;
  136. const protocol = /^([^:]+:)[\s\S]*$/;
  137. const domain = /^([^:]+:\/*[^/]*)[\s\S]*$/;
  138. function resolveUrl(base, href) {
  139. if (!baseUrls[' ' + base]) {
  140. // we can ignore everything in base after the last slash of its path component,
  141. // but we might need to add _that_
  142. // https://tools.ietf.org/html/rfc3986#section-3
  143. if (justDomain.test(base)) {
  144. baseUrls[' ' + base] = base + '/';
  145. }
  146. else {
  147. baseUrls[' ' + base] = rtrim(base, '/', true);
  148. }
  149. }
  150. base = baseUrls[' ' + base];
  151. const relativeBase = base.indexOf(':') === -1;
  152. if (href.substring(0, 2) === '//') {
  153. if (relativeBase) {
  154. return href;
  155. }
  156. return base.replace(protocol, '$1') + href;
  157. }
  158. else if (href.charAt(0) === '/') {
  159. if (relativeBase) {
  160. return href;
  161. }
  162. return base.replace(domain, '$1') + href;
  163. }
  164. else {
  165. return base + href;
  166. }
  167. }
  168. const noopTest = { exec: () => null };
  169. function splitCells(tableRow, count) {
  170. // ensure that every cell-delimiting pipe has a space
  171. // before it to distinguish it from an escaped pipe
  172. const row = tableRow.replace(/\|/g, (match, offset, str) => {
  173. let escaped = false;
  174. let curr = offset;
  175. while (--curr >= 0 && str[curr] === '\\')
  176. escaped = !escaped;
  177. if (escaped) {
  178. // odd number of slashes means | is escaped
  179. // so we leave it alone
  180. return '|';
  181. }
  182. else {
  183. // add space before unescaped |
  184. return ' |';
  185. }
  186. }), cells = row.split(/ \|/);
  187. let i = 0;
  188. // First/last cell in a row cannot be empty if it has no leading/trailing pipe
  189. if (!cells[0].trim()) {
  190. cells.shift();
  191. }
  192. if (cells.length > 0 && !cells[cells.length - 1].trim()) {
  193. cells.pop();
  194. }
  195. if (count) {
  196. if (cells.length > count) {
  197. cells.splice(count);
  198. }
  199. else {
  200. while (cells.length < count)
  201. cells.push('');
  202. }
  203. }
  204. for (; i < cells.length; i++) {
  205. // leading or trailing whitespace is ignored per the gfm spec
  206. cells[i] = cells[i].trim().replace(/\\\|/g, '|');
  207. }
  208. return cells;
  209. }
  210. /**
  211. * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
  212. * /c*$/ is vulnerable to REDOS.
  213. *
  214. * @param str
  215. * @param c
  216. * @param invert Remove suffix of non-c chars instead. Default falsey.
  217. */
  218. function rtrim(str, c, invert) {
  219. const l = str.length;
  220. if (l === 0) {
  221. return '';
  222. }
  223. // Length of suffix matching the invert condition.
  224. let suffLen = 0;
  225. // Step left until we fail to match the invert condition.
  226. while (suffLen < l) {
  227. const currChar = str.charAt(l - suffLen - 1);
  228. if (currChar === c && !invert) {
  229. suffLen++;
  230. }
  231. else if (currChar !== c && invert) {
  232. suffLen++;
  233. }
  234. else {
  235. break;
  236. }
  237. }
  238. return str.slice(0, l - suffLen);
  239. }
  240. function findClosingBracket(str, b) {
  241. if (str.indexOf(b[1]) === -1) {
  242. return -1;
  243. }
  244. let level = 0;
  245. for (let i = 0; i < str.length; i++) {
  246. if (str[i] === '\\') {
  247. i++;
  248. }
  249. else if (str[i] === b[0]) {
  250. level++;
  251. }
  252. else if (str[i] === b[1]) {
  253. level--;
  254. if (level < 0) {
  255. return i;
  256. }
  257. }
  258. }
  259. return -1;
  260. }
  261. function checkDeprecations(opt, callback) {
  262. if (!opt || opt.silent) {
  263. return;
  264. }
  265. if (callback) {
  266. console.warn('marked(): callback is deprecated since version 5.0.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/using_pro#async');
  267. }
  268. if (opt.sanitize || opt.sanitizer) {
  269. console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options');
  270. }
  271. if (opt.highlight || opt.langPrefix !== 'language-') {
  272. console.warn('marked(): highlight and langPrefix parameters are deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-highlight.');
  273. }
  274. if (opt.mangle) {
  275. console.warn('marked(): mangle parameter is enabled by default, but is deprecated since version 5.0.0, and will be removed in the future. To clear this warning, install https://www.npmjs.com/package/marked-mangle, or disable by setting `{mangle: false}`.');
  276. }
  277. if (opt.baseUrl) {
  278. console.warn('marked(): baseUrl parameter is deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-base-url.');
  279. }
  280. if (opt.smartypants) {
  281. console.warn('marked(): smartypants parameter is deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-smartypants.');
  282. }
  283. if (opt.xhtml) {
  284. console.warn('marked(): xhtml parameter is deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-xhtml.');
  285. }
  286. if (opt.headerIds || opt.headerPrefix) {
  287. console.warn('marked(): headerIds and headerPrefix parameters enabled by default, but are deprecated since version 5.0.0, and will be removed in the future. To clear this warning, install https://www.npmjs.com/package/marked-gfm-heading-id, or disable by setting `{headerIds: false}`.');
  288. }
  289. }
  290. function outputLink(cap, link, raw, lexer) {
  291. const href = link.href;
  292. const title = link.title ? escape(link.title) : null;
  293. const text = cap[1].replace(/\\([\[\]])/g, '$1');
  294. if (cap[0].charAt(0) !== '!') {
  295. lexer.state.inLink = true;
  296. const token = {
  297. type: 'link',
  298. raw,
  299. href,
  300. title,
  301. text,
  302. tokens: lexer.inlineTokens(text)
  303. };
  304. lexer.state.inLink = false;
  305. return token;
  306. }
  307. return {
  308. type: 'image',
  309. raw,
  310. href,
  311. title,
  312. text: escape(text)
  313. };
  314. }
  315. function indentCodeCompensation(raw, text) {
  316. const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
  317. if (matchIndentToCode === null) {
  318. return text;
  319. }
  320. const indentToCode = matchIndentToCode[1];
  321. return text
  322. .split('\n')
  323. .map(node => {
  324. const matchIndentInNode = node.match(/^\s+/);
  325. if (matchIndentInNode === null) {
  326. return node;
  327. }
  328. const [indentInNode] = matchIndentInNode;
  329. if (indentInNode.length >= indentToCode.length) {
  330. return node.slice(indentToCode.length);
  331. }
  332. return node;
  333. })
  334. .join('\n');
  335. }
  336. /**
  337. * Tokenizer
  338. */
  339. class _Tokenizer {
  340. options;
  341. // TODO: Fix this rules type
  342. rules;
  343. lexer;
  344. constructor(options) {
  345. this.options = options || exports.defaults;
  346. }
  347. space(src) {
  348. const cap = this.rules.block.newline.exec(src);
  349. if (cap && cap[0].length > 0) {
  350. return {
  351. type: 'space',
  352. raw: cap[0]
  353. };
  354. }
  355. }
  356. code(src) {
  357. const cap = this.rules.block.code.exec(src);
  358. if (cap) {
  359. const text = cap[0].replace(/^ {1,4}/gm, '');
  360. return {
  361. type: 'code',
  362. raw: cap[0],
  363. codeBlockStyle: 'indented',
  364. text: !this.options.pedantic
  365. ? rtrim(text, '\n')
  366. : text
  367. };
  368. }
  369. }
  370. fences(src) {
  371. const cap = this.rules.block.fences.exec(src);
  372. if (cap) {
  373. const raw = cap[0];
  374. const text = indentCodeCompensation(raw, cap[3] || '');
  375. return {
  376. type: 'code',
  377. raw,
  378. lang: cap[2] ? cap[2].trim().replace(this.rules.inline._escapes, '$1') : cap[2],
  379. text
  380. };
  381. }
  382. }
  383. heading(src) {
  384. const cap = this.rules.block.heading.exec(src);
  385. if (cap) {
  386. let text = cap[2].trim();
  387. // remove trailing #s
  388. if (/#$/.test(text)) {
  389. const trimmed = rtrim(text, '#');
  390. if (this.options.pedantic) {
  391. text = trimmed.trim();
  392. }
  393. else if (!trimmed || / $/.test(trimmed)) {
  394. // CommonMark requires space before trailing #s
  395. text = trimmed.trim();
  396. }
  397. }
  398. return {
  399. type: 'heading',
  400. raw: cap[0],
  401. depth: cap[1].length,
  402. text,
  403. tokens: this.lexer.inline(text)
  404. };
  405. }
  406. }
  407. hr(src) {
  408. const cap = this.rules.block.hr.exec(src);
  409. if (cap) {
  410. return {
  411. type: 'hr',
  412. raw: cap[0]
  413. };
  414. }
  415. }
  416. blockquote(src) {
  417. const cap = this.rules.block.blockquote.exec(src);
  418. if (cap) {
  419. const text = cap[0].replace(/^ *>[ \t]?/gm, '');
  420. const top = this.lexer.state.top;
  421. this.lexer.state.top = true;
  422. const tokens = this.lexer.blockTokens(text);
  423. this.lexer.state.top = top;
  424. return {
  425. type: 'blockquote',
  426. raw: cap[0],
  427. tokens,
  428. text
  429. };
  430. }
  431. }
  432. list(src) {
  433. let cap = this.rules.block.list.exec(src);
  434. if (cap) {
  435. let bull = cap[1].trim();
  436. const isordered = bull.length > 1;
  437. const list = {
  438. type: 'list',
  439. raw: '',
  440. ordered: isordered,
  441. start: isordered ? +bull.slice(0, -1) : '',
  442. loose: false,
  443. items: []
  444. };
  445. bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
  446. if (this.options.pedantic) {
  447. bull = isordered ? bull : '[*+-]';
  448. }
  449. // Get next list item
  450. const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`);
  451. let raw = '';
  452. let itemContents = '';
  453. let endsWithBlankLine = false;
  454. // Check if current bullet point can start a new List Item
  455. while (src) {
  456. let endEarly = false;
  457. if (!(cap = itemRegex.exec(src))) {
  458. break;
  459. }
  460. if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)
  461. break;
  462. }
  463. raw = cap[0];
  464. src = src.substring(raw.length);
  465. let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t) => ' '.repeat(3 * t.length));
  466. let nextLine = src.split('\n', 1)[0];
  467. let indent = 0;
  468. if (this.options.pedantic) {
  469. indent = 2;
  470. itemContents = line.trimLeft();
  471. }
  472. else {
  473. indent = cap[2].search(/[^ ]/); // Find first non-space char
  474. indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent
  475. itemContents = line.slice(indent);
  476. indent += cap[1].length;
  477. }
  478. let blankLine = false;
  479. if (!line && /^ *$/.test(nextLine)) { // Items begin with at most one blank line
  480. raw += nextLine + '\n';
  481. src = src.substring(nextLine.length + 1);
  482. endEarly = true;
  483. }
  484. if (!endEarly) {
  485. const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`);
  486. const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
  487. const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
  488. const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
  489. // Check if following lines should be included in List Item
  490. while (src) {
  491. const rawLine = src.split('\n', 1)[0];
  492. nextLine = rawLine;
  493. // Re-align to follow commonmark nesting rules
  494. if (this.options.pedantic) {
  495. nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' ');
  496. }
  497. // End list item if found code fences
  498. if (fencesBeginRegex.test(nextLine)) {
  499. break;
  500. }
  501. // End list item if found start of new heading
  502. if (headingBeginRegex.test(nextLine)) {
  503. break;
  504. }
  505. // End list item if found start of new bullet
  506. if (nextBulletRegex.test(nextLine)) {
  507. break;
  508. }
  509. // Horizontal rule found
  510. if (hrRegex.test(src)) {
  511. break;
  512. }
  513. if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible
  514. itemContents += '\n' + nextLine.slice(indent);
  515. }
  516. else {
  517. // not enough indentation
  518. if (blankLine) {
  519. break;
  520. }
  521. // paragraph continuation unless last line was a different block level element
  522. if (line.search(/[^ ]/) >= 4) { // indented code block
  523. break;
  524. }
  525. if (fencesBeginRegex.test(line)) {
  526. break;
  527. }
  528. if (headingBeginRegex.test(line)) {
  529. break;
  530. }
  531. if (hrRegex.test(line)) {
  532. break;
  533. }
  534. itemContents += '\n' + nextLine;
  535. }
  536. if (!blankLine && !nextLine.trim()) { // Check if current line is blank
  537. blankLine = true;
  538. }
  539. raw += rawLine + '\n';
  540. src = src.substring(rawLine.length + 1);
  541. line = nextLine.slice(indent);
  542. }
  543. }
  544. if (!list.loose) {
  545. // If the previous item ended with a blank line, the list is loose
  546. if (endsWithBlankLine) {
  547. list.loose = true;
  548. }
  549. else if (/\n *\n *$/.test(raw)) {
  550. endsWithBlankLine = true;
  551. }
  552. }
  553. let istask = null;
  554. let ischecked;
  555. // Check for task list items
  556. if (this.options.gfm) {
  557. istask = /^\[[ xX]\] /.exec(itemContents);
  558. if (istask) {
  559. ischecked = istask[0] !== '[ ] ';
  560. itemContents = itemContents.replace(/^\[[ xX]\] +/, '');
  561. }
  562. }
  563. list.items.push({
  564. type: 'list_item',
  565. raw,
  566. task: !!istask,
  567. checked: ischecked,
  568. loose: false,
  569. text: itemContents,
  570. tokens: []
  571. });
  572. list.raw += raw;
  573. }
  574. // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic
  575. list.items[list.items.length - 1].raw = raw.trimRight();
  576. list.items[list.items.length - 1].text = itemContents.trimRight();
  577. list.raw = list.raw.trimRight();
  578. // Item child tokens handled here at end because we needed to have the final item to trim it first
  579. for (let i = 0; i < list.items.length; i++) {
  580. this.lexer.state.top = false;
  581. list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);
  582. if (!list.loose) {
  583. // Check if list should be loose
  584. const spacers = list.items[i].tokens.filter(t => t.type === 'space');
  585. const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\n.*\n/.test(t.raw));
  586. list.loose = hasMultipleLineBreaks;
  587. }
  588. }
  589. // Set all items to loose if list is loose
  590. if (list.loose) {
  591. for (let i = 0; i < list.items.length; i++) {
  592. list.items[i].loose = true;
  593. }
  594. }
  595. return list;
  596. }
  597. }
  598. html(src) {
  599. const cap = this.rules.block.html.exec(src);
  600. if (cap) {
  601. const token = {
  602. type: 'html',
  603. block: true,
  604. raw: cap[0],
  605. pre: !this.options.sanitizer
  606. && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
  607. text: cap[0]
  608. };
  609. if (this.options.sanitize) {
  610. const text = this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]);
  611. const paragraph = token;
  612. paragraph.type = 'paragraph';
  613. paragraph.text = text;
  614. paragraph.tokens = this.lexer.inline(text);
  615. }
  616. return token;
  617. }
  618. }
  619. def(src) {
  620. const cap = this.rules.block.def.exec(src);
  621. if (cap) {
  622. const tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
  623. const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline._escapes, '$1') : '';
  624. const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline._escapes, '$1') : cap[3];
  625. return {
  626. type: 'def',
  627. tag,
  628. raw: cap[0],
  629. href,
  630. title
  631. };
  632. }
  633. }
  634. table(src) {
  635. const cap = this.rules.block.table.exec(src);
  636. if (cap) {
  637. const item = {
  638. type: 'table',
  639. raw: cap[0],
  640. header: splitCells(cap[1]).map(c => {
  641. return { text: c, tokens: [] };
  642. }),
  643. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  644. rows: cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : []
  645. };
  646. if (item.header.length === item.align.length) {
  647. let l = item.align.length;
  648. let i, j, k, row;
  649. for (i = 0; i < l; i++) {
  650. const align = item.align[i];
  651. if (align) {
  652. if (/^ *-+: *$/.test(align)) {
  653. item.align[i] = 'right';
  654. }
  655. else if (/^ *:-+: *$/.test(align)) {
  656. item.align[i] = 'center';
  657. }
  658. else if (/^ *:-+ *$/.test(align)) {
  659. item.align[i] = 'left';
  660. }
  661. else {
  662. item.align[i] = null;
  663. }
  664. }
  665. }
  666. l = item.rows.length;
  667. for (i = 0; i < l; i++) {
  668. item.rows[i] = splitCells(item.rows[i], item.header.length).map(c => {
  669. return { text: c, tokens: [] };
  670. });
  671. }
  672. // parse child tokens inside headers and cells
  673. // header child tokens
  674. l = item.header.length;
  675. for (j = 0; j < l; j++) {
  676. item.header[j].tokens = this.lexer.inline(item.header[j].text);
  677. }
  678. // cell child tokens
  679. l = item.rows.length;
  680. for (j = 0; j < l; j++) {
  681. row = item.rows[j];
  682. for (k = 0; k < row.length; k++) {
  683. row[k].tokens = this.lexer.inline(row[k].text);
  684. }
  685. }
  686. return item;
  687. }
  688. }
  689. }
  690. lheading(src) {
  691. const cap = this.rules.block.lheading.exec(src);
  692. if (cap) {
  693. return {
  694. type: 'heading',
  695. raw: cap[0],
  696. depth: cap[2].charAt(0) === '=' ? 1 : 2,
  697. text: cap[1],
  698. tokens: this.lexer.inline(cap[1])
  699. };
  700. }
  701. }
  702. paragraph(src) {
  703. const cap = this.rules.block.paragraph.exec(src);
  704. if (cap) {
  705. const text = cap[1].charAt(cap[1].length - 1) === '\n'
  706. ? cap[1].slice(0, -1)
  707. : cap[1];
  708. return {
  709. type: 'paragraph',
  710. raw: cap[0],
  711. text,
  712. tokens: this.lexer.inline(text)
  713. };
  714. }
  715. }
  716. text(src) {
  717. const cap = this.rules.block.text.exec(src);
  718. if (cap) {
  719. return {
  720. type: 'text',
  721. raw: cap[0],
  722. text: cap[0],
  723. tokens: this.lexer.inline(cap[0])
  724. };
  725. }
  726. }
  727. escape(src) {
  728. const cap = this.rules.inline.escape.exec(src);
  729. if (cap) {
  730. return {
  731. type: 'escape',
  732. raw: cap[0],
  733. text: escape(cap[1])
  734. };
  735. }
  736. }
  737. tag(src) {
  738. const cap = this.rules.inline.tag.exec(src);
  739. if (cap) {
  740. if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
  741. this.lexer.state.inLink = true;
  742. }
  743. else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
  744. this.lexer.state.inLink = false;
  745. }
  746. if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
  747. this.lexer.state.inRawBlock = true;
  748. }
  749. else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
  750. this.lexer.state.inRawBlock = false;
  751. }
  752. return {
  753. type: this.options.sanitize
  754. ? 'text'
  755. : 'html',
  756. raw: cap[0],
  757. inLink: this.lexer.state.inLink,
  758. inRawBlock: this.lexer.state.inRawBlock,
  759. block: false,
  760. text: this.options.sanitize
  761. ? (this.options.sanitizer
  762. ? this.options.sanitizer(cap[0])
  763. : escape(cap[0]))
  764. : cap[0]
  765. };
  766. }
  767. }
  768. link(src) {
  769. const cap = this.rules.inline.link.exec(src);
  770. if (cap) {
  771. const trimmedUrl = cap[2].trim();
  772. if (!this.options.pedantic && /^</.test(trimmedUrl)) {
  773. // commonmark requires matching angle brackets
  774. if (!(/>$/.test(trimmedUrl))) {
  775. return;
  776. }
  777. // ending angle bracket cannot be escaped
  778. const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\');
  779. if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
  780. return;
  781. }
  782. }
  783. else {
  784. // find closing parenthesis
  785. const lastParenIndex = findClosingBracket(cap[2], '()');
  786. if (lastParenIndex > -1) {
  787. const start = cap[0].indexOf('!') === 0 ? 5 : 4;
  788. const linkLen = start + cap[1].length + lastParenIndex;
  789. cap[2] = cap[2].substring(0, lastParenIndex);
  790. cap[0] = cap[0].substring(0, linkLen).trim();
  791. cap[3] = '';
  792. }
  793. }
  794. let href = cap[2];
  795. let title = '';
  796. if (this.options.pedantic) {
  797. // split pedantic href and title
  798. const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
  799. if (link) {
  800. href = link[1];
  801. title = link[3];
  802. }
  803. }
  804. else {
  805. title = cap[3] ? cap[3].slice(1, -1) : '';
  806. }
  807. href = href.trim();
  808. if (/^</.test(href)) {
  809. if (this.options.pedantic && !(/>$/.test(trimmedUrl))) {
  810. // pedantic allows starting angle bracket without ending angle bracket
  811. href = href.slice(1);
  812. }
  813. else {
  814. href = href.slice(1, -1);
  815. }
  816. }
  817. return outputLink(cap, {
  818. href: href ? href.replace(this.rules.inline._escapes, '$1') : href,
  819. title: title ? title.replace(this.rules.inline._escapes, '$1') : title
  820. }, cap[0], this.lexer);
  821. }
  822. }
  823. reflink(src, links) {
  824. let cap;
  825. if ((cap = this.rules.inline.reflink.exec(src))
  826. || (cap = this.rules.inline.nolink.exec(src))) {
  827. let link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
  828. link = links[link.toLowerCase()];
  829. if (!link) {
  830. const text = cap[0].charAt(0);
  831. return {
  832. type: 'text',
  833. raw: text,
  834. text
  835. };
  836. }
  837. return outputLink(cap, link, cap[0], this.lexer);
  838. }
  839. }
  840. emStrong(src, maskedSrc, prevChar = '') {
  841. let match = this.rules.inline.emStrong.lDelim.exec(src);
  842. if (!match)
  843. return;
  844. // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well
  845. if (match[3] && prevChar.match(/[\p{L}\p{N}]/u))
  846. return;
  847. const nextChar = match[1] || match[2] || '';
  848. if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
  849. // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)
  850. const lLength = [...match[0]].length - 1;
  851. let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
  852. const endReg = match[0][0] === '*' ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd;
  853. endReg.lastIndex = 0;
  854. // Clip maskedSrc to same section of string as src (move to lexer?)
  855. maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
  856. while ((match = endReg.exec(maskedSrc)) != null) {
  857. rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
  858. if (!rDelim)
  859. continue; // skip single * in __abc*abc__
  860. rLength = [...rDelim].length;
  861. if (match[3] || match[4]) { // found another Left Delim
  862. delimTotal += rLength;
  863. continue;
  864. }
  865. else if (match[5] || match[6]) { // either Left or Right Delim
  866. if (lLength % 3 && !((lLength + rLength) % 3)) {
  867. midDelimTotal += rLength;
  868. continue; // CommonMark Emphasis Rules 9-10
  869. }
  870. }
  871. delimTotal -= rLength;
  872. if (delimTotal > 0)
  873. continue; // Haven't found enough closing delimiters
  874. // Remove extra characters. *a*** -> *a*
  875. rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
  876. const raw = [...src].slice(0, lLength + match.index + rLength + 1).join('');
  877. // Create `em` if smallest delimiter has odd char count. *a***
  878. if (Math.min(lLength, rLength) % 2) {
  879. const text = raw.slice(1, -1);
  880. return {
  881. type: 'em',
  882. raw,
  883. text,
  884. tokens: this.lexer.inlineTokens(text)
  885. };
  886. }
  887. // Create 'strong' if smallest delimiter has even char count. **a***
  888. const text = raw.slice(2, -2);
  889. return {
  890. type: 'strong',
  891. raw,
  892. text,
  893. tokens: this.lexer.inlineTokens(text)
  894. };
  895. }
  896. }
  897. }
  898. codespan(src) {
  899. const cap = this.rules.inline.code.exec(src);
  900. if (cap) {
  901. let text = cap[2].replace(/\n/g, ' ');
  902. const hasNonSpaceChars = /[^ ]/.test(text);
  903. const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);
  904. if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
  905. text = text.substring(1, text.length - 1);
  906. }
  907. text = escape(text, true);
  908. return {
  909. type: 'codespan',
  910. raw: cap[0],
  911. text
  912. };
  913. }
  914. }
  915. br(src) {
  916. const cap = this.rules.inline.br.exec(src);
  917. if (cap) {
  918. return {
  919. type: 'br',
  920. raw: cap[0]
  921. };
  922. }
  923. }
  924. del(src) {
  925. const cap = this.rules.inline.del.exec(src);
  926. if (cap) {
  927. return {
  928. type: 'del',
  929. raw: cap[0],
  930. text: cap[2],
  931. tokens: this.lexer.inlineTokens(cap[2])
  932. };
  933. }
  934. }
  935. autolink(src, mangle) {
  936. const cap = this.rules.inline.autolink.exec(src);
  937. if (cap) {
  938. let text, href;
  939. if (cap[2] === '@') {
  940. text = escape(this.options.mangle ? mangle(cap[1]) : cap[1]);
  941. href = 'mailto:' + text;
  942. }
  943. else {
  944. text = escape(cap[1]);
  945. href = text;
  946. }
  947. return {
  948. type: 'link',
  949. raw: cap[0],
  950. text,
  951. href,
  952. tokens: [
  953. {
  954. type: 'text',
  955. raw: text,
  956. text
  957. }
  958. ]
  959. };
  960. }
  961. }
  962. url(src, mangle) {
  963. let cap;
  964. if (cap = this.rules.inline.url.exec(src)) {
  965. let text, href;
  966. if (cap[2] === '@') {
  967. text = escape(this.options.mangle ? mangle(cap[0]) : cap[0]);
  968. href = 'mailto:' + text;
  969. }
  970. else {
  971. // do extended autolink path validation
  972. let prevCapZero;
  973. do {
  974. prevCapZero = cap[0];
  975. cap[0] = this.rules.inline._backpedal.exec(cap[0])[0];
  976. } while (prevCapZero !== cap[0]);
  977. text = escape(cap[0]);
  978. if (cap[1] === 'www.') {
  979. href = 'http://' + cap[0];
  980. }
  981. else {
  982. href = cap[0];
  983. }
  984. }
  985. return {
  986. type: 'link',
  987. raw: cap[0],
  988. text,
  989. href,
  990. tokens: [
  991. {
  992. type: 'text',
  993. raw: text,
  994. text
  995. }
  996. ]
  997. };
  998. }
  999. }
  1000. inlineText(src, smartypants) {
  1001. const cap = this.rules.inline.text.exec(src);
  1002. if (cap) {
  1003. let text;
  1004. if (this.lexer.state.inRawBlock) {
  1005. text = this.options.sanitize ? (this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0])) : cap[0];
  1006. }
  1007. else {
  1008. text = escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]);
  1009. }
  1010. return {
  1011. type: 'text',
  1012. raw: cap[0],
  1013. text
  1014. };
  1015. }
  1016. }
  1017. }
  1018. /**
  1019. * Block-Level Grammar
  1020. */
  1021. // Not all rules are defined in the object literal
  1022. // @ts-expect-error
  1023. const block = {
  1024. newline: /^(?: *(?:\n|$))+/,
  1025. code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,
  1026. fences: /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,
  1027. hr: /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,
  1028. heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,
  1029. blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
  1030. list: /^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,
  1031. html: '^ {0,3}(?:' // optional indentation
  1032. + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
  1033. + '|comment[^\\n]*(\\n+|$)' // (2)
  1034. + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3)
  1035. + '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4)
  1036. + '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5)
  1037. + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6)
  1038. + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag
  1039. + '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag
  1040. + ')',
  1041. def: /^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,
  1042. table: noopTest,
  1043. lheading: /^((?:(?!^bull ).|\n(?!\n|bull ))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
  1044. // regex template, placeholders will be replaced according to different paragraph
  1045. // interruption rules of commonmark and the original markdown spec:
  1046. _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,
  1047. text: /^[^\n]+/
  1048. };
  1049. block._label = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
  1050. block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
  1051. block.def = edit(block.def)
  1052. .replace('label', block._label)
  1053. .replace('title', block._title)
  1054. .getRegex();
  1055. block.bullet = /(?:[*+-]|\d{1,9}[.)])/;
  1056. block.listItemStart = edit(/^( *)(bull) */)
  1057. .replace('bull', block.bullet)
  1058. .getRegex();
  1059. block.list = edit(block.list)
  1060. .replace(/bull/g, block.bullet)
  1061. .replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))')
  1062. .replace('def', '\\n+(?=' + block.def.source + ')')
  1063. .getRegex();
  1064. block._tag = 'address|article|aside|base|basefont|blockquote|body|caption'
  1065. + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
  1066. + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
  1067. + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
  1068. + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr'
  1069. + '|track|ul';
  1070. block._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/;
  1071. block.html = edit(block.html, 'i')
  1072. .replace('comment', block._comment)
  1073. .replace('tag', block._tag)
  1074. .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
  1075. .getRegex();
  1076. block.lheading = edit(block.lheading)
  1077. .replace(/bull/g, block.bullet) // lists can interrupt
  1078. .getRegex();
  1079. block.paragraph = edit(block._paragraph)
  1080. .replace('hr', block.hr)
  1081. .replace('heading', ' {0,3}#{1,6} ')
  1082. .replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
  1083. .replace('|table', '')
  1084. .replace('blockquote', ' {0,3}>')
  1085. .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
  1086. .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  1087. .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
  1088. .replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
  1089. .getRegex();
  1090. block.blockquote = edit(block.blockquote)
  1091. .replace('paragraph', block.paragraph)
  1092. .getRegex();
  1093. /**
  1094. * Normal Block Grammar
  1095. */
  1096. block.normal = { ...block };
  1097. /**
  1098. * GFM Block Grammar
  1099. */
  1100. block.gfm = {
  1101. ...block.normal,
  1102. table: '^ *([^\\n ].*\\|.*)\\n' // Header
  1103. + ' {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?' // Align
  1104. + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells
  1105. };
  1106. block.gfm.table = edit(block.gfm.table)
  1107. .replace('hr', block.hr)
  1108. .replace('heading', ' {0,3}#{1,6} ')
  1109. .replace('blockquote', ' {0,3}>')
  1110. .replace('code', ' {4}[^\\n]')
  1111. .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
  1112. .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  1113. .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
  1114. .replace('tag', block._tag) // tables can be interrupted by type (6) html blocks
  1115. .getRegex();
  1116. block.gfm.paragraph = edit(block._paragraph)
  1117. .replace('hr', block.hr)
  1118. .replace('heading', ' {0,3}#{1,6} ')
  1119. .replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
  1120. .replace('table', block.gfm.table) // interrupt paragraphs with table
  1121. .replace('blockquote', ' {0,3}>')
  1122. .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
  1123. .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  1124. .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
  1125. .replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
  1126. .getRegex();
  1127. /**
  1128. * Pedantic grammar (original John Gruber's loose markdown specification)
  1129. */
  1130. block.pedantic = {
  1131. ...block.normal,
  1132. html: edit('^ *(?:comment *(?:\\n|\\s*$)'
  1133. + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
  1134. + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
  1135. .replace('comment', block._comment)
  1136. .replace(/tag/g, '(?!(?:'
  1137. + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
  1138. + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
  1139. + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b')
  1140. .getRegex(),
  1141. def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
  1142. heading: /^(#{1,6})(.*)(?:\n+|$)/,
  1143. fences: noopTest,
  1144. lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
  1145. paragraph: edit(block.normal._paragraph)
  1146. .replace('hr', block.hr)
  1147. .replace('heading', ' *#{1,6} *[^\n]')
  1148. .replace('lheading', block.lheading)
  1149. .replace('blockquote', ' {0,3}>')
  1150. .replace('|fences', '')
  1151. .replace('|list', '')
  1152. .replace('|html', '')
  1153. .getRegex()
  1154. };
  1155. /**
  1156. * Inline-Level Grammar
  1157. */
  1158. // Not all rules are defined in the object literal
  1159. // @ts-expect-error
  1160. const inline = {
  1161. escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
  1162. autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
  1163. url: noopTest,
  1164. tag: '^comment'
  1165. + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
  1166. + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
  1167. + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
  1168. + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
  1169. + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>',
  1170. link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
  1171. reflink: /^!?\[(label)\]\[(ref)\]/,
  1172. nolink: /^!?\[(ref)\](?:\[\])?/,
  1173. reflinkSearch: 'reflink|nolink(?!\\()',
  1174. emStrong: {
  1175. lDelim: /^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,
  1176. // (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left. (5) and (6) can be either Left or Right.
  1177. // | Skip orphan inside strong | Consume to delim | (1) #*** | (2) a***#, a*** | (3) #***a, ***a | (4) ***# | (5) #***# | (6) a***a
  1178. rDelimAst: /^[^_*]*?__[^_*]*?\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\*)[punct](\*+)(?=[\s]|$)|[^punct\s](\*+)(?!\*)(?=[punct\s]|$)|(?!\*)[punct\s](\*+)(?=[^punct\s])|[\s](\*+)(?!\*)(?=[punct])|(?!\*)[punct](\*+)(?!\*)(?=[punct])|[^punct\s](\*+)(?=[^punct\s])/,
  1179. rDelimUnd: /^[^_*]*?\*\*[^_*]*?_[^_*]*?(?=\*\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\s]|$)|[^punct\s](_+)(?!_)(?=[punct\s]|$)|(?!_)[punct\s](_+)(?=[^punct\s])|[\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])/ // ^- Not allowed for _
  1180. },
  1181. code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
  1182. br: /^( {2,}|\\)\n(?!\s*$)/,
  1183. del: noopTest,
  1184. text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,
  1185. punctuation: /^((?![*_])[\spunctuation])/
  1186. };
  1187. // list of unicode punctuation marks, plus any missing characters from CommonMark spec
  1188. inline._punctuation = '\\p{P}$+<=>`^|~';
  1189. inline.punctuation = edit(inline.punctuation, 'u').replace(/punctuation/g, inline._punctuation).getRegex();
  1190. // sequences em should skip over [title](link), `code`, <html>
  1191. inline.blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g;
  1192. inline.anyPunctuation = /\\[punct]/g;
  1193. inline._escapes = /\\([punct])/g;
  1194. inline._comment = edit(block._comment).replace('(?:-->|$)', '-->').getRegex();
  1195. inline.emStrong.lDelim = edit(inline.emStrong.lDelim, 'u')
  1196. .replace(/punct/g, inline._punctuation)
  1197. .getRegex();
  1198. inline.emStrong.rDelimAst = edit(inline.emStrong.rDelimAst, 'gu')
  1199. .replace(/punct/g, inline._punctuation)
  1200. .getRegex();
  1201. inline.emStrong.rDelimUnd = edit(inline.emStrong.rDelimUnd, 'gu')
  1202. .replace(/punct/g, inline._punctuation)
  1203. .getRegex();
  1204. inline.anyPunctuation = edit(inline.anyPunctuation, 'gu')
  1205. .replace(/punct/g, inline._punctuation)
  1206. .getRegex();
  1207. inline._escapes = edit(inline._escapes, 'gu')
  1208. .replace(/punct/g, inline._punctuation)
  1209. .getRegex();
  1210. inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
  1211. inline._email = /[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])?)+(?![-_])/;
  1212. inline.autolink = edit(inline.autolink)
  1213. .replace('scheme', inline._scheme)
  1214. .replace('email', inline._email)
  1215. .getRegex();
  1216. inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
  1217. inline.tag = edit(inline.tag)
  1218. .replace('comment', inline._comment)
  1219. .replace('attribute', inline._attribute)
  1220. .getRegex();
  1221. inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
  1222. inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;
  1223. inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
  1224. inline.link = edit(inline.link)
  1225. .replace('label', inline._label)
  1226. .replace('href', inline._href)
  1227. .replace('title', inline._title)
  1228. .getRegex();
  1229. inline.reflink = edit(inline.reflink)
  1230. .replace('label', inline._label)
  1231. .replace('ref', block._label)
  1232. .getRegex();
  1233. inline.nolink = edit(inline.nolink)
  1234. .replace('ref', block._label)
  1235. .getRegex();
  1236. inline.reflinkSearch = edit(inline.reflinkSearch, 'g')
  1237. .replace('reflink', inline.reflink)
  1238. .replace('nolink', inline.nolink)
  1239. .getRegex();
  1240. /**
  1241. * Normal Inline Grammar
  1242. */
  1243. inline.normal = { ...inline };
  1244. /**
  1245. * Pedantic Inline Grammar
  1246. */
  1247. inline.pedantic = {
  1248. ...inline.normal,
  1249. strong: {
  1250. start: /^__|\*\*/,
  1251. middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
  1252. endAst: /\*\*(?!\*)/g,
  1253. endUnd: /__(?!_)/g
  1254. },
  1255. em: {
  1256. start: /^_|\*/,
  1257. middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,
  1258. endAst: /\*(?!\*)/g,
  1259. endUnd: /_(?!_)/g
  1260. },
  1261. link: edit(/^!?\[(label)\]\((.*?)\)/)
  1262. .replace('label', inline._label)
  1263. .getRegex(),
  1264. reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
  1265. .replace('label', inline._label)
  1266. .getRegex()
  1267. };
  1268. /**
  1269. * GFM Inline Grammar
  1270. */
  1271. inline.gfm = {
  1272. ...inline.normal,
  1273. escape: edit(inline.escape).replace('])', '~|])').getRegex(),
  1274. _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
  1275. url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
  1276. _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
  1277. del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
  1278. text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
  1279. };
  1280. inline.gfm.url = edit(inline.gfm.url, 'i')
  1281. .replace('email', inline.gfm._extended_email)
  1282. .getRegex();
  1283. /**
  1284. * GFM + Line Breaks Inline Grammar
  1285. */
  1286. inline.breaks = {
  1287. ...inline.gfm,
  1288. br: edit(inline.br).replace('{2,}', '*').getRegex(),
  1289. text: edit(inline.gfm.text)
  1290. .replace('\\b_', '\\b_| {2,}\\n')
  1291. .replace(/\{2,\}/g, '*')
  1292. .getRegex()
  1293. };
  1294. /**
  1295. * smartypants text replacement
  1296. */
  1297. function smartypants(text) {
  1298. return text
  1299. // em-dashes
  1300. .replace(/---/g, '\u2014')
  1301. // en-dashes
  1302. .replace(/--/g, '\u2013')
  1303. // opening singles
  1304. .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
  1305. // closing singles & apostrophes
  1306. .replace(/'/g, '\u2019')
  1307. // opening doubles
  1308. .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
  1309. // closing doubles
  1310. .replace(/"/g, '\u201d')
  1311. // ellipses
  1312. .replace(/\.{3}/g, '\u2026');
  1313. }
  1314. /**
  1315. * mangle email addresses
  1316. */
  1317. function mangle(text) {
  1318. let out = '';
  1319. for (let i = 0; i < text.length; i++) {
  1320. const ch = Math.random() > 0.5
  1321. ? 'x' + text.charCodeAt(i).toString(16)
  1322. : text.charCodeAt(i).toString();
  1323. out += '&#' + ch + ';';
  1324. }
  1325. return out;
  1326. }
  1327. /**
  1328. * Block Lexer
  1329. */
  1330. class _Lexer {
  1331. tokens;
  1332. options;
  1333. state;
  1334. tokenizer;
  1335. inlineQueue;
  1336. constructor(options) {
  1337. // TokenList cannot be created in one go
  1338. // @ts-expect-error
  1339. this.tokens = [];
  1340. this.tokens.links = Object.create(null);
  1341. this.options = options || exports.defaults;
  1342. this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
  1343. this.tokenizer = this.options.tokenizer;
  1344. this.tokenizer.options = this.options;
  1345. this.tokenizer.lexer = this;
  1346. this.inlineQueue = [];
  1347. this.state = {
  1348. inLink: false,
  1349. inRawBlock: false,
  1350. top: true
  1351. };
  1352. const rules = {
  1353. block: block.normal,
  1354. inline: inline.normal
  1355. };
  1356. if (this.options.pedantic) {
  1357. rules.block = block.pedantic;
  1358. rules.inline = inline.pedantic;
  1359. }
  1360. else if (this.options.gfm) {
  1361. rules.block = block.gfm;
  1362. if (this.options.breaks) {
  1363. rules.inline = inline.breaks;
  1364. }
  1365. else {
  1366. rules.inline = inline.gfm;
  1367. }
  1368. }
  1369. this.tokenizer.rules = rules;
  1370. }
  1371. /**
  1372. * Expose Rules
  1373. */
  1374. static get rules() {
  1375. return {
  1376. block,
  1377. inline
  1378. };
  1379. }
  1380. /**
  1381. * Static Lex Method
  1382. */
  1383. static lex(src, options) {
  1384. const lexer = new _Lexer(options);
  1385. return lexer.lex(src);
  1386. }
  1387. /**
  1388. * Static Lex Inline Method
  1389. */
  1390. static lexInline(src, options) {
  1391. const lexer = new _Lexer(options);
  1392. return lexer.inlineTokens(src);
  1393. }
  1394. /**
  1395. * Preprocessing
  1396. */
  1397. lex(src) {
  1398. src = src
  1399. .replace(/\r\n|\r/g, '\n');
  1400. this.blockTokens(src, this.tokens);
  1401. let next;
  1402. while (next = this.inlineQueue.shift()) {
  1403. this.inlineTokens(next.src, next.tokens);
  1404. }
  1405. return this.tokens;
  1406. }
  1407. blockTokens(src, tokens = []) {
  1408. if (this.options.pedantic) {
  1409. src = src.replace(/\t/g, ' ').replace(/^ +$/gm, '');
  1410. }
  1411. else {
  1412. src = src.replace(/^( *)(\t+)/gm, (_, leading, tabs) => {
  1413. return leading + ' '.repeat(tabs.length);
  1414. });
  1415. }
  1416. let token;
  1417. let lastToken;
  1418. let cutSrc;
  1419. let lastParagraphClipped;
  1420. while (src) {
  1421. if (this.options.extensions
  1422. && this.options.extensions.block
  1423. && this.options.extensions.block.some((extTokenizer) => {
  1424. if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
  1425. src = src.substring(token.raw.length);
  1426. tokens.push(token);
  1427. return true;
  1428. }
  1429. return false;
  1430. })) {
  1431. continue;
  1432. }
  1433. // newline
  1434. if (token = this.tokenizer.space(src)) {
  1435. src = src.substring(token.raw.length);
  1436. if (token.raw.length === 1 && tokens.length > 0) {
  1437. // if there's a single \n as a spacer, it's terminating the last line,
  1438. // so move it there so that we don't get unecessary paragraph tags
  1439. tokens[tokens.length - 1].raw += '\n';
  1440. }
  1441. else {
  1442. tokens.push(token);
  1443. }
  1444. continue;
  1445. }
  1446. // code
  1447. if (token = this.tokenizer.code(src)) {
  1448. src = src.substring(token.raw.length);
  1449. lastToken = tokens[tokens.length - 1];
  1450. // An indented code block cannot interrupt a paragraph.
  1451. if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
  1452. lastToken.raw += '\n' + token.raw;
  1453. lastToken.text += '\n' + token.text;
  1454. this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
  1455. }
  1456. else {
  1457. tokens.push(token);
  1458. }
  1459. continue;
  1460. }
  1461. // fences
  1462. if (token = this.tokenizer.fences(src)) {
  1463. src = src.substring(token.raw.length);
  1464. tokens.push(token);
  1465. continue;
  1466. }
  1467. // heading
  1468. if (token = this.tokenizer.heading(src)) {
  1469. src = src.substring(token.raw.length);
  1470. tokens.push(token);
  1471. continue;
  1472. }
  1473. // hr
  1474. if (token = this.tokenizer.hr(src)) {
  1475. src = src.substring(token.raw.length);
  1476. tokens.push(token);
  1477. continue;
  1478. }
  1479. // blockquote
  1480. if (token = this.tokenizer.blockquote(src)) {
  1481. src = src.substring(token.raw.length);
  1482. tokens.push(token);
  1483. continue;
  1484. }
  1485. // list
  1486. if (token = this.tokenizer.list(src)) {
  1487. src = src.substring(token.raw.length);
  1488. tokens.push(token);
  1489. continue;
  1490. }
  1491. // html
  1492. if (token = this.tokenizer.html(src)) {
  1493. src = src.substring(token.raw.length);
  1494. tokens.push(token);
  1495. continue;
  1496. }
  1497. // def
  1498. if (token = this.tokenizer.def(src)) {
  1499. src = src.substring(token.raw.length);
  1500. lastToken = tokens[tokens.length - 1];
  1501. if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
  1502. lastToken.raw += '\n' + token.raw;
  1503. lastToken.text += '\n' + token.raw;
  1504. this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
  1505. }
  1506. else if (!this.tokens.links[token.tag]) {
  1507. this.tokens.links[token.tag] = {
  1508. href: token.href,
  1509. title: token.title
  1510. };
  1511. }
  1512. continue;
  1513. }
  1514. // table (gfm)
  1515. if (token = this.tokenizer.table(src)) {
  1516. src = src.substring(token.raw.length);
  1517. tokens.push(token);
  1518. continue;
  1519. }
  1520. // lheading
  1521. if (token = this.tokenizer.lheading(src)) {
  1522. src = src.substring(token.raw.length);
  1523. tokens.push(token);
  1524. continue;
  1525. }
  1526. // top-level paragraph
  1527. // prevent paragraph consuming extensions by clipping 'src' to extension start
  1528. cutSrc = src;
  1529. if (this.options.extensions && this.options.extensions.startBlock) {
  1530. let startIndex = Infinity;
  1531. const tempSrc = src.slice(1);
  1532. let tempStart;
  1533. this.options.extensions.startBlock.forEach((getStartIndex) => {
  1534. tempStart = getStartIndex.call({ lexer: this }, tempSrc);
  1535. if (typeof tempStart === 'number' && tempStart >= 0) {
  1536. startIndex = Math.min(startIndex, tempStart);
  1537. }
  1538. });
  1539. if (startIndex < Infinity && startIndex >= 0) {
  1540. cutSrc = src.substring(0, startIndex + 1);
  1541. }
  1542. }
  1543. if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
  1544. lastToken = tokens[tokens.length - 1];
  1545. if (lastParagraphClipped && lastToken.type === 'paragraph') {
  1546. lastToken.raw += '\n' + token.raw;
  1547. lastToken.text += '\n' + token.text;
  1548. this.inlineQueue.pop();
  1549. this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
  1550. }
  1551. else {
  1552. tokens.push(token);
  1553. }
  1554. lastParagraphClipped = (cutSrc.length !== src.length);
  1555. src = src.substring(token.raw.length);
  1556. continue;
  1557. }
  1558. // text
  1559. if (token = this.tokenizer.text(src)) {
  1560. src = src.substring(token.raw.length);
  1561. lastToken = tokens[tokens.length - 1];
  1562. if (lastToken && lastToken.type === 'text') {
  1563. lastToken.raw += '\n' + token.raw;
  1564. lastToken.text += '\n' + token.text;
  1565. this.inlineQueue.pop();
  1566. this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
  1567. }
  1568. else {
  1569. tokens.push(token);
  1570. }
  1571. continue;
  1572. }
  1573. if (src) {
  1574. const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
  1575. if (this.options.silent) {
  1576. console.error(errMsg);
  1577. break;
  1578. }
  1579. else {
  1580. throw new Error(errMsg);
  1581. }
  1582. }
  1583. }
  1584. this.state.top = true;
  1585. return tokens;
  1586. }
  1587. inline(src, tokens = []) {
  1588. this.inlineQueue.push({ src, tokens });
  1589. return tokens;
  1590. }
  1591. /**
  1592. * Lexing/Compiling
  1593. */
  1594. inlineTokens(src, tokens = []) {
  1595. let token, lastToken, cutSrc;
  1596. // String with links masked to avoid interference with em and strong
  1597. let maskedSrc = src;
  1598. let match;
  1599. let keepPrevChar, prevChar;
  1600. // Mask out reflinks
  1601. if (this.tokens.links) {
  1602. const links = Object.keys(this.tokens.links);
  1603. if (links.length > 0) {
  1604. while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
  1605. if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
  1606. maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
  1607. }
  1608. }
  1609. }
  1610. }
  1611. // Mask out other blocks
  1612. while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
  1613. maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
  1614. }
  1615. // Mask out escaped characters
  1616. while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
  1617. maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
  1618. }
  1619. while (src) {
  1620. if (!keepPrevChar) {
  1621. prevChar = '';
  1622. }
  1623. keepPrevChar = false;
  1624. // extensions
  1625. if (this.options.extensions
  1626. && this.options.extensions.inline
  1627. && this.options.extensions.inline.some((extTokenizer) => {
  1628. if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
  1629. src = src.substring(token.raw.length);
  1630. tokens.push(token);
  1631. return true;
  1632. }
  1633. return false;
  1634. })) {
  1635. continue;
  1636. }
  1637. // escape
  1638. if (token = this.tokenizer.escape(src)) {
  1639. src = src.substring(token.raw.length);
  1640. tokens.push(token);
  1641. continue;
  1642. }
  1643. // tag
  1644. if (token = this.tokenizer.tag(src)) {
  1645. src = src.substring(token.raw.length);
  1646. lastToken = tokens[tokens.length - 1];
  1647. if (lastToken && token.type === 'text' && lastToken.type === 'text') {
  1648. lastToken.raw += token.raw;
  1649. lastToken.text += token.text;
  1650. }
  1651. else {
  1652. tokens.push(token);
  1653. }
  1654. continue;
  1655. }
  1656. // link
  1657. if (token = this.tokenizer.link(src)) {
  1658. src = src.substring(token.raw.length);
  1659. tokens.push(token);
  1660. continue;
  1661. }
  1662. // reflink, nolink
  1663. if (token = this.tokenizer.reflink(src, this.tokens.links)) {
  1664. src = src.substring(token.raw.length);
  1665. lastToken = tokens[tokens.length - 1];
  1666. if (lastToken && token.type === 'text' && lastToken.type === 'text') {
  1667. lastToken.raw += token.raw;
  1668. lastToken.text += token.text;
  1669. }
  1670. else {
  1671. tokens.push(token);
  1672. }
  1673. continue;
  1674. }
  1675. // em & strong
  1676. if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
  1677. src = src.substring(token.raw.length);
  1678. tokens.push(token);
  1679. continue;
  1680. }
  1681. // code
  1682. if (token = this.tokenizer.codespan(src)) {
  1683. src = src.substring(token.raw.length);
  1684. tokens.push(token);
  1685. continue;
  1686. }
  1687. // br
  1688. if (token = this.tokenizer.br(src)) {
  1689. src = src.substring(token.raw.length);
  1690. tokens.push(token);
  1691. continue;
  1692. }
  1693. // del (gfm)
  1694. if (token = this.tokenizer.del(src)) {
  1695. src = src.substring(token.raw.length);
  1696. tokens.push(token);
  1697. continue;
  1698. }
  1699. // autolink
  1700. if (token = this.tokenizer.autolink(src, mangle)) {
  1701. src = src.substring(token.raw.length);
  1702. tokens.push(token);
  1703. continue;
  1704. }
  1705. // url (gfm)
  1706. if (!this.state.inLink && (token = this.tokenizer.url(src, mangle))) {
  1707. src = src.substring(token.raw.length);
  1708. tokens.push(token);
  1709. continue;
  1710. }
  1711. // text
  1712. // prevent inlineText consuming extensions by clipping 'src' to extension start
  1713. cutSrc = src;
  1714. if (this.options.extensions && this.options.extensions.startInline) {
  1715. let startIndex = Infinity;
  1716. const tempSrc = src.slice(1);
  1717. let tempStart;
  1718. this.options.extensions.startInline.forEach((getStartIndex) => {
  1719. tempStart = getStartIndex.call({ lexer: this }, tempSrc);
  1720. if (typeof tempStart === 'number' && tempStart >= 0) {
  1721. startIndex = Math.min(startIndex, tempStart);
  1722. }
  1723. });
  1724. if (startIndex < Infinity && startIndex >= 0) {
  1725. cutSrc = src.substring(0, startIndex + 1);
  1726. }
  1727. }
  1728. if (token = this.tokenizer.inlineText(cutSrc, smartypants)) {
  1729. src = src.substring(token.raw.length);
  1730. if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started
  1731. prevChar = token.raw.slice(-1);
  1732. }
  1733. keepPrevChar = true;
  1734. lastToken = tokens[tokens.length - 1];
  1735. if (lastToken && lastToken.type === 'text') {
  1736. lastToken.raw += token.raw;
  1737. lastToken.text += token.text;
  1738. }
  1739. else {
  1740. tokens.push(token);
  1741. }
  1742. continue;
  1743. }
  1744. if (src) {
  1745. const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
  1746. if (this.options.silent) {
  1747. console.error(errMsg);
  1748. break;
  1749. }
  1750. else {
  1751. throw new Error(errMsg);
  1752. }
  1753. }
  1754. }
  1755. return tokens;
  1756. }
  1757. }
  1758. /**
  1759. * Renderer
  1760. */
  1761. class _Renderer {
  1762. options;
  1763. constructor(options) {
  1764. this.options = options || exports.defaults;
  1765. }
  1766. code(code, infostring, escaped) {
  1767. const lang = (infostring || '').match(/^\S*/)?.[0];
  1768. if (this.options.highlight) {
  1769. const out = this.options.highlight(code, lang);
  1770. if (out != null && out !== code) {
  1771. escaped = true;
  1772. code = out;
  1773. }
  1774. }
  1775. code = code.replace(/\n$/, '') + '\n';
  1776. if (!lang) {
  1777. return '<pre><code>'
  1778. + (escaped ? code : escape(code, true))
  1779. + '</code></pre>\n';
  1780. }
  1781. return '<pre><code class="'
  1782. + this.options.langPrefix
  1783. + escape(lang)
  1784. + '">'
  1785. + (escaped ? code : escape(code, true))
  1786. + '</code></pre>\n';
  1787. }
  1788. blockquote(quote) {
  1789. return `<blockquote>\n${quote}</blockquote>\n`;
  1790. }
  1791. html(html, block) {
  1792. return html;
  1793. }
  1794. heading(text, level, raw, slugger) {
  1795. if (this.options.headerIds) {
  1796. const id = this.options.headerPrefix + slugger.slug(raw);
  1797. return `<h${level} id="${id}">${text}</h${level}>\n`;
  1798. }
  1799. // ignore IDs
  1800. return `<h${level}>${text}</h${level}>\n`;
  1801. }
  1802. hr() {
  1803. return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
  1804. }
  1805. list(body, ordered, start) {
  1806. const type = ordered ? 'ol' : 'ul';
  1807. const startatt = (ordered && start !== 1) ? (' start="' + start + '"') : '';
  1808. return '<' + type + startatt + '>\n' + body + '</' + type + '>\n';
  1809. }
  1810. listitem(text, task, checked) {
  1811. return `<li>${text}</li>\n`;
  1812. }
  1813. checkbox(checked) {
  1814. return '<input '
  1815. + (checked ? 'checked="" ' : '')
  1816. + 'disabled="" type="checkbox"'
  1817. + (this.options.xhtml ? ' /' : '')
  1818. + '> ';
  1819. }
  1820. paragraph(text) {
  1821. return `<p>${text}</p>\n`;
  1822. }
  1823. table(header, body) {
  1824. if (body)
  1825. body = `<tbody>${body}</tbody>`;
  1826. return '<table>\n'
  1827. + '<thead>\n'
  1828. + header
  1829. + '</thead>\n'
  1830. + body
  1831. + '</table>\n';
  1832. }
  1833. tablerow(content) {
  1834. return `<tr>\n${content}</tr>\n`;
  1835. }
  1836. tablecell(content, flags) {
  1837. const type = flags.header ? 'th' : 'td';
  1838. const tag = flags.align
  1839. ? `<${type} align="${flags.align}">`
  1840. : `<${type}>`;
  1841. return tag + content + `</${type}>\n`;
  1842. }
  1843. /**
  1844. * span level renderer
  1845. */
  1846. strong(text) {
  1847. return `<strong>${text}</strong>`;
  1848. }
  1849. em(text) {
  1850. return `<em>${text}</em>`;
  1851. }
  1852. codespan(text) {
  1853. return `<code>${text}</code>`;
  1854. }
  1855. br() {
  1856. return this.options.xhtml ? '<br/>' : '<br>';
  1857. }
  1858. del(text) {
  1859. return `<del>${text}</del>`;
  1860. }
  1861. link(href, title, text) {
  1862. const cleanHref = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
  1863. if (cleanHref === null) {
  1864. return text;
  1865. }
  1866. href = cleanHref;
  1867. let out = '<a href="' + href + '"';
  1868. if (title) {
  1869. out += ' title="' + title + '"';
  1870. }
  1871. out += '>' + text + '</a>';
  1872. return out;
  1873. }
  1874. image(href, title, text) {
  1875. const cleanHref = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
  1876. if (cleanHref === null) {
  1877. return text;
  1878. }
  1879. href = cleanHref;
  1880. let out = `<img src="${href}" alt="${text}"`;
  1881. if (title) {
  1882. out += ` title="${title}"`;
  1883. }
  1884. out += this.options.xhtml ? '/>' : '>';
  1885. return out;
  1886. }
  1887. text(text) {
  1888. return text;
  1889. }
  1890. }
  1891. /**
  1892. * TextRenderer
  1893. * returns only the textual part of the token
  1894. */
  1895. class _TextRenderer {
  1896. // no need for block level renderers
  1897. strong(text) {
  1898. return text;
  1899. }
  1900. em(text) {
  1901. return text;
  1902. }
  1903. codespan(text) {
  1904. return text;
  1905. }
  1906. del(text) {
  1907. return text;
  1908. }
  1909. html(text) {
  1910. return text;
  1911. }
  1912. text(text) {
  1913. return text;
  1914. }
  1915. link(href, title, text) {
  1916. return '' + text;
  1917. }
  1918. image(href, title, text) {
  1919. return '' + text;
  1920. }
  1921. br() {
  1922. return '';
  1923. }
  1924. }
  1925. /**
  1926. * Slugger generates header id
  1927. */
  1928. class _Slugger {
  1929. seen;
  1930. constructor() {
  1931. this.seen = {};
  1932. }
  1933. serialize(value) {
  1934. return value
  1935. .toLowerCase()
  1936. .trim()
  1937. // remove html tags
  1938. .replace(/<[!\/a-z].*?>/ig, '')
  1939. // remove unwanted chars
  1940. .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '')
  1941. .replace(/\s/g, '-');
  1942. }
  1943. /**
  1944. * Finds the next safe (unique) slug to use
  1945. */
  1946. getNextSafeSlug(originalSlug, isDryRun) {
  1947. let slug = originalSlug;
  1948. let occurenceAccumulator = 0;
  1949. if (this.seen.hasOwnProperty(slug)) {
  1950. occurenceAccumulator = this.seen[originalSlug];
  1951. do {
  1952. occurenceAccumulator++;
  1953. slug = originalSlug + '-' + occurenceAccumulator;
  1954. } while (this.seen.hasOwnProperty(slug));
  1955. }
  1956. if (!isDryRun) {
  1957. this.seen[originalSlug] = occurenceAccumulator;
  1958. this.seen[slug] = 0;
  1959. }
  1960. return slug;
  1961. }
  1962. /**
  1963. * Convert string to unique id
  1964. */
  1965. slug(value, options = {}) {
  1966. const slug = this.serialize(value);
  1967. return this.getNextSafeSlug(slug, options.dryrun);
  1968. }
  1969. }
  1970. /**
  1971. * Parsing & Compiling
  1972. */
  1973. class _Parser {
  1974. options;
  1975. renderer;
  1976. textRenderer;
  1977. slugger;
  1978. constructor(options) {
  1979. this.options = options || exports.defaults;
  1980. this.options.renderer = this.options.renderer || new _Renderer();
  1981. this.renderer = this.options.renderer;
  1982. this.renderer.options = this.options;
  1983. this.textRenderer = new _TextRenderer();
  1984. this.slugger = new _Slugger();
  1985. }
  1986. /**
  1987. * Static Parse Method
  1988. */
  1989. static parse(tokens, options) {
  1990. const parser = new _Parser(options);
  1991. return parser.parse(tokens);
  1992. }
  1993. /**
  1994. * Static Parse Inline Method
  1995. */
  1996. static parseInline(tokens, options) {
  1997. const parser = new _Parser(options);
  1998. return parser.parseInline(tokens);
  1999. }
  2000. /**
  2001. * Parse Loop
  2002. */
  2003. parse(tokens, top = true) {
  2004. let out = '';
  2005. for (let i = 0; i < tokens.length; i++) {
  2006. const token = tokens[i];
  2007. // Run any renderer extensions
  2008. if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
  2009. const genericToken = token;
  2010. const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
  2011. if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(genericToken.type)) {
  2012. out += ret || '';
  2013. continue;
  2014. }
  2015. }
  2016. switch (token.type) {
  2017. case 'space': {
  2018. continue;
  2019. }
  2020. case 'hr': {
  2021. out += this.renderer.hr();
  2022. continue;
  2023. }
  2024. case 'heading': {
  2025. const headingToken = token;
  2026. out += this.renderer.heading(this.parseInline(headingToken.tokens), headingToken.depth, unescape(this.parseInline(headingToken.tokens, this.textRenderer)), this.slugger);
  2027. continue;
  2028. }
  2029. case 'code': {
  2030. const codeToken = token;
  2031. out += this.renderer.code(codeToken.text, codeToken.lang, !!codeToken.escaped);
  2032. continue;
  2033. }
  2034. case 'table': {
  2035. const tableToken = token;
  2036. let header = '';
  2037. // header
  2038. let cell = '';
  2039. for (let j = 0; j < tableToken.header.length; j++) {
  2040. cell += this.renderer.tablecell(this.parseInline(tableToken.header[j].tokens), { header: true, align: tableToken.align[j] });
  2041. }
  2042. header += this.renderer.tablerow(cell);
  2043. let body = '';
  2044. for (let j = 0; j < tableToken.rows.length; j++) {
  2045. const row = tableToken.rows[j];
  2046. cell = '';
  2047. for (let k = 0; k < row.length; k++) {
  2048. cell += this.renderer.tablecell(this.parseInline(row[k].tokens), { header: false, align: tableToken.align[k] });
  2049. }
  2050. body += this.renderer.tablerow(cell);
  2051. }
  2052. out += this.renderer.table(header, body);
  2053. continue;
  2054. }
  2055. case 'blockquote': {
  2056. const blockquoteToken = token;
  2057. const body = this.parse(blockquoteToken.tokens);
  2058. out += this.renderer.blockquote(body);
  2059. continue;
  2060. }
  2061. case 'list': {
  2062. const listToken = token;
  2063. const ordered = listToken.ordered;
  2064. const start = listToken.start;
  2065. const loose = listToken.loose;
  2066. let body = '';
  2067. for (let j = 0; j < listToken.items.length; j++) {
  2068. const item = listToken.items[j];
  2069. const checked = item.checked;
  2070. const task = item.task;
  2071. let itemBody = '';
  2072. if (item.task) {
  2073. const checkbox = this.renderer.checkbox(!!checked);
  2074. if (loose) {
  2075. if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
  2076. item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
  2077. if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
  2078. item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
  2079. }
  2080. }
  2081. else {
  2082. item.tokens.unshift({
  2083. type: 'text',
  2084. text: checkbox
  2085. });
  2086. }
  2087. }
  2088. else {
  2089. itemBody += checkbox;
  2090. }
  2091. }
  2092. itemBody += this.parse(item.tokens, loose);
  2093. body += this.renderer.listitem(itemBody, task, !!checked);
  2094. }
  2095. out += this.renderer.list(body, ordered, start);
  2096. continue;
  2097. }
  2098. case 'html': {
  2099. const htmlToken = token;
  2100. out += this.renderer.html(htmlToken.text, htmlToken.block);
  2101. continue;
  2102. }
  2103. case 'paragraph': {
  2104. const paragraphToken = token;
  2105. out += this.renderer.paragraph(this.parseInline(paragraphToken.tokens));
  2106. continue;
  2107. }
  2108. case 'text': {
  2109. let textToken = token;
  2110. let body = textToken.tokens ? this.parseInline(textToken.tokens) : textToken.text;
  2111. while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {
  2112. textToken = tokens[++i];
  2113. body += '\n' + (textToken.tokens ? this.parseInline(textToken.tokens) : textToken.text);
  2114. }
  2115. out += top ? this.renderer.paragraph(body) : body;
  2116. continue;
  2117. }
  2118. default: {
  2119. const errMsg = 'Token with "' + token.type + '" type was not found.';
  2120. if (this.options.silent) {
  2121. console.error(errMsg);
  2122. return '';
  2123. }
  2124. else {
  2125. throw new Error(errMsg);
  2126. }
  2127. }
  2128. }
  2129. }
  2130. return out;
  2131. }
  2132. /**
  2133. * Parse Inline Tokens
  2134. */
  2135. parseInline(tokens, renderer) {
  2136. renderer = renderer || this.renderer;
  2137. let out = '';
  2138. for (let i = 0; i < tokens.length; i++) {
  2139. const token = tokens[i];
  2140. // Run any renderer extensions
  2141. if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
  2142. const ret = this.options.extensions.renderers[token.type].call({ parser: this }, token);
  2143. if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(token.type)) {
  2144. out += ret || '';
  2145. continue;
  2146. }
  2147. }
  2148. switch (token.type) {
  2149. case 'escape': {
  2150. const escapeToken = token;
  2151. out += renderer.text(escapeToken.text);
  2152. break;
  2153. }
  2154. case 'html': {
  2155. const tagToken = token;
  2156. out += renderer.html(tagToken.text);
  2157. break;
  2158. }
  2159. case 'link': {
  2160. const linkToken = token;
  2161. out += renderer.link(linkToken.href, linkToken.title, this.parseInline(linkToken.tokens, renderer));
  2162. break;
  2163. }
  2164. case 'image': {
  2165. const imageToken = token;
  2166. out += renderer.image(imageToken.href, imageToken.title, imageToken.text);
  2167. break;
  2168. }
  2169. case 'strong': {
  2170. const strongToken = token;
  2171. out += renderer.strong(this.parseInline(strongToken.tokens, renderer));
  2172. break;
  2173. }
  2174. case 'em': {
  2175. const emToken = token;
  2176. out += renderer.em(this.parseInline(emToken.tokens, renderer));
  2177. break;
  2178. }
  2179. case 'codespan': {
  2180. const codespanToken = token;
  2181. out += renderer.codespan(codespanToken.text);
  2182. break;
  2183. }
  2184. case 'br': {
  2185. out += renderer.br();
  2186. break;
  2187. }
  2188. case 'del': {
  2189. const delToken = token;
  2190. out += renderer.del(this.parseInline(delToken.tokens, renderer));
  2191. break;
  2192. }
  2193. case 'text': {
  2194. const textToken = token;
  2195. out += renderer.text(textToken.text);
  2196. break;
  2197. }
  2198. default: {
  2199. const errMsg = 'Token with "' + token.type + '" type was not found.';
  2200. if (this.options.silent) {
  2201. console.error(errMsg);
  2202. return '';
  2203. }
  2204. else {
  2205. throw new Error(errMsg);
  2206. }
  2207. }
  2208. }
  2209. }
  2210. return out;
  2211. }
  2212. }
  2213. class _Hooks {
  2214. options;
  2215. constructor(options) {
  2216. this.options = options || exports.defaults;
  2217. }
  2218. static passThroughHooks = new Set([
  2219. 'preprocess',
  2220. 'postprocess'
  2221. ]);
  2222. /**
  2223. * Process markdown before marked
  2224. */
  2225. preprocess(markdown) {
  2226. return markdown;
  2227. }
  2228. /**
  2229. * Process HTML after marked is finished
  2230. */
  2231. postprocess(html) {
  2232. return html;
  2233. }
  2234. }
  2235. class Marked {
  2236. defaults = _getDefaults();
  2237. options = this.setOptions;
  2238. parse = this.#parseMarkdown(_Lexer.lex, _Parser.parse);
  2239. parseInline = this.#parseMarkdown(_Lexer.lexInline, _Parser.parseInline);
  2240. Parser = _Parser;
  2241. parser = _Parser.parse;
  2242. Renderer = _Renderer;
  2243. TextRenderer = _TextRenderer;
  2244. Lexer = _Lexer;
  2245. lexer = _Lexer.lex;
  2246. Tokenizer = _Tokenizer;
  2247. Slugger = _Slugger;
  2248. Hooks = _Hooks;
  2249. constructor(...args) {
  2250. this.use(...args);
  2251. }
  2252. /**
  2253. * Run callback for every token
  2254. */
  2255. walkTokens(tokens, callback) {
  2256. let values = [];
  2257. for (const token of tokens) {
  2258. values = values.concat(callback.call(this, token));
  2259. switch (token.type) {
  2260. case 'table': {
  2261. const tableToken = token;
  2262. for (const cell of tableToken.header) {
  2263. values = values.concat(this.walkTokens(cell.tokens, callback));
  2264. }
  2265. for (const row of tableToken.rows) {
  2266. for (const cell of row) {
  2267. values = values.concat(this.walkTokens(cell.tokens, callback));
  2268. }
  2269. }
  2270. break;
  2271. }
  2272. case 'list': {
  2273. const listToken = token;
  2274. values = values.concat(this.walkTokens(listToken.items, callback));
  2275. break;
  2276. }
  2277. default: {
  2278. const genericToken = token;
  2279. if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
  2280. this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
  2281. values = values.concat(this.walkTokens(genericToken[childTokens], callback));
  2282. });
  2283. }
  2284. else if (genericToken.tokens) {
  2285. values = values.concat(this.walkTokens(genericToken.tokens, callback));
  2286. }
  2287. }
  2288. }
  2289. }
  2290. return values;
  2291. }
  2292. use(...args) {
  2293. const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
  2294. args.forEach((pack) => {
  2295. // copy options to new object
  2296. const opts = { ...pack };
  2297. // set async to true if it was set to true before
  2298. opts.async = this.defaults.async || opts.async || false;
  2299. // ==-- Parse "addon" extensions --== //
  2300. if (pack.extensions) {
  2301. pack.extensions.forEach((ext) => {
  2302. if (!ext.name) {
  2303. throw new Error('extension name required');
  2304. }
  2305. if ('renderer' in ext) { // Renderer extensions
  2306. const prevRenderer = extensions.renderers[ext.name];
  2307. if (prevRenderer) {
  2308. // Replace extension with func to run new extension but fall back if false
  2309. extensions.renderers[ext.name] = function (...args) {
  2310. let ret = ext.renderer.apply(this, args);
  2311. if (ret === false) {
  2312. ret = prevRenderer.apply(this, args);
  2313. }
  2314. return ret;
  2315. };
  2316. }
  2317. else {
  2318. extensions.renderers[ext.name] = ext.renderer;
  2319. }
  2320. }
  2321. if ('tokenizer' in ext) { // Tokenizer Extensions
  2322. if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {
  2323. throw new Error("extension level must be 'block' or 'inline'");
  2324. }
  2325. const extLevel = extensions[ext.level];
  2326. if (extLevel) {
  2327. extLevel.unshift(ext.tokenizer);
  2328. }
  2329. else {
  2330. extensions[ext.level] = [ext.tokenizer];
  2331. }
  2332. if (ext.start) { // Function to check for start of token
  2333. if (ext.level === 'block') {
  2334. if (extensions.startBlock) {
  2335. extensions.startBlock.push(ext.start);
  2336. }
  2337. else {
  2338. extensions.startBlock = [ext.start];
  2339. }
  2340. }
  2341. else if (ext.level === 'inline') {
  2342. if (extensions.startInline) {
  2343. extensions.startInline.push(ext.start);
  2344. }
  2345. else {
  2346. extensions.startInline = [ext.start];
  2347. }
  2348. }
  2349. }
  2350. }
  2351. if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens
  2352. extensions.childTokens[ext.name] = ext.childTokens;
  2353. }
  2354. });
  2355. opts.extensions = extensions;
  2356. }
  2357. // ==-- Parse "overwrite" extensions --== //
  2358. if (pack.renderer) {
  2359. const renderer = this.defaults.renderer || new _Renderer(this.defaults);
  2360. for (const prop in pack.renderer) {
  2361. const rendererFunc = pack.renderer[prop];
  2362. const rendererKey = prop;
  2363. const prevRenderer = renderer[rendererKey];
  2364. // Replace renderer with func to run extension, but fall back if false
  2365. renderer[rendererKey] = (...args) => {
  2366. let ret = rendererFunc.apply(renderer, args);
  2367. if (ret === false) {
  2368. ret = prevRenderer.apply(renderer, args);
  2369. }
  2370. return ret || '';
  2371. };
  2372. }
  2373. opts.renderer = renderer;
  2374. }
  2375. if (pack.tokenizer) {
  2376. const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
  2377. for (const prop in pack.tokenizer) {
  2378. const tokenizerFunc = pack.tokenizer[prop];
  2379. const tokenizerKey = prop;
  2380. const prevTokenizer = tokenizer[tokenizerKey];
  2381. // Replace tokenizer with func to run extension, but fall back if false
  2382. tokenizer[tokenizerKey] = (...args) => {
  2383. let ret = tokenizerFunc.apply(tokenizer, args);
  2384. if (ret === false) {
  2385. ret = prevTokenizer.apply(tokenizer, args);
  2386. }
  2387. return ret;
  2388. };
  2389. }
  2390. opts.tokenizer = tokenizer;
  2391. }
  2392. // ==-- Parse Hooks extensions --== //
  2393. if (pack.hooks) {
  2394. const hooks = this.defaults.hooks || new _Hooks();
  2395. for (const prop in pack.hooks) {
  2396. const hooksFunc = pack.hooks[prop];
  2397. const hooksKey = prop;
  2398. const prevHook = hooks[hooksKey];
  2399. if (_Hooks.passThroughHooks.has(prop)) {
  2400. hooks[hooksKey] = (arg) => {
  2401. if (this.defaults.async) {
  2402. return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {
  2403. return prevHook.call(hooks, ret);
  2404. });
  2405. }
  2406. const ret = hooksFunc.call(hooks, arg);
  2407. return prevHook.call(hooks, ret);
  2408. };
  2409. }
  2410. else {
  2411. hooks[hooksKey] = (...args) => {
  2412. let ret = hooksFunc.apply(hooks, args);
  2413. if (ret === false) {
  2414. ret = prevHook.apply(hooks, args);
  2415. }
  2416. return ret;
  2417. };
  2418. }
  2419. }
  2420. opts.hooks = hooks;
  2421. }
  2422. // ==-- Parse WalkTokens extensions --== //
  2423. if (pack.walkTokens) {
  2424. const walkTokens = this.defaults.walkTokens;
  2425. const packWalktokens = pack.walkTokens;
  2426. opts.walkTokens = function (token) {
  2427. let values = [];
  2428. values.push(packWalktokens.call(this, token));
  2429. if (walkTokens) {
  2430. values = values.concat(walkTokens.call(this, token));
  2431. }
  2432. return values;
  2433. };
  2434. }
  2435. this.defaults = { ...this.defaults, ...opts };
  2436. });
  2437. return this;
  2438. }
  2439. setOptions(opt) {
  2440. this.defaults = { ...this.defaults, ...opt };
  2441. return this;
  2442. }
  2443. #parseMarkdown(lexer, parser) {
  2444. return (src, optOrCallback, callback) => {
  2445. if (typeof optOrCallback === 'function') {
  2446. callback = optOrCallback;
  2447. optOrCallback = null;
  2448. }
  2449. const origOpt = { ...optOrCallback };
  2450. const opt = { ...this.defaults, ...origOpt };
  2451. const throwError = this.#onError(!!opt.silent, !!opt.async, callback);
  2452. // throw error in case of non string input
  2453. if (typeof src === 'undefined' || src === null) {
  2454. return throwError(new Error('marked(): input parameter is undefined or null'));
  2455. }
  2456. if (typeof src !== 'string') {
  2457. return throwError(new Error('marked(): input parameter is of type '
  2458. + Object.prototype.toString.call(src) + ', string expected'));
  2459. }
  2460. checkDeprecations(opt, callback);
  2461. if (opt.hooks) {
  2462. opt.hooks.options = opt;
  2463. }
  2464. if (callback) {
  2465. const resultCallback = callback;
  2466. const highlight = opt.highlight;
  2467. let tokens;
  2468. try {
  2469. if (opt.hooks) {
  2470. src = opt.hooks.preprocess(src);
  2471. }
  2472. tokens = lexer(src, opt);
  2473. }
  2474. catch (e) {
  2475. return throwError(e);
  2476. }
  2477. const done = (err) => {
  2478. let out;
  2479. if (!err) {
  2480. try {
  2481. if (opt.walkTokens) {
  2482. this.walkTokens(tokens, opt.walkTokens);
  2483. }
  2484. out = parser(tokens, opt);
  2485. if (opt.hooks) {
  2486. out = opt.hooks.postprocess(out);
  2487. }
  2488. }
  2489. catch (e) {
  2490. err = e;
  2491. }
  2492. }
  2493. opt.highlight = highlight;
  2494. return err
  2495. ? throwError(err)
  2496. : resultCallback(null, out);
  2497. };
  2498. if (!highlight || highlight.length < 3) {
  2499. return done();
  2500. }
  2501. delete opt.highlight;
  2502. if (!tokens.length)
  2503. return done();
  2504. let pending = 0;
  2505. this.walkTokens(tokens, (token) => {
  2506. if (token.type === 'code') {
  2507. pending++;
  2508. setTimeout(() => {
  2509. highlight(token.text, token.lang, (err, code) => {
  2510. if (err) {
  2511. return done(err);
  2512. }
  2513. if (code != null && code !== token.text) {
  2514. token.text = code;
  2515. token.escaped = true;
  2516. }
  2517. pending--;
  2518. if (pending === 0) {
  2519. done();
  2520. }
  2521. });
  2522. }, 0);
  2523. }
  2524. });
  2525. if (pending === 0) {
  2526. done();
  2527. }
  2528. return;
  2529. }
  2530. if (opt.async) {
  2531. return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)
  2532. .then(src => lexer(src, opt))
  2533. .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)
  2534. .then(tokens => parser(tokens, opt))
  2535. .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)
  2536. .catch(throwError);
  2537. }
  2538. try {
  2539. if (opt.hooks) {
  2540. src = opt.hooks.preprocess(src);
  2541. }
  2542. const tokens = lexer(src, opt);
  2543. if (opt.walkTokens) {
  2544. this.walkTokens(tokens, opt.walkTokens);
  2545. }
  2546. let html = parser(tokens, opt);
  2547. if (opt.hooks) {
  2548. html = opt.hooks.postprocess(html);
  2549. }
  2550. return html;
  2551. }
  2552. catch (e) {
  2553. return throwError(e);
  2554. }
  2555. };
  2556. }
  2557. #onError(silent, async, callback) {
  2558. return (e) => {
  2559. e.message += '\nPlease report this to https://github.com/markedjs/marked.';
  2560. if (silent) {
  2561. const msg = '<p>An error occurred:</p><pre>'
  2562. + escape(e.message + '', true)
  2563. + '</pre>';
  2564. if (async) {
  2565. return Promise.resolve(msg);
  2566. }
  2567. if (callback) {
  2568. callback(null, msg);
  2569. return;
  2570. }
  2571. return msg;
  2572. }
  2573. if (async) {
  2574. return Promise.reject(e);
  2575. }
  2576. if (callback) {
  2577. callback(e);
  2578. return;
  2579. }
  2580. throw e;
  2581. };
  2582. }
  2583. }
  2584. const markedInstance = new Marked();
  2585. function marked(src, opt, callback) {
  2586. return markedInstance.parse(src, opt, callback);
  2587. }
  2588. /**
  2589. * Sets the default options.
  2590. *
  2591. * @param options Hash of options
  2592. */
  2593. marked.options =
  2594. marked.setOptions = function (options) {
  2595. markedInstance.setOptions(options);
  2596. marked.defaults = markedInstance.defaults;
  2597. changeDefaults(marked.defaults);
  2598. return marked;
  2599. };
  2600. /**
  2601. * Gets the original marked default options.
  2602. */
  2603. marked.getDefaults = _getDefaults;
  2604. marked.defaults = exports.defaults;
  2605. /**
  2606. * Use Extension
  2607. */
  2608. marked.use = function (...args) {
  2609. markedInstance.use(...args);
  2610. marked.defaults = markedInstance.defaults;
  2611. changeDefaults(marked.defaults);
  2612. return marked;
  2613. };
  2614. /**
  2615. * Run callback for every token
  2616. */
  2617. marked.walkTokens = function (tokens, callback) {
  2618. return markedInstance.walkTokens(tokens, callback);
  2619. };
  2620. /**
  2621. * Compiles markdown to HTML without enclosing `p` tag.
  2622. *
  2623. * @param src String of markdown source to be compiled
  2624. * @param options Hash of options
  2625. * @return String of compiled HTML
  2626. */
  2627. marked.parseInline = markedInstance.parseInline;
  2628. /**
  2629. * Expose
  2630. */
  2631. marked.Parser = _Parser;
  2632. marked.parser = _Parser.parse;
  2633. marked.Renderer = _Renderer;
  2634. marked.TextRenderer = _TextRenderer;
  2635. marked.Lexer = _Lexer;
  2636. marked.lexer = _Lexer.lex;
  2637. marked.Tokenizer = _Tokenizer;
  2638. marked.Slugger = _Slugger;
  2639. marked.Hooks = _Hooks;
  2640. marked.parse = marked;
  2641. const options = marked.options;
  2642. const setOptions = marked.setOptions;
  2643. const use = marked.use;
  2644. const walkTokens = marked.walkTokens;
  2645. const parseInline = marked.parseInline;
  2646. const parse = marked;
  2647. const parser = _Parser.parse;
  2648. const lexer = _Lexer.lex;
  2649. exports.Hooks = _Hooks;
  2650. exports.Lexer = _Lexer;
  2651. exports.Marked = Marked;
  2652. exports.Parser = _Parser;
  2653. exports.Renderer = _Renderer;
  2654. exports.Slugger = _Slugger;
  2655. exports.TextRenderer = _TextRenderer;
  2656. exports.Tokenizer = _Tokenizer;
  2657. exports.getDefaults = _getDefaults;
  2658. exports.lexer = lexer;
  2659. exports.marked = marked;
  2660. exports.options = options;
  2661. exports.parse = parse;
  2662. exports.parseInline = parseInline;
  2663. exports.parser = parser;
  2664. exports.setOptions = setOptions;
  2665. exports.use = use;
  2666. exports.walkTokens = walkTokens;
  2667. }));
  2668. //# sourceMappingURL=marked.umd.js.map