russross / blackfriday

Blackfriday: a markdown processor for Go
Other
5.42k stars 598 forks source link

Add AutoHeadingAnchorLinks extension #543

Open matt-allan opened 5 years ago

matt-allan commented 5 years ago

This PR adds an extension 'AutoHeadingAnchorLinks' that can be used to automatically add an anchor link to each header.

This is used to generate HTML similar to these examples:

It's a pretty common request for Hugo. I'm personally looking to add this feature to my Hugo site as well.

It's possible to workaround the issue with JavaScript or regex but an extension is a little easier and should be less likely to fail.

When the AutoHeadingAnchorLinks and AutoHeadingIDs extensions are enabled this markdown:

# First

Some text

## Second

...would create this HTML:

<h1 id="first"><a href="#first">#</a>First</h1>

<p>Some text</p>

<h2 id="second"><a href="#second">#</a>Second</h2>

It's possible to enable just the AutoHeadingAnchorLinks extension without the AutoHeadingIDs or HeadingIDs extension, it just generates links like <a href="#">#</a>. Not that you would want to do that but it doesn't break anything 😁.

My only concern with this extension is it seems pretty common to want to use a SVG instead of # for the link. It is possible to override this with CSS, i.e.

h1 > a, h2 > a, h3 > a, h4 > a, h5 > a, h6 > a {
  visibility: hidden;
}

h1 > a:before, h2 > a:before, h3 > a:before, h4 > a:before, h5 > a:before, h6 > a:before {
  visibility: visible;
  content: '🔗';
}
cbednarski commented 2 months ago

@matt-allan, thanks for the PR! I didn't see this at first, and ended up writing another PR that's almost identical. I've declined to submit it since yours is already here.

Since the project seems to have slowed down (and you may have moved on, too), I looked for another way to solve this.

I copied the approach that bfchroma used to add highlighting and wrote a custom renderer. This can live in your own code and obviates changing blackfriday.

If you (the general you) still need this, the code is here: https://gist.github.com/cbednarski/8dcc0c90890613f2b74008dc264bd14f