markedjs / marked

A markdown parser and compiler. Built for speed.
https://marked.js.org
Other
32.32k stars 3.36k forks source link

Can't seem to make inline extension work properly #3343

Closed ivanjaros closed 1 week ago

ivanjaros commented 1 week ago

I have an inline extension for rendering embedded links in [embed:URL] format.

const embed = {
  name: 'embed',
  level: 'inline',
  start(src) {
    const m = src.match(/\[embed\:.*\]/)
    return m ? m.index : null
  },
  tokenizer(src, tokens) {
    const rule = /\[embed\:(.*)\]/;
    const match = rule.exec(src);
    if (match) {
      return {
        type: "embed",
        raw: match[0],
        path: match[1].trim(),
      }
    }
  },
  renderer(token) {
    return '<script rel="embed" type="application/json">' + JSON.stringify({path: token.path}) + '</script>'
  }
};

For some reason it does not properly render content and it behaves in a way that takes length of preceding text and then renders suffix of the url of this length. Also in start() i never match the input. Simply strange behavior overall and am not sure what the issue is.

For example if I have embed 1: [embed:https://www.github.com] it will result in thub.com] being rendered as suffix after the token. In start() the src would then be hub.com].

I have made block extension before for an image gallery and that one works fine but the inline just behaves differently and I cannot figure out what to do with it. The documentation is quite lacking and there are no examples anywhere.

PS: in other words, it seems that what comes before the tag is lost, but the length of this "lost" content is then rendered AFTER as length of the original token. So it seems there is issue with offset or order.

ivanjaros commented 1 week ago

Here's the result obrázok

UziTech commented 1 week ago

Your rule matches anywhere in the string. Try adding ^ at the beginning so it will only match a token at the start of src

ivanjaros commented 1 week ago

Adding it to tokenizer() and start() patterns seem to fixed it. Thanks.