Showdown: Automatic anchor links

Created on 18 Feb 2017  路  4Comments  路  Source: showdownjs/showdown

Is there any way to add anchor links with showdown similar to Github READMEs?
ylhyu1hikk

help wanted

Most helpful comment

Not out of the box. But it's quite possible with an extension (check fiddle https://jsfiddle.net/tivie/knf9nb8f/)

// Extension
showdown.extension('header-anchors', function() {

    var ancTpl = '$1<a id="user-content-$3" class="anchor" href="#$3" aria-hidden="true"><svg aria-hidden="true" class="octicon octicon-link" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>$4';

  return [{
    type: 'html',
    regex: /(<h([1-3]) id="([^"]+?)">)(.*<\/h\2>)/g,
    replace: ancTpl
  }];
});

All 4 comments

Not out of the box. But it's quite possible with an extension (check fiddle https://jsfiddle.net/tivie/knf9nb8f/)

// Extension
showdown.extension('header-anchors', function() {

    var ancTpl = '$1<a id="user-content-$3" class="anchor" href="#$3" aria-hidden="true"><svg aria-hidden="true" class="octicon octicon-link" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>$4';

  return [{
    type: 'html',
    regex: /(<h([1-3]) id="([^"]+?)">)(.*<\/h\2>)/g,
    replace: ancTpl
  }];
});

@tivie thanks a lot!

Is this for anchor links that have a space?
I'm finding that all my single word anchors work automatically but not anchors with two or more words.

A prettier css with unnecessary space removed. Borrowed from GitHub css.

.anchor
{
    float: left;
    line-height: 1;
    margin-left: -20px;
    padding-right: 4px
}

h1 .anchor:focus,
h2 .anchor:focus,
h3 .anchor:focus
{
  outline: none
}

h1 .octicon-link,
h2 .octicon-link,
h3 .octicon-link
{
  color: #1b1f23;
  vertical-align: middle;
  visibility: hidden
}

h1:hover .anchor .octicon-link,
h2:hover .anchor .octicon-link,
h3:hover .anchor .octicon-link
{
  visibility: visible
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

andistuder picture andistuder  路  5Comments

JerryYangJin picture JerryYangJin  路  7Comments

geudrik picture geudrik  路  7Comments

oscarmorrison picture oscarmorrison  路  4Comments

reisraff picture reisraff  路  5Comments