marked.esm.js 76 KB

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