Backtestshugorun-20261007-020926#14044

Issue #14044 Merged fix PR #15353 Run 7 Oct 2026 · run-20261007-020926 gohugoio/hugo

Automatic summary may generate invalid HTML with blockquotes and lists

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches fix the core bug the same way: after the word-count cutoff, they push the summary end forward until the open block elements are closed. Both add unit and integration tests for blockquotes and lists that would fail before the change and pass after it.

The main difference is correctness across markup formats.

**Patch A** tracks every non-void element, including `div` and `section`, for all formats. AsciiDoc output wraps entire sections in `div.sect1`/`div.sectionbody`, and Org output similarly nests whole sections in divs. Patch A would therefore stretch an AsciiDoc or Org summary to the end of the enclosing section, often most of the document. This is a likely regression for non-Markdown content. Patch A also relies on a hand-written HTML tag scanner. It handles comments, quoted attributes and raw-text elements, but it is a large amount of bespoke parsing code that adds maintenance risk. Finally, it rewrites the existing `BenchmarkSummaryFromHTML`, dropping its correctness assertions and replacing `b.Loop()` with `b.N`. That is unrelated churn that weakens existing coverage.

**Patch B** uses `golang.org/x/net/html`'s tokenizer, which is robust and already a Hugo dependency. It only tracks a curated set of block containers matching the elements listed in the issue's spec quote, plus raw-text elements. It deliberately treats `div`/`section` as containers only for Markdown and HTML, which avoids the AsciiDoc/RST/Org whole-section problem. Its tests cover several important cases:
- nested list and blockquote
- a div in Markdown
- a blockquote at the end of the document
- a `</p>` inside a script
- an RST document wrapper, showing that `WrapperStart`/`WrapperEnd` still work correctly

Its integration test also checks `Truncated` and `ContentWithoutSummary`.

Patch B's per-call map and tokenizer allocations are a minor performance cost. Overall, Patch B is the more correct and safer fix with better-targeted tests and no damage to existing tests.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

1h 11m

Wall-clock time in the container

Full test suite

No new failures

3,770 passed · 101 skipped · 3,873 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

130vs 226 merged

Changed lines, ours vs merged

<!--
Please do not use the issue queue for questions or troubleshooting. Unless you are certain that your issue is a software defect, use the forum:

https://discourse.gohugo.io
-->

<!-- Please answer these questions before submitting your issue. Thanks! -->

What version of Hugo are you using (hugo version)?

<pre>
$ hugo version
hugo v0.151.0+extended+withdeploy darwin/arm64 BuildDate=2025-10-02T13:30:36Z VendorInfo=brew
</pre>

Does this issue reproduce with the latest release?

Yes

Issue

Using a blockquote that extends past the .Summary cutoff causes the content below {{ .Summary }} to be treated as part of the blockquote until the end of the parent tag. Reproduction repo

<img width="848" height="652" alt="Image" src="https://github.com/user-attachments/assets/212f747c-af3c-4af5-89fe-78fe9dc04ebd" />

Hugo's .Summary may lead to blockquote end tag be below cutoff point

Explanation

In most modern browsers this html code will be parsed and rendered without errors

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
  <main>
    <blockquote>
      <p>1</p>
  </main>
</body>
</html>

Leading to shown in browser as a source

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
  <main>
    <blockquote>
      <p>1</p>
      <!-- This blockquote end tag was automatically inserted -->
    </blockquote>
  </main>
</body>
</html>

This is due to these parsing rules

An end tag whose tag name is one of: "address", "article", "aside", "blockquote", "button", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "main", "menu", "nav", "ol", "pre", "search", "section", "select", "summary", "ul"

If the stack of open elements does not have an element in scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, run these steps:

Generate implied end tags.

If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.

Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.

To Discuss

I think the best case scenario is for .Summary to handle generation of implied tags. But I am not sure how to do that myself.

For now I plan to provide a PR with fixes for a theme and docs, to avoid confusion and errors

The two patches

Our patch+129 −1
hugolib/page_test.goindex a50ff316b..e7762e3af 100644@@ -788,6 +788,47 @@ Content: {{ .Content }}| 		"Content: <p>This is <strong>summary</strong>.") } +// Issue 14044.+func TestSummaryAutoBlockquoteAndList(t *testing.T) {+	t.Parallel()+	b := Test(t, `+-- hugo.toml --+summaryLength = 2+-- content/blockquote.md --+---+title: Blockquote+---+> First quote.+>+> Second quote.++After quote.+-- content/list.md --+---+title: List+---+- First item.++  More first item.+- Second item.++After list.+-- layouts/single.html --+Summary: {{ .Summary }}|Truncated: {{ .Truncated }}|+ContentWithoutSummary: {{ .ContentWithoutSummary }}|+`)+	b.AssertFileContent("public/blockquote/index.html",+		"Summary: <blockquote>\n<p>First quote.</p>\n<p>Second quote.</p>\n</blockquote>|",+		"Truncated: true|",+		"ContentWithoutSummary: <p>After quote.</p>|",+	)+	b.AssertFileContent("public/list/index.html",+		"Summary: <ul>\n<li>\n<p>First item.</p>\n<p>More first item.</p>\n</li>\n<li>\n<p>Second item.</p>\n</li>\n</ul>|",+		"Truncated: true|",+		"ContentWithoutSummary: <p>After list.</p>|",+	)+}+ // #2973 func TestSummaryWithHTMLTagsOnNextLine(t *testing.T) { 	htesting.SkipSlowTestUnlessCI(t)resources/page/page_markup.goindex 8f58fc2ab..cc253ff42 100644@@ -25,6 +25,7 @@ import ( 	"github.com/gohugoio/hugo/markup/tableofcontents" 	"github.com/gohugoio/hugo/media" 	"github.com/gohugoio/hugo/tpl"+	"golang.org/x/net/html" )  type Content interface {@@ -234,9 +235,12 @@ func ExtractSummaryFromHTML(mt media.Type, input string, numWords int, isCJK boo 		}  		if count >= numWords {+			// Make sure we don't cut inside e.g. a blockquote or a list,+			// which would leave unclosed elements in the summary, see issue 14044.+			end := endOfEnclosingBlocks(mt, input, result.WrapperStart.High, j+closingIndex+len(ptag.tagName)+3, high) 			result.SummaryLowHigh = types.LowHigh[string]{ 				Low:  result.WrapperStart.High,-				High: j + closingIndex + len(ptag.tagName) + 3,+				High: end, 			} 			return 		}@@ -253,6 +257,81 @@ func ExtractSummaryFromHTML(mt media.Type, input string, numWords int, isCJK boo 	return } +// summaryBlockContainers are the block elements that we never want to split+// when creating an automatic summary.+var summaryBlockContainers = map[string]bool{+	"address":    true,+	"article":    true,+	"aside":      true,+	"blockquote": true,+	"details":    true,+	"dialog":     true,+	"dl":         true,+	"fieldset":   true,+	"figure":     true,+	"footer":     true,+	"header":     true,+	"main":       true,+	"nav":        true,+	"ol":         true,+	"table":      true,+	"ul":         true,+	// Raw text elements, which may contain a "</p>" that isn't a tag.+	"script":   true,+	"style":    true,+	"textarea": true,+}++// summaryBlockContainersStructural are block elements that some markup+// formats (e.g. AsciiDoc, reStructuredText and Org) use to wrap whole sections+// of the document, so we only treat them as containers for Markdown and HTML.+var summaryBlockContainersStructural = map[string]bool{+	"div":     true,+	"section": true,+}++// endOfEnclosingBlocks returns the position of the first top level element+// boundary in input[start:high] at or after pos, i.e. a position where none+// of the block containers opened after start are left open.+// If no such position exists, high is returned.+func endOfEnclosingBlocks(mt media.Type, input string, start, pos, high int) int {+	includeStructural := mt.SubType == media.DefaultContentTypes.Markdown.SubType || mt.SubType == media.DefaultContentTypes.HTML.SubType+	isContainer := func(name string) bool {+		return summaryBlockContainers[name] || (includeStructural && summaryBlockContainersStructural[name])+	}++	open := make(map[string]int)+	numOpen := 0+	offset := start+	z := html.NewTokenizer(strings.NewReader(input[start:high]))++	for {+		if offset >= pos && numOpen == 0 {+			return offset+		}+		tt := z.Next()+		if tt == html.ErrorToken {+			// io.EOF or malformed input; either way, use the rest of the content.+			return high+		}+		offset += len(z.Raw())+		switch tt {+		case html.StartTagToken:+			name, _ := z.TagName()+			if n := string(name); isContainer(n) {+				open[n]+++				numOpen+++			}+		case html.EndTagToken:+			name, _ := z.TagName()+			if n := string(name); open[n] > 0 {+				open[n]--+				numOpen--+			}+		}+	}+}+ // ExtractSummaryFromHTMLWithDivider extracts a summary from the given HTML content with // a manual summary divider. func ExtractSummaryFromHTMLWithDivider(mt media.Type, input, divider string) (result HtmlSummary) {resources/page/page_markup_test.goindex fc1102434..857863d81 100644@@ -40,6 +40,14 @@ func TestExtractSummaryFromHTML(t *testing.T) { 		{media.Builtin.MarkdownType, "<p>First paragraph</p><p>Second paragraph</p><p>Third paragraph</p>", false, 3, "<p>First paragraph</p><p>Second paragraph</p>", "<p>Third paragraph</p>"}, 		{media.Builtin.AsciiDocType, "<div><p>First paragraph</p></div><div><p>Second paragraph</p></div>", false, 2, "<div><p>First paragraph</p></div>", "<div><p>Second paragraph</p></div>"}, 		{media.Builtin.MarkdownType, "<p>这是中文,全中文</p><p>a这是中文,全中文</p>", true, 5, "<p>这是中文,全中文</p>", "<p>a这是中文,全中文</p>"},+		// Issue 14044: never cut inside a block container.+		{media.Builtin.MarkdownType, "<blockquote>\n<p>First paragraph</p>\n<p>Second paragraph</p>\n</blockquote>\n<p>Third paragraph</p>", false, 2, "<blockquote>\n<p>First paragraph</p>\n<p>Second paragraph</p>\n</blockquote>", "<p>Third paragraph</p>"},+		{media.Builtin.MarkdownType, "<p>First paragraph</p>\n<ul>\n<li><p>Item one</p></li>\n<li><p>Item two</p></li>\n</ul>\n<p>After list</p>", false, 3, "<p>First paragraph</p>\n<ul>\n<li><p>Item one</p></li>\n<li><p>Item two</p></li>\n</ul>", "<p>After list</p>"},+		{media.Builtin.MarkdownType, "<ol>\n<li>\n<blockquote>\n<p>Nested one</p>\n</blockquote>\n</li>\n<li><p>Nested two</p></li>\n</ol>\n<p>After</p>", false, 1, "<ol>\n<li>\n<blockquote>\n<p>Nested one</p>\n</blockquote>\n</li>\n<li><p>Nested two</p></li>\n</ol>", "<p>After</p>"},+		{media.Builtin.MarkdownType, "<div class=\"note\"><p>First paragraph</p><p>Second paragraph</p></div><p>Third paragraph</p>", false, 2, "<div class=\"note\"><p>First paragraph</p><p>Second paragraph</p></div>", "<p>Third paragraph</p>"},+		{media.Builtin.MarkdownType, "<blockquote>\n<p>First paragraph</p>\n<p>Second paragraph</p>\n</blockquote>", false, 2, "<blockquote>\n<p>First paragraph</p>\n<p>Second paragraph</p>\n</blockquote>", ""},+		{media.Builtin.MarkdownType, "<p>First paragraph</p><script>var s = \"</p>\";</script><p>Second paragraph</p>", false, 3, "<p>First paragraph</p><script>var s = \"</p>\";</script>", "<p>Second paragraph</p>"},+		{media.Builtin.ReStructuredTextType, "<div class=\"document\"><blockquote><p>First paragraph</p><p>Second paragraph</p></blockquote><p>Third paragraph</p></div>", false, 2, "<div class=\"document\"><blockquote><p>First paragraph</p><p>Second paragraph</p></blockquote></div>", "<div class=\"document\"><p>Third paragraph</p></div>"}, 	}  	for i, test := range tests { 
Merged fix · PR #15353+210 −16
hugolib/page_test.goindex a50ff316b..88a6b22f3 100644@@ -788,6 +788,36 @@ Content: {{ .Content }}| 		"Content: <p>This is <strong>summary</strong>.") } +// See issue 14044.+func TestSummaryAutoBalancesContainerTags(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ['home','rss','section','sitemap','taxonomy','term']+summaryLength = 1+-- content/p1.md --+---+title: p1+---+> foo+-- content/p2.md --+---+title: p2+---+- item 1 line 1++  item 1 line 2+-- layouts/page.html --+|{{ .Summary }}|+`++	b := Test(t, files)++	b.AssertFileContent("public/p1/index.html", "|<blockquote>\n<p>foo</p>\n</blockquote>|")+	b.AssertFileContent("public/p2/index.html", "|<ul>\n<li>\n<p>item 1 line 1</p>\n<p>item 1 line 2</p>\n</li>\n</ul>|")+}+ // #2973 func TestSummaryWithHTMLTagsOnNextLine(t *testing.T) { 	htesting.SkipSlowTestUnlessCI(t)resources/page/page_markup.goindex 8f58fc2ab..572822b0b 100644@@ -234,9 +234,11 @@ func ExtractSummaryFromHTML(mt media.Type, input string, numWords int, isCJK boo 		}  		if count >= numWords {+			summaryHigh := j + closingIndex + len(ptag.tagName) + 3+			summaryHigh = expandSummaryHighToBalancedHTML(input, result.WrapperStart.High, summaryHigh, high) 			result.SummaryLowHigh = types.LowHigh[string]{ 				Low:  result.WrapperStart.High,-				High: j + closingIndex + len(ptag.tagName) + 3,+				High: summaryHigh, 			} 			return 		}@@ -253,6 +255,167 @@ func ExtractSummaryFromHTML(mt media.Type, input string, numWords int, isCJK boo 	return } +// expandSummaryHighToBalancedHTML moves high forward until every element+// opened in input[low:high] is closed, so the summary does not end inside+// e.g. a blockquote or list item.+func expandSummaryHighToBalancedHTML(input string, low, high, maxHigh int) int {+	if low >= high || high >= maxHigh {+		return high+	}++	var buf [16]string+	stack := buf[:0]+	sc := htmlTagScanner{s: input, pos: low}++	for {+		name, end, ok := sc.next(high)+		if !ok {+			break+		}+		stack = pushOrPopHTMLStack(stack, name, end)+	}++	if len(stack) == 0 {+		return high+	}++	for {+		name, end, ok := sc.next(maxHigh)+		if !ok {+			return high+		}+		stack = pushOrPopHTMLStack(stack, name, end)+		if len(stack) == 0 {+			return sc.pos+		}+	}+}++func pushOrPopHTMLStack(stack []string, name string, end bool) []string {+	if end {+		for i := len(stack) - 1; i >= 0; i-- {+			if stack[i] == name {+				return stack[:i]+			}+		}+		return stack+	}+	if isVoidHTMLElement(name) {+		return stack+	}+	return append(stack, name)+}++// htmlTagScanner is a minimal, allocation-free scanner for start and end tags.+// It skips comments, quoted attribute values and raw text elements.+type htmlTagScanner struct {+	s   string+	pos int+}++// next returns the lowercased name of the next tag before limit and+// whether it is an end tag. ok is false when no more tags are found.+func (sc *htmlTagScanner) next(limit int) (name string, end, ok bool) {+	for {+		i := strings.IndexByte(sc.s[sc.pos:limit], '<')+		if i == -1 {+			sc.pos = limit+			return "", false, false+		}+		sc.pos += i + 1+		if sc.pos >= limit {+			return "", false, false+		}++		end = false+		switch c := sc.s[sc.pos]; c {+		case '!', '?':+			if strings.HasPrefix(sc.s[sc.pos:limit], "!--") {+				sc.skipPast(limit, "-->")+			} else {+				sc.skipPast(limit, ">")+			}+			continue+		case '/':+			end = true+			sc.pos+++		}++		start := sc.pos+		for sc.pos < limit && isHTMLTagNameByte(sc.s[sc.pos]) {+			sc.pos+++		}+		if sc.pos == start {+			continue+		}+		name = strings.ToLower(sc.s[start:sc.pos])++		selfClosing := false+		for sc.pos < limit {+			c := sc.s[sc.pos]+			sc.pos+++			switch c {+			case '"', '\'':+				sc.skipPast(limit, string(c))+			case '/':+				selfClosing = true+			case '>':+				if selfClosing {+					continue+				}+				if !end && isRawTextHTMLElement(name) {+					sc.skipPastEndTag(limit, name)+				}+				return name, end, true+			default:+				selfClosing = false+			}+		}+		return name, end, true+	}+}++func (sc *htmlTagScanner) skipPast(limit int, sep string) {+	if i := strings.Index(sc.s[sc.pos:limit], sep); i == -1 {+		sc.pos = limit+	} else {+		sc.pos += i + len(sep)+	}+}++func (sc *htmlTagScanner) skipPastEndTag(limit int, name string) {+	for {+		sc.skipPast(limit, "</")+		if sc.pos >= limit {+			return+		}+		if rest := sc.s[sc.pos:limit]; len(rest) > len(name) && strings.EqualFold(rest[:len(name)], name) && !isHTMLTagNameByte(rest[len(name)]) {+			sc.pos -= 2+			return+		}+	}+}++func isHTMLTagNameByte(c byte) bool {+	return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-'+}++func isRawTextHTMLElement(name string) bool {+	switch name {+	case "script", "style", "textarea", "title", "iframe", "xmp", "noembed", "noframes":+		return true+	}+	return false+}++func isVoidHTMLElement(name string) bool {+	switch name {+	case "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr":+		return true+	}+	return false+}+ // ExtractSummaryFromHTMLWithDivider extracts a summary from the given HTML content with // a manual summary divider. func ExtractSummaryFromHTMLWithDivider(mt media.Type, input, divider string) (result HtmlSummary) {resources/page/page_markup_test.goindex fc1102434..ee9fb1bbe 100644@@ -38,6 +38,14 @@ func TestExtractSummaryFromHTML(t *testing.T) { 		{media.Builtin.MarkdownType, "<p>First paragraph</p>", false, 10, "<p>First paragraph</p>", ""}, 		{media.Builtin.MarkdownType, "<p>First paragraph</p><p>Second paragraph</p>", false, 2, "<p>First paragraph</p>", "<p>Second paragraph</p>"}, 		{media.Builtin.MarkdownType, "<p>First paragraph</p><p>Second paragraph</p><p>Third paragraph</p>", false, 3, "<p>First paragraph</p><p>Second paragraph</p>", "<p>Third paragraph</p>"},+		{media.Builtin.MarkdownType, "<blockquote>\n<p>foo</p>\n</blockquote>\n<p>bar</p>", false, 1, "<blockquote>\n<p>foo</p>\n</blockquote>", "<p>bar</p>"},+		{media.Builtin.MarkdownType, "<ul>\n<li>\n<p>item 1 line 1</p>\n<p>item 1 line 2</p>\n</li>\n</ul>\n<p>bar</p>", false, 1, "<ul>\n<li>\n<p>item 1 line 1</p>\n<p>item 1 line 2</p>\n</li>\n</ul>", "<p>bar</p>"},+		{media.Builtin.HTMLType, "<div><p>foo</p></div><p>bar</p>", false, 1, "<div><p>foo</p></div>", "<p>bar</p>"},+		{media.Builtin.HTMLType, "<DIV><p>foo</p></DIV><p>bar</p>", false, 1, "<DIV><p>foo</p></DIV>", "<p>bar</p>"},+		{media.Builtin.HTMLType, "<div><!-- <span> --><p>foo</p></div><p>bar</p>", false, 1, "<div><!-- <span> --><p>foo</p></div>", "<p>bar</p>"},+		{media.Builtin.HTMLType, `<div><p title="a>b"><img src="x"/>foo</p></div><p>bar</p>`, false, 1, `<div><p title="a>b"><img src="x"/>foo</p></div>`, "<p>bar</p>"},+		{media.Builtin.HTMLType, "<div><script>var a = '<div>';</script><p>foo</p></div><p>bar</p>", false, 1, "<div><script>var a = '<div>';</script><p>foo</p></div>", "<p>bar</p>"},+		{media.Builtin.HTMLType, "<div><p>foo</p><p>bar</p>", false, 1, "<div><p>foo</p>", "<p>bar</p>"}, 		{media.Builtin.AsciiDocType, "<div><p>First paragraph</p></div><div><p>Second paragraph</p></div>", false, 2, "<div><p>First paragraph</p></div>", "<div><p>Second paragraph</p></div>"}, 		{media.Builtin.MarkdownType, "<p>这是中文,全中文</p><p>a这是中文,全中文</p>", true, 5, "<p>这是中文,全中文</p>", "<p>a这是中文,全中文</p>"}, 	}@@ -172,25 +180,18 @@ func TestIsProbablyHTMLToken(t *testing.T) { }  func BenchmarkSummaryFromHTML(b *testing.B) {--	input := "<p>First paragraph</p><p>Second paragraph</p>"--	for b.Loop() {-		summary := ExtractSummaryFromHTML(media.Builtin.MarkdownType, input, 2, false)-		if s := summary.Content(); s != input {-			b.Fatalf("unexpected content: %q", s)-		}-		if s := summary.ContentWithoutSummary(); s != "<p>Second paragraph</p>" {-			b.Fatalf("unexpected content without summary: %q", s)-		}-		if s := summary.Summary(); s != "<p>First paragraph</p>" {-			b.Fatalf("unexpected summary: %q", s)-		}+	run := func(name, input string) {+		b.Run(name, func(b *testing.B) {+			for i := 0; i < b.N; i++ {+				_ = ExtractSummaryFromHTML(media.Builtin.MarkdownType, input, 2, false)+			}+		}) 	}+	run("basic", "<p>First paragraph</p><p>Second paragraph</p>")+	run("list", "<ul>\n<li>\n<p>item 1 line 1</p>\n<p>item 1 line 2</p>\n</li>\n</ul>\n<p>bar</p>") }  func BenchmarkSummaryFromHTMLWithDivider(b *testing.B) {- 	input := "<p>First paragraph</p><p>FOOO</p><p>Second paragraph</p>"  	for b.Loop() {