From 3c568ad0139c79e5c0596ca40637512d71401afc Mon Sep 17 00:00:00 2001 From: satotake Date: Mon, 17 Feb 2020 22:59:26 +0900 Subject: markup/highlight: Fix chroma highlight * Use chroma.Coalesce * Escape code strings if lexer is nil Fixes #6877 Fixes #6856 --- markup/highlight/highlight.go | 4 +++- markup/highlight/highlight_test.go | 29 ++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/markup/highlight/highlight.go b/markup/highlight/highlight.go index 9e26aaf84..2bd77af0b 100644 --- a/markup/highlight/highlight.go +++ b/markup/highlight/highlight.go @@ -15,6 +15,7 @@ package highlight import ( "fmt" + gohtml "html" "io" "strings" @@ -63,7 +64,7 @@ func highlight(code, lang string, cfg Config) (string, error) { if lexer == nil { wrapper := getPreWrapper(lang) fmt.Fprint(w, wrapper.Start(true, "")) - fmt.Fprint(w, code) + fmt.Fprint(w, gohtml.EscapeString(code)) fmt.Fprint(w, wrapper.End(true)) return w.String(), nil } @@ -72,6 +73,7 @@ func highlight(code, lang string, cfg Config) (string, error) { if style == nil { style = styles.Fallback } + lexer = chroma.Coalesce(lexer) iterator, err := lexer.Tokenise(nil, code) if err != nil { diff --git a/markup/highlight/highlight_test.go b/markup/highlight/highlight_test.go index 6da292489..308679263 100644 --- a/markup/highlight/highlight_test.go +++ b/markup/highlight/highlight_test.go @@ -29,6 +29,13 @@ LINE3 LINE4 LINE5 ` + coalesceNeeded := `GET /foo HTTP/1.1 +Content-Type: application/json +User-Agent: foo + +{ + "hello": "world" +}` c.Run("Basic", func(c *qt.C) { cfg := DefaultConfig @@ -38,7 +45,7 @@ LINE5 result, _ := h.Highlight(`echo "Hugo Rocks!"`, "bash", "") c.Assert(result, qt.Equals, `
echo "Hugo Rocks!"
`) result, _ = h.Highlight(`echo "Hugo Rocks!"`, "unknown", "") - c.Assert(result, qt.Equals, `
echo "Hugo Rocks!"
`) + c.Assert(result, qt.Equals, `
echo "Hugo Rocks!"
`) }) @@ -106,4 +113,24 @@ LINE5 result, _ := h.Highlight(lines, "", "") c.Assert(result, qt.Contains, "2LINE2\n<") }) + + c.Run("No language, Escape HTML string", func(c *qt.C) { + cfg := DefaultConfig + cfg.NoClasses = false + h := New(cfg) + + result, _ := h.Highlight("Escaping less-than in code block? ", "", "") + c.Assert(result, qt.Contains, "<fail>") + }) + + c.Run("Highlight lines, default config", func(c *qt.C) { + cfg := DefaultConfig + cfg.NoClasses = false + h := New(cfg) + + result, _ := h.Highlight(coalesceNeeded, "http", "linenos=true,hl_lines=2") + c.Assert(result, qt.Contains, "hello") + c.Assert(result, qt.Contains, "}") + }) + } -- cgit v1.2.3