Home

ugit @0db8cc06a5f78185567f8f311d719f0c4304dd48 - refs - log -
-
https://git.jolheiser.com/ugit.git
The code powering this h*ckin' site
ugit / internal / html / markup / chroma.go
- raw
 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
package markup

import (
	"io"

	"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 is the default formatter
	Formatter = html.New(
		html.WithLineNumbers(true),
		html.WithLinkableLineNumbers(true, "L"),
		html.WithClasses(true),
		html.LineNumbersInTable(true),
	)
	basicFormatter = html.New(
		html.WithClasses(true),
	)
	// Code is the entrypoint for formatting
	Code = code{}
)

type code struct{}

func setup(source []byte, fileName string) (chroma.Iterator, *chroma.Style, error) {
	lexer := lexers.Match(fileName)
	if lexer == nil {
		lexer = lexers.Fallback
	}
	lexer = chroma.Coalesce(lexer)

	style := styles.Get("catppuccin-mocha")
	if style == nil {
		style = styles.Fallback
	}

	iter, err := lexer.Tokenise(nil, string(source))
	if err != nil {
		return nil, nil, err
	}

	return iter, style, nil
}

// Basic formats code without any extras
func (c code) Basic(source []byte, fileName string, writer io.Writer) error {
	iter, style, err := setup(source, fileName)
	if err != nil {
		return err
	}
	return basicFormatter.Format(writer, style, iter)
}

// Convert formats code with line numbers, links, etc.
func (c code) Convert(source []byte, fileName string, writer io.Writer) error {
	iter, style, err := setup(source, fileName)
	if err != nil {
		return err
	}
	return Formatter.Format(writer, style, iter)
}

// Snippet formats code with line numbers starting at a specific line
func Snippet(source []byte, fileName string, line int, writer io.Writer) error {
	iter, style, err := setup(source, fileName)
	if err != nil {
		return err
	}
	formatter := html.New(
		html.WithLineNumbers(true),
		html.WithClasses(true),
		html.LineNumbersInTable(true),
		html.BaseLineNumber(line),
	)
	return formatter.Format(writer, style, iter)
}