showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
highlight.go
2.7 KB · 92 lines
1package render23import (4 "html/template"5 "strings"67 "github.com/alecthomas/chroma/v2"8 "github.com/alecthomas/chroma/v2/lexers"9)1011// Highlight tokenises src with chroma and returns one HTML string per line.12// Tokens get saturn's hl-<role> classes, so the palette CSS applies and no13// inline styles are needed. name picks the lexer; lang, if set, wins.14func Highlight(name, lang, src string) []template.HTML {15 var lx chroma.Lexer16 if lang != "" {17 lx = lexers.Get(lang)18 }19 if lx == nil {20 lx = lexers.Match(name)21 }22 if lx == nil && name != "" {23 lx = lexers.Analyse(src)24 }25 if lx == nil {26 lx = lexers.Fallback27 }28 src = strings.TrimSuffix(strings.TrimSuffix(src, "\n"), "\r") // the last line's ending29 it, err := chroma.Coalesce(lx).Tokenise(nil, src)30 if err != nil {31 it = chroma.Literator(chroma.Token{Type: chroma.Text, Value: src})32 }33 var lines []template.HTML34 for _, line := range chroma.SplitTokensIntoLines(it.Tokens()) {35 var b strings.Builder36 for _, t := range line {37 v := template.HTMLEscapeString(strings.TrimSuffix(t.Value, "\n"))38 if r := role(t.Type); r != "" && v != "" {39 b.WriteString(`<span class="hl-` + r + `">` + v + `</span>`)40 } else {41 b.WriteString(v)42 }43 }44 lines = append(lines, template.HTML(b.String()))45 }46 if strings.HasSuffix(src, "\n") { // chroma drops the empty line after a final newline47 lines = append(lines, "")48 }49 return lines50}5152// role maps a chroma token type to one of saturn's syntax roles, following53// the scopes in saturn's scripts/highlight.mjs.54func role(t chroma.TokenType) string {55 switch t {56 case chroma.KeywordConstant, chroma.NameConstant, chroma.NameDecorator, chroma.NameEntity:57 return "constant"58 case chroma.KeywordType, chroma.NameClass, chroma.NameException, chroma.NameNamespace:59 return "type"60 case chroma.NameBuiltinPseudo:61 return "self"62 case chroma.NameBuiltin:63 return "builtin"64 case chroma.NameFunction, chroma.NameFunctionMagic:65 return "function"66 case chroma.NameTag, chroma.NameAttribute, chroma.NameProperty:67 return "variable"68 case chroma.LiteralStringEscape, chroma.LiteralStringRegex, chroma.LiteralStringInterpol:69 return "escape"70 case chroma.GenericInserted:71 return "added"72 case chroma.GenericDeleted:73 return "removed"74 case chroma.GenericHeading, chroma.GenericSubheading:75 return "heading"76 }77 switch {78 case t.InCategory(chroma.Comment):79 return "comment"80 case t.InCategory(chroma.Keyword):81 return "keyword"82 case t.InSubCategory(chroma.NameVariable):83 return "variable"84 case t.InSubCategory(chroma.LiteralString):85 return "string"86 case t.InSubCategory(chroma.LiteralNumber):87 return "constant"88 case t.InCategory(chroma.Operator), t.InCategory(chroma.Punctuation):89 return "punct"90 }91 return ""92}