Skip to content

Customize id's of headers?  #515

@peteruithoven

Description

@peteruithoven

When using the id's of headers as anchors, the current id's conflict very quickly. It would be very nice to have an option to change the id's, so I can change the id's of h3's to "header2text/header3text" for example. DocumentUp currently does this, but in a very hacky way.
So I would like to for example,

## header2
### header3

parse into:

<h2 id="header2">header2</h2>
<h3 id="header2/header3">header3</h3>

How could this be implemented properly?

I can't simply override the header parser methods, because I'd need to add an extra token. I need to use a extra token because I need to specify the id per header. But currently the tok method selects a few properties and forwards only these to the specific renderer method, see:

Parser.prototype.tok = function() {
  switch (this.token.type) {
    ...
    case 'heading': {
      return this.renderer.heading(
        this.inline.output(this.token.text),
        this.token.depth,
        this.token.text);
    }
  ...
}

Another way would be to forward an id property from the token, and when it's given use this to overrule the regular id.

What I'd like to do:

function parse(markdown) {
  var current_h2 = null;
  tokens = marked.lexer(markdown)
  for(token in tokens) {
    if(token.type == "heading") {
      to_param = token.text.parameterize()
      if(token.depth == 2) {
        current_h2 = to_param;
      } else if (token.depth == 3) {
        token.id = '#{current_h2}/#{to_param}'
      }
    }
  }
  return marked.parser(tokens)
}

Maybe the system would be more flexible if the tokens where given to the render method, so I could fix this by overriding the heading method into something like:

var renderer = new marked.Renderer();
renderer.heading = function(tokens) {
  return '<h'
    + tokens.level
    + ' id="'
    + this.options.headerPrefix
    + tokens.id.toLowerCase().replace(/[^\w]+/g, '-')
    + '">'
    + tokens.text
    + '</h'
    + tokens.level
    + '>\n';
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions