From 5a7d1dab8fb8afb02b4fee4e81073568e0a77bc3 Mon Sep 17 00:00:00 2001 From: Dave Rolsky Date: Fri, 10 Jan 2025 10:40:20 -0600 Subject: [PATCH] Handle fenced code block without a name Previously, this would panic on a plain fenced block like this: ``` Some text ``` Now it will try having the `lexers.Analyse` function pick a lexer. If that fails, it falls back to the "plaintext" lexer. --- pkg/parser.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/pkg/parser.go b/pkg/parser.go index fa56871..fc8dde0 100644 --- a/pkg/parser.go +++ b/pkg/parser.go @@ -10,6 +10,7 @@ import ( "regexp" "strings" + "github.com/alecthomas/chroma/v2" chroma_html "github.com/alecthomas/chroma/v2/formatters/html" "github.com/alecthomas/chroma/v2/lexers" "github.com/alecthomas/chroma/v2/styles" @@ -63,7 +64,15 @@ func renderHookCodeBlock(w io.Writer, node ast.Node, theme string) (ast.WalkStat return ast.GoToNext, true } - lexer := lexers.Get(string(block.Info)) + var lexer chroma.Lexer + if block.Info == nil { + lexer = lexers.Analyse(string(block.Literal)) + if lexer == nil { + lexer = lexers.Get("plaintext") + } + } else { + lexer = lexers.Get(string(block.Info)) + } iterator, _ := lexer.Tokenise(nil, string(block.Literal)) formatter := chroma_html.New(chroma_html.WithClasses(true)) err := formatter.Format(w, styles.Fallback, iterator)