marked.esm.js 73 KB

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