From 5b535eebe5750c075f2ca088737dbfe22a4b7d18 Mon Sep 17 00:00:00 2001 From: Darwin Wu Date: Wed, 21 Oct 2026 06:48:19 +0000 Subject: [PATCH] fix(links): match Asciidoctor's ids for anchored sections and listings sectionIDs accepted ids that Asciidoctor never generates, so a link to a missing section could pass rfdtool check: - A section whose block attributes or title set an id, as with [[values]] above it, gets that id instead of one from its title. sectionIDs added both. Block attributes apply across blank lines, as in Asciidoctor. - [[exporters]] in a TOML listing is text, not an anchor. sectionIDs read anchors in literal blocks, which it already skipped for section titles. It also missed an id shorthand after a style, as in [source#id] or [discrete#id], which it now accepts. Where it cannot tell, sectionIDs keeps an id rather than rejecting a valid link: listings that set subs= may render anchors, an anchor inside monospace text still renders, and a quoted attribute value that looks like an anchor does not take the section's title id away. Against asciidoctor.js 4.1.1 with the site settings, across the 24 Renga RFDs and 30 edge cases, main accepted 20 ids that do not exist and missed 3; this accepts 1 that does not exist, deliberately, and misses none. Amp-Thread-ID: https://ampcode.com/threads/T-01a15d15-bb12-7429-9794-374e145cd95e Co-authored-by: Amp --- internal/rfd/links.go | 130 +++++++++++++++++++++++++++++++++++-- internal/rfd/links_test.go | 31 +++++++++ 2 files changed, 156 insertions(+), 5 deletions(-) diff --git a/internal/rfd/links.go b/internal/rfd/links.go index ba67c94..477f775 100644 --- a/internal/rfd/links.go +++ b/internal/rfd/links.go @@ -178,25 +178,145 @@ func LinkMentions(text string, self int, exists func(int) bool) string { } // sectionIDs returns the ids a document's sections and anchors get, with the -// site's AsciiDoc settings: no prefix and "-" between words. +// site's AsciiDoc settings: no prefix and "-" between words. A section whose +// block attributes or title set an id gets that id instead of one from its +// title. Anchors in literal blocks, such as TOML tables in a listing, are +// text, unless the block turns substitutions on. When unsure, it keeps an id: +// accepting a link to a missing section is better than rejecting a valid one. func sectionIDs(text string) map[string]bool { ids := map[string]bool{} + lines := strings.Split(text, "\n") plainLines := strings.Split(prose(text), "\n") - for i, line := range strings.Split(text, "\n") { - if m := sectionTitle.FindStringSubmatch(line); m != nil && strings.TrimSpace(plainLines[i]) != "" { - ids[sectionID(m[1])] = true + literal := literalLines(lines) + anchored := false // the block attributes above this line set an id + for i, line := range lines { + if literal[i] { + anchored = false + continue } - for _, m := range explicitAnchor.FindAllStringSubmatch(line, -1) { + anchors := explicitAnchor.FindAllStringSubmatch(line, -1) + for _, m := range anchors { for _, id := range m[1:] { if id != "" { ids[strings.TrimSpace(id)] = true } } } + switch m := sectionTitle.FindStringSubmatch(line); { + case m != nil: + if strings.TrimSpace(plainLines[i]) != "" && !anchored && len(anchors) == 0 { + ids[sectionID(m[1])] = true + } + anchored = false + case blockAttributes.MatchString(line): + if id, ok := blockID(line); ok { + anchored = true + if id != "" { + ids[id] = true + } + } + case strings.TrimSpace(line) != "": + // Block attributes apply across blank lines, to the next block. + anchored = false + } } return ids } +var ( + // blockAttributes matches a line of block attributes, such as [[id]], + // [#id.role], or [source,toml], which apply to the block or section below. + blockAttributes = regexp.MustCompile(`^\[[^\]].*\][ \t]*$`) + // anchorLine matches a line of block anchors, such as [[id]] or + // [[id,text]][[other]]. + anchorLine = regexp.MustCompile(`^(?:\[\[[^\[\]]+\]\])+[ \t]*$`) + // substitutions matches a block attribute that sets substitutions. + substitutions = regexp.MustCompile(`\bsubs=`) +) + +// blockID reports whether a block attribute line gives the block below an +// id: [[id]], an id shorthand in the first attribute as in [#id] or +// [source#id], or id=. It returns the id, except for [[id]], whose ids +// explicitAnchor finds. Text that only looks like an anchor inside a quoted +// value, as in [role="[[x]]"], sets no id. +func blockID(line string) (string, bool) { + line = strings.TrimSpace(line) + if anchorLine.MatchString(line) { + return "", true + } + if strings.HasPrefix(line, "[[") { + return "", false + } + for i, attr := range splitAttributes(line[1 : len(line)-1]) { + attr = strings.TrimSpace(attr) + if id, ok := strings.CutPrefix(attr, "id="); ok && strings.Trim(id, `"'`) != "" { + return strings.Trim(id, `"'`), true + } + // Asciidoctor reads no shorthand from a value with spaces. + if i == 0 && !strings.ContainsAny(attr, "=\"' \t") { + if _, id, ok := strings.Cut(attr, "#"); ok { + // Roles (.) and options (%) may follow the id. + if i := strings.IndexAny(id, ".%"); i >= 0 { + id = id[:i] + } + if id != "" { + return id, true + } + } + } + } + return "", false +} + +// splitAttributes splits a block attribute list at the commas outside quotes. +func splitAttributes(list string) []string { + var out []string + start, quote := 0, rune(0) + for i, r := range list { + switch { + case quote != 0: + if r == quote { + quote = 0 + } + case r == '"' || r == '\'': + quote = r + case r == ',': + out = append(out, list[start:i]) + start = i + 1 + } + } + return append(out, list[start:]) +} + +// literalLines reports which lines are in literal blocks or their +// delimiters: listings, literals, comments, and passthroughs. Blocks whose +// attributes set substitutions, which can turn macros such as anchors on, are +// not literal here, except comments, which never render. +func literalLines(lines []string) []bool { + literal := make([]bool, len(lines)) + open, skip, attrs := "", false, "" + for i, line := range lines { + trimmed := strings.TrimSpace(line) + switch { + case open != "": + literal[i] = skip + if trimmed == open { + open = "" + } + case literalDelimiter.MatchString(line): + open = trimmed + skip = trimmed == "////" || !substitutions.MatchString(attrs) + literal[i] = skip + } + if blockAttributes.MatchString(line) && open == "" { + attrs += line + } else if trimmed != "" { + attrs = "" + } + } + return literal +} + // sectionID mirrors Asciidoctor's generated section ids with idprefix="" and // idseparator="-". func sectionID(title string) string { diff --git a/internal/rfd/links_test.go b/internal/rfd/links_test.go index f060403..bcebb4f 100644 --- a/internal/rfd/links_test.go +++ b/internal/rfd/links_test.go @@ -74,6 +74,37 @@ func TestSectionIDs(t *testing.T) { if ids["not-a-section"] { t.Errorf("listing text became a section: %v", ids) } + + // Ids as asciidoctor.js gives them with the site's settings. + for _, tt := range []struct { + name, text string + want, not []string + }{ + {"anchor replaces title id", "[[values]]\n=== Values and drift\n", []string{"values"}, []string{"values-and-drift"}}, + {"anchor across attributes", "[#ext]\n[role=wide]\n== Extension points\n", []string{"ext"}, []string{"extension-points"}}, + {"anchor across a blank line", "[[a]]\n\n== Blank between\n", []string{"a"}, []string{"blank-between"}}, + {"anchor on a paragraph", "[[p]]\nA paragraph.\n\n== Para before\n", []string{"p", "para-before"}, nil}, + {"anchor in the title", "== Title anchor [[ta]]\n", []string{"ta"}, []string{"title-anchor"}}, + {"id shorthand after a style", "[discrete#dd.role]\n== Discrete\n", []string{"dd"}, []string{"discrete"}}, + {"id attribute", "[id=\"sec\"]\n== Id attr\n", []string{"sec"}, []string{"id-attr"}}, + {"anchor in a quoted value", "[role=\"[[x]]\"]\n== Title\n", []string{"title"}, nil}, + {"anchor in monospace", "Use `[[x]]value` here.\n", []string{"x"}, nil}, + {"TOML in a listing", "[source,toml]\n----\n[[exporters]]\n----\n\n== After\n", []string{"after"}, []string{"exporters"}}, + {"listing with macros", "[subs=\"+macros\"]\n----\n[[x]]\n----\n\n== After\n", []string{"x", "after"}, nil}, + {"positional with a space", "[foo #bar]\n== Title\n", []string{"title"}, nil}, + } { + ids := sectionIDs("= RFD 1 Title\n\n" + tt.text) + for _, id := range tt.want { + if !ids[id] { + t.Errorf("%s: missing id %q in %v", tt.name, id, ids) + } + } + for _, id := range tt.not { + if ids[id] { + t.Errorf("%s: unexpected id %q in %v", tt.name, id, ids) + } + } + } } func TestWrapChanged(t *testing.T) {