~gitpocket/gitpocket

4
67f37ad5a2fec2b77e0047a434c3dc21a62667ff
mainfeed-discovery
gitpocket/highlight.go -rw-r--r--1.2 KiB ViewLogBlameView rawPermalink 2d63c31406 feat(basin): squash and rebase merges, collaborators, quota 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
52
53
54
55
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("pygments")

func highlightLimited(name string, content []byte) (template.HTML, bool) {
	if len(content) > maxHighlight {
		return "", false
	}
	return highlight(name, content)
}

func highlight(name string, content []byte) (template.HTML, bool) {
	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()
}