~gitpocket/gitpocket

1
d5cfc6e983209bc916a951c045d4f801c32f6bab
mainfeed-discovery
gitpocket/highlight.go -rw-r--r--1.1 KiB ViewLogBlameView rawPermalink bfa87e353b feat(basin): failure based rate limits and size caps 1 months ago
 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
package main

import (
	"bytes"
	"html/template"
	"path/filepath"

	"github.com/alecthomas/chroma/v2"
	"github.com/alecthomas/chroma/v2/formatters/html"
	"github.com/alecthomas/chroma/v2/lexers"
	"github.com/alecthomas/chroma/v2/styles"
)

var formatter = html.New(
	html.WithClasses(true),
	html.WithLineNumbers(true),
	html.LineNumbersInTable(true),
	html.WithLinkableLineNumbers(true, "L"),
	html.TabWidth(4),
)

var highlightStyle = styles.Get("github")

func highlight(name string, content []byte) (template.HTML, bool) {
	if len(content) > 256<<10 {
		return "", false
	}
	lexer := lexers.Match(filepath.Base(name))
	if lexer == nil {
		lexer = lexers.Analyse(string(content))
	}
	if lexer == nil {
		return "", false
	}
	lexer = chroma.Coalesce(lexer)
	iterator, err := lexer.Tokenise(nil, string(content))
	if err != nil {
		return "", false
	}
	var buf bytes.Buffer
	if err := formatter.Format(&buf, highlightStyle, iterator); err != nil {
		return "", false
	}
	return template.HTML(buf.String()), true
}

func highlightCSS() []byte {
	var buf bytes.Buffer
	formatter.WriteCSS(&buf, highlightStyle)
	return buf.Bytes()
}