1package markdown
2
3import (
4	"os"
5	"strings"
6
7	"github.com/charmbracelet/glamour"
8)
9
10type RenderOpts []glamour.TermRendererOption
11
12func WithoutIndentation() glamour.TermRendererOption {
13	overrides := []byte(`
14	  {
15			"document": {
16				"margin": 0
17			},
18			"code_block": {
19				"margin": 0
20			}
21	  }`)
22
23	return glamour.WithStylesFromJSONBytes(overrides)
24}
25
26func WithoutWrap() glamour.TermRendererOption {
27	return glamour.WithWordWrap(0)
28}
29
30func render(text string, opts RenderOpts) (string, error) {
31	// Glamour rendering preserves carriage return characters in code blocks, but
32	// we need to ensure that no such characters are present in the output.
33	text = strings.ReplaceAll(text, "\r\n", "\n")
34
35	tr, err := glamour.NewTermRenderer(opts...)
36	if err != nil {
37		return "", err
38	}
39
40	return tr.Render(text)
41}
42
43func Render(text, style string) (string, error) {
44	opts := RenderOpts{
45		glamour.WithStylePath(style),
46		glamour.WithEmoji(),
47	}
48
49	return render(text, opts)
50}
51
52func RenderWithOpts(text, style string, opts RenderOpts) (string, error) {
53	defaultOpts := RenderOpts{
54		glamour.WithStylePath(style),
55		glamour.WithEmoji(),
56	}
57	opts = append(defaultOpts, opts...)
58
59	return render(text, opts)
60}
61
62func RenderWithBaseURL(text, style, baseURL string) (string, error) {
63	opts := RenderOpts{
64		glamour.WithStylePath(style),
65		glamour.WithEmoji(),
66		glamour.WithBaseURL(baseURL),
67	}
68
69	return render(text, opts)
70}
71
72func RenderWithWrap(text, style string, wrap int) (string, error) {
73	opts := RenderOpts{
74		glamour.WithStylePath(style),
75		glamour.WithEmoji(),
76		glamour.WithWordWrap(wrap),
77	}
78
79	return render(text, opts)
80}
81
82func GetStyle(defaultStyle string) string {
83	style := fromEnv()
84	if style != "" && style != "auto" {
85		return style
86	}
87
88	if defaultStyle == "light" || defaultStyle == "dark" {
89		return defaultStyle
90	}
91
92	return "notty"
93}
94
95var fromEnv = func() string {
96	return os.Getenv("GLAMOUR_STYLE")
97}
98