Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Building an extension but it doesn't act as excepted. #2737

Closed
Antonio225t opened this issue Feb 17, 2023 · 3 comments
Closed

Building an extension but it doesn't act as excepted. #2737

Antonio225t opened this issue Feb 17, 2023 · 3 comments

Comments

@Antonio225t
Copy link

Antonio225t commented Feb 17, 2023

Marked version: 4.2.12

Markdown flavor: n/a (?)

I tried to add an extension like this:

marked.use({
  extensions: [
    {
      name: "underline",
      level: "inline",
      start: (src) => {
        return src.match(/__(.*?)__/)?.index;
      },
      tokenizer(src, tokens) {
        var match = src.match(/__(.*?)__/);
        if (match) {
          var token = {
            type: "underline",
            raw: match[0],
            text: this.lexer.inlineTokens(match[1].trim(), [])
          };
          return token;
        }
      },
      renderer(token) {
        return `<u>${this.parser.parseInline(token.text, null)}</u>`;
      },
    }
  ]
});

var md = `
# Header
**This** is a normal text writted in \`JavaScript\` for \`Marked\`.
__test__
`;
marked.parse(md);

For supporting underline in Marked. But for some reasons it didn't work. Can someone explain what I did wrong? Thanks.

Expectation

<h1>Header</h1>
<p><strong>This</strong> is a normal text writted in <code>JavaScript</code> for <code>Marked</code>.
<u>test</u></p>

Result

<h1>Header</h1>
<p><u>test</u><u>test</u><u>test</u><u>test</u><u>test</u><u>test</u><u>test</u><u>test</u><u>test</u></p>

What was attempted

Before making this issue I attempt to looking some source codes of other extensions of Marked but it did not help. Plus I took a look at the documentation but still no luck. I tried fixing the RegEx in RegExR but it seems good. I probably didn't understand something and did a mistake in the tokenizer section but I don't know what it is, can someone help me please? Thanks in advance 👍.

@calculuschild
Copy link
Contributor

calculuschild commented Feb 17, 2023

One common mistake: you need to add a ^ to the start of your Tokenizer match regex (but not the "start" match regex).

Otherwise the Tokenizer will start finding your underline tokens way out in the middle of your document before handling earlier tokens first, and your resulting output becomes out of order or duplicated.

@Antonio225t
Copy link
Author

Thank you, I'll try it now

@Antonio225t
Copy link
Author

This worked. Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants