okami.mom/glamour

git clone https://git.nkp.pet/okami.mom/glamour

Ayman BagabasMerge pull request #408 from charmbracelet/v2-expcf874d7

main
1.4 KiB57 linesraw
1package main
2
3// This example illustrates how to render markdown and downsample colors when
4// necessary per the detected color profile of the terminal.
5
6import (
7	"bytes"
8	"embed"
9	"fmt"
10	"log"
11	"os"
12
13	"charm.land/glamour/v2"
14	"github.com/charmbracelet/colorprofile"
15)
16
17//go:embed artichokes.md
18var f embed.FS
19
20func main() {
21	// Open the file to learn a thing or two about artichokes.
22	f, err := f.Open("artichokes.md")
23	if err != nil {
24		fmt.Fprintf(os.Stderr, "Error opening file: %s\n", err)
25		os.Exit(1)
26	}
27	defer f.Close()
28
29	// Read the data.
30	var buf bytes.Buffer
31	if _, readErr := buf.ReadFrom(f); readErr != nil {
32		fmt.Fprintf(os.Stderr, "Error reading file: %s\n", readErr)
33		os.Exit(1)
34	}
35
36	// Create a new colorprofile writer. We'll use it to detect the color
37	// profile and downsample colors when necessary.
38	w := colorprofile.NewWriter(os.Stdout, os.Environ())
39
40	// While we're at it, let's jot down the detected color profile in the
41	// markdown output while we're at it.
42	fmt.Fprintf(&buf, "\n\nBy the way, this was rendererd as _%s._\n", w.Profile)
43
44	// Okay, now let's render some markdown.
45	r, err := glamour.NewTermRenderer(glamour.WithEnvironmentConfig())
46	if err != nil {
47		log.Fatal(err)
48	}
49	md, err := r.RenderBytes(buf.Bytes())
50	if err != nil {
51		log.Fatal(err)
52	}
53
54	// And finally, write it to stdout using the colorprofile writer. This will
55	// ensure colors are downsampled if necessary.
56	fmt.Fprintf(w, "%s\n", md)
57}