package preview import ( "context" "fmt" "strings" "github.com/alecthomas/chroma/v2" "github.com/alecthomas/chroma/v2/lexers" "github.com/alecthomas/chroma/v2/styles" "vcom/internal/theme" ) // highlightInto fills Lines/Plain for text. The formatter writes SGR for // foreground colour, bold, italic and underline only — never a background // (no post-processing regexps). ctx is checked every 256 tokens. func highlightInto(ctx context.Context, req Request, res Result, name, src string) Result { plain, cut := textLines(src, req.MaxLines) res.Plain = plain res.Truncated = res.Truncated || cut n := min(req.HighlightLines, len(plain)) lines, err := Highlight(ctx, name, strings.Join(plain[:n], "\n"), req.Theme) if err != nil { res.Kind, res.Err = Error, err res.Lines, res.Plain = nil, nil return res } if len(lines) != n { lines, n = plain[:n], 0 // a lexer that changed the text: show it plain } res.Lines = make([]string, 0, len(plain)) res.Lines = append(append(res.Lines, lines...), plain[n:]...) res.Highlighted = n return res } // Highlight returns src (already normalised: LF, no tabs) as highlighted // lines for the given vcom theme. func Highlight(ctx context.Context, name, src, themeName string) ([]string, error) { lexer := lexers.Match(name) if lexer == nil { lexer = lexers.Analyse(src) } if lexer == nil { return strings.Split(src, "\n"), nil } lexer = chroma.Coalesce(lexer) style := styles.Get(theme.ChromaStyle(themeName)) it, err := lexer.Tokenise(nil, src) if err != nil { return nil, err } sgr := map[chroma.TokenType]string{} var lines []string var cur strings.Builder n := 0 for tok := it(); tok != chroma.EOF; tok = it() { if n++; n&255 == 0 { if err := ctx.Err(); err != nil { return nil, err } } code, ok := sgr[tok.Type] if !ok { code = sgrFor(style.Get(tok.Type)) sgr[tok.Type] = code } for i, seg := range strings.Split(tok.Value, "\n") { if i > 0 { lines = append(lines, cur.String()) cur.Reset() } if seg == "" { continue } if code != "" { cur.WriteString(code) cur.WriteString(seg) cur.WriteString("\x1b[0m") } else { cur.WriteString(seg) } } } lines = append(lines, cur.String()) return lines, nil } // sgrFor renders a style entry as a foreground-only SGR sequence. func sgrFor(e chroma.StyleEntry) string { var parts []string if e.Bold == chroma.Yes { parts = append(parts, "1") } if e.Italic == chroma.Yes { parts = append(parts, "3") } if e.Underline == chroma.Yes { parts = append(parts, "4") } if e.Colour.IsSet() { parts = append(parts, fmt.Sprintf("38;2;%d;%d;%d", e.Colour.Red(), e.Colour.Green(), e.Colour.Blue())) } if len(parts) == 0 { return "" } return "\x1b[" + strings.Join(parts, ";") + "m" }