Skip to content

Commit

Permalink
fix: walkTokens uses marked as this (#2251)
Browse files Browse the repository at this point in the history
  • Loading branch information
UziTech authored Oct 24, 2021
1 parent 40b33d0 commit 2da5885
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 12 deletions.
20 changes: 11 additions & 9 deletions docs/USING_PRO.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,19 +406,21 @@ const description = {
return `\n<dt>${this.parser.parseInline(token.dt)}</dt><dd>${this.parser.parseInline(token.dd)}</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'
Expand Down
6 changes: 3 additions & 3 deletions src/marked.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
};
}
Expand All @@ -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) {
Expand Down
12 changes: 12 additions & 0 deletions test/unit/marked-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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('<p><em>text walked</em></p>');
});
});

1 comment on commit 2da5885

@vercel
Copy link

@vercel vercel bot commented on 2da5885 Oct 24, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.