remarkjs / ideas

Share ideas for new utilities and tools built with @remarkjs
https://remark.js.org
5 stars 1 forks source link

Plugin to add automatic ids to headings #17

Closed iloveip closed 4 years ago

iloveip commented 4 years ago

Hi there,

Are there any plugins available to add automatic numbered id to headings? I know about https://github.com/remarkjs/remark-slug and https://github.com/imcuttle/remark-heading-id. But I would like to add numbered heading ids, without slugs, like #id1, #id2, etc. automatically.

wooorm commented 4 years ago

No, that does not exist, but you can create such as plugin yourself: https://github.com/unifiedjs/unifiedjs.github.io/blob/src/doc/learn/create-a-plugin.md

wooorm commented 4 years ago

Welcome btw! 👋 And: here’s some pseudocode that should do the trick:

var visit = require('unist-util-visit')

module.exports = numberedHeadingIds

function numberedHeadingIds() {
  return transformer
}

function transformer(ast) {
  var count = 1

  visit(ast, 'heading', visitor)

  function visitor(node) {
    var data = node.data || (node.data = {})
    var props = data.hProperties || (data.hProperties = {})

    props.id = 'heading-' + String(count)

    count++
  }
}
iloveip commented 4 years ago

Hi @wooorm, Thank you very much for your reply. I'm now working on this plugin. Could you please tell, how can I pass custom options to the plugin? I would like to be able to customize this part 'heading-'. If it's not set in the options, it will default to 'heading-'.

wooorm commented 4 years ago

See the Create a plugin guide for the basics of how to create plugins. However, it doesn’t mention options. But the docs in unifiedjs/unified for Plugin does show examples of options. Finally, a good way to learn is “View source” of existing plugins, for example, remark-external-links accepts options!

iloveip commented 4 years ago

Hi @wooorm,

Thank you very much for your help! I have published the plugin on npm. Here is the link to GitHub repository: remark-heading-autoid.

It supports automatic numbered ids and custom ids, for example:

## My Heading {#custom-id}

It's also possible to add a custom prefix for numbered ids. If it's not provided, then id, followed by the consecutive number of the heading, is used.

wooorm commented 4 years ago

That’s awesome Svetlana! ✨