diff --git a/extension/linkify.go b/extension/linkify.go index 0efe2ce..250666c 100644 --- a/extension/linkify.go +++ b/extension/linkify.go @@ -132,11 +132,53 @@ func (s *linkifyParser) CloseBlock(parent ast.Node, pc parser.Context) { type linkify struct { } +type linkifyASTTransformer struct { +} + +var defaultLinkifyASTTransformer = &linkifyASTTransformer{} + +// NewLinkifyASTTransformer returns a new parser.ASTTransformer that +// is related to AutoLink. +func NewLinkifyASTTransformer() parser.ASTTransformer { + return defaultLinkifyASTTransformer +} + +func (a *linkifyASTTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) { + var autoLinks []*ast.AutoLink + _ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) { + if entering { + if autoLink, ok := n.(*ast.AutoLink); ok { + autoLinks = append(autoLinks, autoLink) + } + } + return ast.WalkContinue, nil + + }) + for _, autoLink := range autoLinks { + nested := false + for p := autoLink.Parent(); p != nil; p = p.Parent() { + if _, ok := p.(*ast.Link); ok { + nested = true + break + } + } + if nested { + parent := autoLink.Parent() + parent.ReplaceChild(parent, autoLink, ast.NewString(autoLink.Label(reader.Source()))) + } + } +} + // Linkify is an extension that allow you to parse text that seems like a URL. var Linkify = &linkify{} func (e *linkify) Extend(m goldmark.Markdown) { - m.Parser().AddOptions(parser.WithInlineParsers( - util.Prioritized(NewLinkifyParser(), 999), - )) + m.Parser().AddOptions( + parser.WithInlineParsers( + util.Prioritized(NewLinkifyParser(), 999), + ), + parser.WithASTTransformers( + util.Prioritized(NewLinkifyASTTransformer(), 999), + ), + ) } diff --git a/extension/linkify_test.go b/extension/linkify_test.go index 040d1ab..1abefad 100644 --- a/extension/linkify_test.go +++ b/extension/linkify_test.go @@ -4,8 +4,8 @@ import ( "testing" "github.com/yuin/goldmark" - "github.com/yuin/goldmark/testutil" "github.com/yuin/goldmark/renderer/html" + "github.com/yuin/goldmark/testutil" ) func TestLinkify(t *testing.T) {