marked.esm.js 72 KB

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