2021-04-22 09:14:51 +03:00
|
|
|
package m
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"strings"
|
|
|
|
|
2022-12-29 10:28:27 +03:00
|
|
|
"github.com/alecthomas/chroma/v2"
|
2021-04-22 09:14:51 +03:00
|
|
|
)
|
|
|
|
|
2024-01-01 14:52:47 +03:00
|
|
|
// Read and highlight some text using Chroma:
|
|
|
|
// https://github.com/alecthomas/chroma
|
2021-04-24 17:14:30 +03:00
|
|
|
//
|
2024-01-02 11:46:19 +03:00
|
|
|
// If lexer is nil no highlighting will be performed.
|
|
|
|
//
|
2021-05-13 08:37:34 +03:00
|
|
|
// Returns nil with no error if highlighting would be a no-op.
|
2024-01-01 14:52:47 +03:00
|
|
|
func highlight(text string, style chroma.Style, formatter chroma.Formatter, lexer chroma.Lexer) (*string, error) {
|
2021-04-22 09:14:51 +03:00
|
|
|
if lexer == nil {
|
2021-04-24 17:14:30 +03:00
|
|
|
// No highlighter available for this file type
|
2021-04-22 20:31:47 +03:00
|
|
|
return nil, nil
|
|
|
|
}
|
2021-04-22 23:05:36 +03:00
|
|
|
|
|
|
|
// FIXME: Can we test for the lexer implementation class instead? That
|
|
|
|
// should be more resilient towards this arbitrary string changing if we
|
|
|
|
// upgrade Chroma at some point.
|
2021-04-22 20:31:47 +03:00
|
|
|
if lexer.Config().Name == "plaintext" {
|
|
|
|
// This highlighter doesn't provide any highlighting, but not doing
|
|
|
|
// anything at all is cheaper and simpler, so we do that.
|
|
|
|
return nil, nil
|
2021-04-22 09:14:51 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// See: https://github.com/alecthomas/chroma#identifying-the-language
|
|
|
|
// FIXME: Do we actually need this? We should profile our reader performance
|
|
|
|
// with and without.
|
|
|
|
lexer = chroma.Coalesce(lexer)
|
|
|
|
|
2024-01-01 13:18:09 +03:00
|
|
|
iterator, err := lexer.Tokenise(nil, text)
|
2021-04-22 09:14:51 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var stringBuffer bytes.Buffer
|
2021-05-13 08:37:34 +03:00
|
|
|
err = formatter.Format(&stringBuffer, &style, iterator)
|
2021-04-22 09:14:51 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
highlighted := stringBuffer.String()
|
|
|
|
|
|
|
|
// If buffer ends with SGR Reset ("<ESC>[0m"), remove it. Chroma sometimes
|
|
|
|
// (always?) puts one of those by itself on the last line, making us believe
|
|
|
|
// there is one line too many.
|
|
|
|
sgrReset := "\x1b[0m"
|
|
|
|
trimmed := strings.TrimSuffix(highlighted, sgrReset)
|
|
|
|
|
|
|
|
return &trimmed, nil
|
|
|
|
}
|