diff --git a/block.go b/block.go index dcd61e6..f9a026a 100644 --- a/block.go +++ b/block.go @@ -260,9 +260,19 @@ func (p *Markdown) prefixHeading(data []byte) int { if id == "" && p.extensions&AutoHeadingIDs != 0 { id = SanitizedAnchorName(string(data[i:end])) } + block := p.addBlock(Heading, data[i:end]) block.HeadingID = id block.Level = level + + if p.extensions&AutoHeadingAnchorLinks != 0 { + link := NewNode(Link) + link.Destination = []byte("#" + id) + linkText := NewNode(Text) + linkText.Literal = []byte("#") + link.AppendChild(linkText) + block.AppendChild(link) + } } return skip } diff --git a/block_test.go b/block_test.go index c339dee..7ebe443 100644 --- a/block_test.go +++ b/block_test.go @@ -1916,3 +1916,36 @@ func TestSanitizedAnchorName(t *testing.T) { } } } + +func TestPrefixHeaderAnchorLinksExtension(t *testing.T) { + t.Parallel() + var tests = []string{ + "# Header 1\n", + "

#Header 1

\n", + + "# Header 1 \n", + "

#Header 1

\n", + + "## Header 2\n", + "

#Header 2

\n", + + "### Header 3\n", + "

#Header 3

\n", + + "#### Header 4\n", + "

#Header 4

\n", + + "##### Header 5\n", + "
#Header 5
\n", + + "###### Header 6\n", + "
#Header 6
\n", + + "####### Header 7\n", + "
## Header 7
\n", + + "Hello\n# Header 1\nGoodbye\n", + "

Hello

\n\n

#Header 1

\n\n

Goodbye

\n", + } + doTestsBlock(t, tests, AutoHeadingIDs|AutoHeadingAnchorLinks) +} diff --git a/markdown.go b/markdown.go index 58d2e45..281a5c1 100644 --- a/markdown.go +++ b/markdown.go @@ -47,6 +47,7 @@ const ( AutoHeadingIDs // Create the heading ID from the text BackslashLineBreak // Translate trailing backslashes into line breaks DefinitionLists // Render definition lists + AutoHeadingAnchorLinks // Create anchor links for headings CommonHTMLFlags HTMLFlags = UseXHTML | Smartypants | SmartypantsFractions | SmartypantsDashes | SmartypantsLatexDashes