From 0d2ac1dd57927910480fe0288f7ef5f35da476a2 Mon Sep 17 00:00:00 2001 From: hypengw Date: Fri, 16 Jan 2026 09:40:38 +0800 Subject: [PATCH] ParseAttributes for image --- README.md | 2 +- _test/options.txt | 10 ++++++++++ ast/inline.go | 1 + parser/link.go | 9 +++++++++ 4 files changed, 21 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cbf1eba6..1c8557c3 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ Parser and Renderer options ### Attributes The `parser.WithAttribute` option allows you to define attributes on some elements. -Currently only headings support attributes. +Currently only headings,images support attributes. **Attributes are being discussed in the [CommonMark forum](https://talk.commonmark.org/t/consistent-attribute-syntax/272). diff --git a/_test/options.txt b/_test/options.txt index 3137b657..bf9d619d 100644 --- a/_test/options.txt +++ b/_test/options.txt @@ -76,3 +76,13 @@ //- - - - - - - - -//

Test

//= = = = = = = = = = = = = = = = = = = = = = = =// + +8: image with attributes +//- - - - - - - - -// +![img](https://url.test){ width="400" } +![img](https://url.test) { width="400" height="400" } +//- - - - - - - - -// +

img +img

+//= = = = = = = = = = = = = = = = = = = = = = = =// + diff --git a/ast/inline.go b/ast/inline.go index 613eb1ed..4789359d 100644 --- a/ast/inline.go +++ b/ast/inline.go @@ -443,6 +443,7 @@ func NewImage(link *Link) *Image { } c.Destination = link.Destination c.Title = link.Title + c.attributes = link.attributes for n := link.FirstChild(); n != nil; { next := n.NextSibling() link.RemoveChild(link, n) diff --git a/parser/link.go b/parser/link.go index 7390d7be..eab13cc8 100644 --- a/parser/link.go +++ b/parser/link.go @@ -168,6 +168,14 @@ func (s *linkParser) Parse(parent ast.Node, block text.Reader, pc Context) ast.N var hasValue bool if c == '(' { // normal link link = s.parseLink(parent, last, block, pc) + if last.IsImage { + attrs, ok := ParseAttributes(block) + if ok { + for _, attr := range attrs { + link.SetAttribute(attr.Name, attr.Value) + } + } + } } else if c == '[' { // reference link link, hasValue = s.parseReferenceLink(parent, last, block, pc) if link == nil && hasValue { @@ -324,6 +332,7 @@ func (s *linkParser) parseLink(parent ast.Node, last *linkLabelState, block text } link := ast.NewLink() + s.processLinkLabel(parent, link, last, pc) link.Destination = destination link.Title = title