Repository: gohugoio/hugo (language: go)

Issue:
error calling Position: runtime error: slice bounds out of range [:-1]
hugo v0.94.0-DEV-B9A1BE2F+extended linux/amd64

The `.Position` method in a code block render hook throws this error:

> error calling Position: runtime error: slice bounds out of range [:-1]

It is triggered when the code block includes a nullified (I don't know what else to call it) shortcode reference.

markdown

````
```text
{{</* foo */>}}
```
````

layouts/_default/_markup/render-codeblock.html

```
{{ .Position }}
```

I ran across this while trying to document shortcode usage.



Discussion / hints:
Example

```bash
git clone --single-branch -b hugo-github-issue-9627 https://github.com/jmooring/hugo-testing hugo-github-issue-9627
cd hugo-github-issue-9627
hugo
```

Fix patch:
diff --git a/hugolib/page.go b/hugolib/page.go
index 175e1fc3b0c..c4f30de9dfb 100644
--- a/hugolib/page.go
+++ b/hugolib/page.go
@@ -784,6 +784,11 @@ func (p *pageState) posFromPage(offset int) text.Position {
 }
 
 func (p *pageState) posFromInput(input []byte, offset int) text.Position {
+	if offset < 0 {
+		return text.Position{
+			Filename: p.pathOrTitle(),
+		}
+	}
 	lf := []byte("\n")
 	input = input[:offset]
 	lineNumber := bytes.Count(input, lf) + 1


Test patch:
diff --git a/markup/goldmark/codeblocks/integration_test.go b/markup/goldmark/codeblocks/integration_test.go
index 1a70b0bf0ab..7362ef2976a 100644
--- a/markup/goldmark/codeblocks/integration_test.go
+++ b/markup/goldmark/codeblocks/integration_test.go
@@ -164,6 +164,43 @@ fmt.Println("Hello, World!");
 	)
 }
 
+func TestCodeblocksBugs(t *testing.T) {
+	t.Parallel()
+
+	files := `
+-- config.toml --
+-- layouts/_default/_markup/render-codeblock.html --
+{{ .Position | safeHTML }}
+-- layouts/_default/single.html --
+{{ .Content }}
+-- content/p1.md --
+---
+title: "p1"
+---
+
+## Issue 9627
+
+§§§text
+{{</* foo */>}}
+§§§
+
+`
+
+	b := hugolib.NewIntegrationTestBuilder(
+		hugolib.IntegrationTestConfig{
+			T:           t,
+			TxtarString: files,
+			NeedsOsFS:   false,
+		},
+	).Build()
+
+	b.AssertFileContent("public/p1/index.html", `
+# Issue 9627: For the Position in code blocks we try to match the .Inner with the original source. This isn't always possible.
+p1.md:0:0
+	`,
+	)
+}
+
 func TestCodeChomp(t *testing.T) {
 	t.Parallel()