From 2da588598992065d7bf54a740d2011f8326d46cd Mon Sep 17 00:00:00 2001 From: Tony Brix Date: Sun, 24 Oct 2021 00:03:59 -0500 Subject: [PATCH] fix: walkTokens uses marked as this (#2251) --- docs/USING_PRO.md | 20 +++++++++++--------- src/marked.js | 6 +++--- test/unit/marked-spec.js | 12 ++++++++++++ 3 files changed, 26 insertions(+), 12 deletions(-) diff --git a/docs/USING_PRO.md b/docs/USING_PRO.md index 2ab33135cd..985a685dae 100644 --- a/docs/USING_PRO.md +++ b/docs/USING_PRO.md @@ -406,19 +406,21 @@ const description = { return `\n
${this.parser.parseInline(token.dt)}
${this.parser.parseInline(token.dd)}
`; }, childTokens: ['dt', 'dd'], // Any child tokens to be visited by walkTokens - walkTokens(token) { // Post-processing on the completed token tree - if (token.type === 'strong') { - token.text += ' walked'; - } - } }; -marked.use({ extensions: [descriptionlist, description] }); +function walkTokens(token) { // Post-processing on the completed token tree + if (token.type === 'strong') { + token.text += ' walked'; + token.tokens = this.Lexer.lexInline(token.text) + } +} +marked.use({ extensions: [descriptionlist, description], walkTokens }); -\\ EQUIVALENT TO: +// EQUIVALENT TO: -marked.use({extensions: [descriptionList] }); -marked.use({extensions: [description] }); +marked.use({ extensions: [descriptionList] }); +marked.use({ extensions: [description] }); +marked.use({ walkTokens }) console.log(marked('A Description List:\n' + ': Topic 1 : Description 1\n' diff --git a/src/marked.js b/src/marked.js index 80a2c9f7ca..1a8f31f6d6 100644 --- a/src/marked.js +++ b/src/marked.js @@ -235,10 +235,10 @@ marked.use = function(...args) { // ==-- Parse WalkTokens extensions --== // if (pack.walkTokens) { const walkTokens = marked.defaults.walkTokens; - opts.walkTokens = (token) => { + opts.walkTokens = function(token) { pack.walkTokens.call(this, token); if (walkTokens) { - walkTokens(token); + walkTokens.call(this, token); } }; } @@ -257,7 +257,7 @@ marked.use = function(...args) { marked.walkTokens = function(tokens, callback) { for (const token of tokens) { - callback(token); + callback.call(marked, token); switch (token.type) { case 'table': { for (const cell of token.header) { diff --git a/test/unit/marked-spec.js b/test/unit/marked-spec.js index 79fa151520..dd773c3744 100644 --- a/test/unit/marked-spec.js +++ b/test/unit/marked-spec.js @@ -1046,4 +1046,16 @@ br ['text', 'br'] ]); }); + + it('should asign marked to `this`', () => { + marked.use({ + walkTokens(token) { + if (token.type === 'em') { + token.text += ' walked'; + token.tokens = this.Lexer.lexInline(token.text); + } + } + }); + expect(marked('*text*').trim()).toBe('

text walked

'); + }); });