Add Anchor Links to Hugo Headings

Hugo already gives rendered headings an id. With one template change, the heading text itself can link to that ID, making it easy to copy a URL for a particular section.

Replace {{ .Content }} in the default single-page layout with this expression:

{{ .Content | replaceRE "(<h[1-6]\\sid=\"([^\"]+)\"\\s?>)(.+)(</h[1-6]+>)" "${1}<a href=\"#${2}\">${3}</a>${4}" | safeHTML }}

The regular expression captures the opening heading tag, its id, the heading text, and the closing tag. replaceRE then wraps the text in an anchor pointing back to that ID.

safeHTML is needed because the replacement creates HTML rather than plain text. That also means I would use this only with content I trust. Regular expressions and generated HTML are a compact solution here, but they are not a general-purpose HTML parser.