Repository: gohugoio/hugo (language: go)

Issue:
Retain newlines when overlaying text on images
Reference: <https://discourse.gohugo.io/t/render-markdown-with-newlines-in-shortcode/48684>

This simple approach to word wrapping eats newlines:

https://github.com/gohugoio/hugo/blob/b1de03f398620eb97e005ae01e1955627475b7c9/resources/images/text.go#L94-L103

Suggest something like this instead:

```go
// Draw text line by line, breaking each line at the maximum width.
f.text = strings.ReplaceAll(f.text, "\r", "")
for _, line := range strings.Split(f.text, "\n") {
	for _, str := range strings.Fields(line) {
		strWidth := font.MeasureString(face, str)
		if (d.Dot.X.Ceil() + strWidth.Ceil()) >= maxWidth {
			y = y + fontHeight + f.linespacing
			d.Dot = fixed.P(f.x, y)
		}
		d.DrawString(str + " ")
	}
	y = y + fontHeight + f.linespacing
	d.Dot = fixed.P(f.x, y)
}
```

This would allow you to overlay this:

```
{{ $text := "This is a list:\n\n1. Item one\n2. Item two" }}
```

With this result:

![good](https://github.com/gohugoio/hugo/assets/335669/f6323542-99df-415a-aea8-5a54d3c2dd8c)

Instead of this:

![bad](https://github.com/gohugoio/hugo/assets/335669/3e163952-ed28-41ca-86f7-2203a643deb1)








Discussion / hints:

Fix patch:
diff --git a/resources/images/text.go b/resources/images/text.go
index cc67a5d1d46..2d3370c6195 100644
--- a/resources/images/text.go
+++ b/resources/images/text.go
@@ -91,15 +91,19 @@ func (f textFilter) Draw(dst draw.Image, src image.Image, options *gift.Options)
 	y := f.y
 	d.Dot = fixed.P(f.x, f.y)
 
-	// Draw text and break line at max width
-	parts := strings.Fields(f.text)
-	for _, str := range parts {
-		strWith := font.MeasureString(face, str)
-		if (d.Dot.X.Ceil() + strWith.Ceil()) >= maxWidth {
-			y = y + fontHeight + f.linespacing
-			d.Dot = fixed.P(f.x, y)
+	// Draw text line by line, breaking each line at the maximum width.
+	f.text = strings.ReplaceAll(f.text, "\r", "")
+	for _, line := range strings.Split(f.text, "\n") {
+		for _, str := range strings.Fields(line) {
+			strWidth := font.MeasureString(face, str)
+			if (d.Dot.X.Ceil() + strWidth.Ceil()) >= maxWidth {
+				y = y + fontHeight + f.linespacing
+				d.Dot = fixed.P(f.x, y)
+			}
+			d.DrawString(str + " ")
 		}
-		d.DrawString(str + " ")
+		y = y + fontHeight + f.linespacing
+		d.Dot = fixed.P(f.x, y)
 	}
 }
 


Test patch: