-
Notifications
You must be signed in to change notification settings - Fork 2
/
highlighter.go
86 lines (77 loc) · 2.16 KB
/
highlighter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"log"
"math"
"strings"
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/styles"
)
var c = chroma.MustParseColour
// ColorMap associates termui color names with a respective chroma color
var ColorMap = map[string]chroma.Colour{
"red": c("#ff0000"),
"blue": c("#0000ff"),
"black": c("#000000"),
"cyan": c("#00ffff"),
"yellow": c("#ffff00"),
"white": c("#ffffff"),
"green": c("#00ff00"),
"magenta": c("#ff00ff"),
}
// Highlighter helps facilitate makefile syntax highlighting
type Highlighter struct {
style *chroma.Style
}
// NewHighlighter constructs a Highlighter and sets the style based on the given styleName
func NewHighlighter(styleName string) *Highlighter {
style := styles.Get(styleName)
if style == nil {
style = styles.Fallback
}
return &Highlighter{style}
}
// GetHighlightedContent iterates through the given content slice and returns it with inline style annotations
func (highlighter *Highlighter) GetHighlightedContent(content []string) []string {
lexer := lexers.Get("Base Makefile")
var highlightedContent []string
currentLine := ""
for _, line := range content {
iterator, err := lexer.Tokenise(nil, line)
tokens := iterator.Tokens()
if err != nil {
log.Fatal(err)
}
for _, token := range tokens {
entry := highlighter.style.Get(token.Type)
fg := "clear"
if entry.Colour.IsSet() {
fg = approximateColor(entry.Colour)
}
style := "fg:" + fg
if entry.Bold == chroma.Yes {
style += ",mod:bold"
} else if entry.Underline == chroma.Yes {
style += ",mod:underline"
}
currentLine += "[" + token.Value + "](" + style + ")"
}
// Remove any newline characters.
currentLine = strings.ReplaceAll(currentLine, "\n", "")
highlightedContent = append(highlightedContent, currentLine)
currentLine = ""
}
return highlightedContent
}
func approximateColor(color chroma.Colour) string {
lowestDistance := math.MaxFloat64
var bestColor string
for colorName, c := range ColorMap {
distance := color.Distance(c)
if distance < lowestDistance {
lowestDistance = distance
bestColor = colorName
}
}
return bestColor
}