Compare commits

..

12 commits

Author SHA1 Message Date
drew
f6846e85bc
fix: windows bug
Signed-off-by: drew <me@andrinoff.com>
2026-09-22 14:57:57 +04:00
drew
f0c1d7df3b
fix: ci
Signed-off-by: drew <me@andrinoff.com>
2026-09-22 14:45:15 +04:00
drew
a101777ad2
feat: svg support
Signed-off-by: drew <me@andrinoff.com>
2026-09-22 13:41:54 +04:00
drew
020ec9b5f8
fix: update glamour
Signed-off-by: drew <me@andrinoff.com>
2026-09-22 10:15:25 +04:00
drew
00f3db0962
fix: status line issues
Signed-off-by: drew <me@andrinoff.com>
2026-09-22 10:11:12 +04:00
drew
fa2b0f451e
many improvements
Signed-off-by: drew <me@andrinoff.com>
2026-09-21 16:00:50 +04:00
drew
3d557fb56b
chore: tidy
Signed-off-by: drew <me@andrinoff.com>
2026-09-14 15:41:37 +04:00
drew
bb61bd7590
chore: update glamour
Signed-off-by: drew <me@andrinoff.com>
2026-09-14 15:31:52 +04:00
drew
ac5b83d3c3
fix: test fails 2026-09-02 11:06:13 +04:00
drew
0214f4d6be
fix: windows compatability 2026-09-02 10:50:38 +04:00
drew
6911314131
pin to charmbracelet/glamour#598 2026-09-02 10:50:37 +04:00
drew
3cf39ac458
feat: image support 2026-09-02 10:50:36 +04:00
24 changed files with 1756 additions and 1101 deletions

View file

@ -22,4 +22,4 @@ jobs:
ruleguard:
uses: charmbracelet/meta/.github/workflows/ruleguard.yml@main
with:
go-version: "1.26"
go-version: 1.26.7

View file

@ -163,6 +163,33 @@ glow -w 60
CLI output can be displayed in your preferred pager with the `-p` flag. This defaults
to the ANSI-aware `less -r` if `$PAGER` is not explicitly set.
### Images
If your terminal supports the kitty graphics protocol (e.g. kitty, Ghostty,
WezTerm) or sixel, images in the document are rendered right in the terminal:
```bash
glow README.md
```
Support is detected automatically, both in the CLI and in the TUI pager, where
images scroll with the text. Images can be turned off with the `--images=false`
flag, or forced with the `GLOW_IMAGE_PROTOCOL` environment variable (`auto`,
`kitty`, `sixel`, or `none`).
Large images are automatically downscaled to what the terminal can actually
display before being transmitted, so even huge photos render quickly. Their
size can also be limited with `--image-max-rows` (default 20 terminal rows, 0
for no limit), or the `imageMaxRows` config key.
Images referenced by an `http(s)` URL are not loaded by default: fetching them
would reveal your IP address to the image's host, much like a tracking pixel
would. Instead, the URL is rendered as a link followed by a note saying the
image wasn't loaded. Set `loadRemoteImages: true` in your config (or
`GLOW_LOAD_REMOTE_IMAGES=true`) to fetch and render them. In the TUI the
document's text appears right away, and a spinner in the status bar spins while
the remote images are being fetched.
### Styles
You can choose a style with the `-s` flag. When no flag is provided `glow` tries
@ -213,6 +240,12 @@ all: false
showLineNumbers: false
# preserve newlines in the output
preserveNewLines: false
# render images when the terminal supports it (kitty or sixel graphics)
images: true
# maximum number of terminal rows an image may occupy (0 for no limit)
imageMaxRows: 20
# load images referenced by http(s) URLs, disabled to avoid leaking your IP
loadRemoteImages: false
```
## Contributing

View file

@ -23,6 +23,10 @@ pager: false
width: 80
# show all files, including hidden and ignored.
all: false
# load images over the network, i.e. from http(s) URLs. Disabled by default,
# as fetching them shares your IP address with the image's host. While
# disabled, remote images render as their URL with a note.
loadRemoteImages: false
`
var configCmd = &cobra.Command{

View file

@ -1,3 +1,4 @@
//go:build windows
// +build windows
package main

View file

@ -2,6 +2,9 @@ package main
import (
"testing"
"charm.land/glow/v3/ui"
"github.com/caarlos0/env/v11"
)
func TestGlowFlags(t *testing.T) {
@ -39,3 +42,25 @@ func TestGlowFlags(t *testing.T) {
}
}
}
// TestLoadRemoteImagesEnv checks the environment variable that enables
// loading remote images.
func TestLoadRemoteImagesEnv(t *testing.T) {
t.Setenv("GLOW_LOAD_REMOTE_IMAGES", "false")
cfg, err := env.ParseAs[ui.Config]()
if err != nil {
t.Fatal(err)
}
if cfg.LoadRemoteImages {
t.Error("expected remote image loading to be disabled by default")
}
t.Setenv("GLOW_LOAD_REMOTE_IMAGES", "true")
cfg, err = env.ParseAs[ui.Config]()
if err != nil {
t.Fatal(err)
}
if !cfg.LoadRemoteImages {
t.Error("expected GLOW_LOAD_REMOTE_IMAGES to enable remote image loading")
}
}

24
go.mod
View file

@ -4,31 +4,31 @@ go 1.26.7
require (
charm.land/bubbles/v2 v2.1.1
charm.land/bubbletea/v2 v2.0.8
charm.land/glamour/v2 v2.0.1
charm.land/bubbletea/v2 v2.0.9
charm.land/glamour/v2 v2.0.2-0.20260922094102-70fab824e2ec
charm.land/lipgloss/v2 v2.0.6
github.com/atotto/clipboard v0.1.4
github.com/caarlos0/env/v11 v11.3.1
github.com/charmbracelet/log v0.4.2
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886
github.com/charmbracelet/x/ansi v0.11.8
github.com/charmbracelet/x/editor v0.1.0
github.com/dustin/go-humanize v1.0.1
github.com/fsnotify/fsnotify v1.9.0
github.com/mattn/go-runewidth v0.0.24
github.com/mitchellh/go-homedir v1.1.0
github.com/muesli/cancelreader v0.2.2
github.com/muesli/gitcha v0.3.0
github.com/muesli/go-app-paths v0.2.2
github.com/muesli/mango-cobra v1.3.0
github.com/muesli/reflow v0.3.0
github.com/muesli/roff v0.1.0
github.com/muesli/termenv v0.16.0
github.com/rivo/uniseg v0.4.7
github.com/sahilm/fuzzy v0.1.3
github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.21.0
golang.org/x/sys v0.47.0
golang.org/x/term v0.44.0
golang.org/x/text v0.39.0
golang.org/x/term v0.43.0
golang.org/x/text v0.41.0
mvdan.cc/sh/v3 v3.13.1
)
@ -36,10 +36,9 @@ require (
github.com/alecthomas/chroma/v2 v2.14.0 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/bits-and-blooms/bitset v1.24.6 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect
github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
github.com/charmbracelet/x/ansi v0.11.8 // indirect
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
@ -55,22 +54,27 @@ require (
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/mango v0.2.0 // indirect
github.com/muesli/mango-pflag v0.1.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/sabhiram/go-gitignore v0.0.0-20180611051255-d3107576ba94 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c // indirect
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/yuin/goldmark v1.7.17 // indirect
github.com/yuin/goldmark v1.8.5 // indirect
github.com/yuin/goldmark-emoji v1.0.5 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8 // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/image v0.45.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/sync v0.22.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
)

32
go.sum
View file

@ -1,9 +1,9 @@
charm.land/bubbles/v2 v2.1.1 h1:7r55WzBxpo/R3z98hGmY7KKPd3ET6vsf0Fb9sDHOV60=
charm.land/bubbles/v2 v2.1.1/go.mod h1:GE6M31gaWZVXzGw73OeuTTgy4lX+OtkH0E5ymnNsHxo=
charm.land/bubbletea/v2 v2.0.8 h1:SxTJMhCAI3lbPmy4SgX5LWZ24AdINr4I6UEqzZvYJuY=
charm.land/bubbletea/v2 v2.0.8/go.mod h1:2SkdgoTXluXJHOUwAoRlRXF/28vklb1rFl6GcgV1/ss=
charm.land/glamour/v2 v2.0.1 h1:xl+r00A4aJWU0z8fgwKd9fQQ4rsphqGUzuEiXZP5n+c=
charm.land/glamour/v2 v2.0.1/go.mod h1:jo9z8XqVKPeEFMVdvCRLGk++RyJ3CdUwgNr7EvXLw3k=
charm.land/bubbletea/v2 v2.0.9 h1:DpJCMWKgzQK8SJv4zbKKFHAI10ymWy/evClPFk0k0f8=
charm.land/bubbletea/v2 v2.0.9/go.mod h1:2SkdgoTXluXJHOUwAoRlRXF/28vklb1rFl6GcgV1/ss=
charm.land/glamour/v2 v2.0.2-0.20260922094102-70fab824e2ec h1:fwSkd2b70GxrE+pQr4k4xlcd3GzyPFU4qrAusI82IMA=
charm.land/glamour/v2 v2.0.2-0.20260922094102-70fab824e2ec/go.mod h1:s2Vc49ayQNFwtN8L3xVdNh10AdF1PFHMW307oQXpEhI=
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE=
@ -20,6 +20,8 @@ github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ
github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/bits-and-blooms/bitset v1.24.6 h1:qcrftZUVBIwfs+m+nhoCBAPT+ZPZZjti8SbHbDQQkZ4=
github.com/bits-and-blooms/bitset v1.24.6/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
github.com/caarlos0/env/v11 v11.3.1 h1:cArPWC15hWmEt+gWk7YBi7lEXTXCvpaSdCiZE2X5mCA=
github.com/caarlos0/env/v11 v11.3.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
@ -144,6 +146,10 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c h1:km8GpoQut05eY3GiYWEedbTT0qnSxrCjsVbb7yKY1KE=
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c/go.mod h1:cNQ3dwVJtS5Hmnjxy6AgTPd0Inb3pW05ftPSX7NZO7Q=
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef h1:Ch6Q+AZUxDBCVqdkI8FSpFyZDtCVBc2VmejdNrm5rRQ=
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef/go.mod h1:nXTWP6+gD5+LUJ8krVhhoeHjvHTutPxMYl5SvkcnJNE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
@ -153,25 +159,27 @@ github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSW
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
github.com/yuin/goldmark v1.7.17 h1:p36OVWwRb246iHxA/U4p8OPEpOTESm4n+g+8t0EE5uA=
github.com/yuin/goldmark v1.7.17/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/yuin/goldmark v1.8.5 h1:r6N5afV5qj/5S4UTch8agZHJ8UxNCMwX7WjkkJam2NA=
github.com/yuin/goldmark v1.8.5/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk=
github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8 h1:LoYXNGAShUG3m/ehNk4iFctuhGX/+R1ZpfJ4/ia80JM=
golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=

86
main.go
View file

@ -12,10 +12,12 @@ import (
"os/exec"
"path/filepath"
"strings"
"sync"
"mvdan.cc/sh/v3/shell"
"charm.land/glamour/v2"
"charm.land/glamour/v2/ansi"
"charm.land/glamour/v2/styles"
"charm.land/glow/v3/ui"
"charm.land/glow/v3/utils"
@ -43,6 +45,14 @@ var (
showLineNumbers bool
preserveNewLines bool
mouse bool
images bool
imageMaxRows int
loadRemoteImages bool
// imageProtocol is the graphics protocol detected for the terminal. It
// is resolved at most once via imageProtocolForCLI.
imageProtocol ansi.ImageProtocol
detectOnce sync.Once
rootCmd = &cobra.Command{
Use: "glow [SOURCE|DIR]",
@ -172,6 +182,9 @@ func validateOptions(cmd *cobra.Command) error {
showAllFiles = viper.GetBool("all")
preserveNewLines = viper.GetBool("preserveNewLines")
showLineNumbers = viper.GetBool("showLineNumbers")
images = viper.GetBool("images")
imageMaxRows = viper.GetInt("imageMaxRows")
loadRemoteImages = viper.GetBool("loadRemoteImages")
if pager && tui {
return errors.New("cannot use both pager and tui")
@ -281,21 +294,49 @@ func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error {
// render
var baseURL string
u, err := url.ParseRequestURI(src.URL)
if err == nil {
u.Path = filepath.Dir(u.Path)
baseURL = u.String() + "/"
if isURL(src.URL) {
if u, err := url.ParseRequestURI(src.URL); err == nil {
u.Path = filepath.Dir(u.Path)
baseURL = u.String() + "/"
}
} else {
// Resolve image URLs relative to the document's directory. This
// uses a file:// URL so that relative references also resolve on
// platforms where absolute paths are no valid URL paths, like
// Windows.
baseURL = utils.FileBaseURL(src.URL)
}
isCode := !utils.IsMarkdownFile(src.URL)
// Only the direct output mode can display graphics protocol sequences:
// external pagers redraw text themselves and the TUI detects graphics
// support on its own.
useImages := images && !isCode &&
!(pager || cmd.Flags().Changed("pager")) &&
!(tui || cmd.Flags().Changed("tui"))
// initialize glamour
r, err := glamour.NewTermRenderer(
options := []glamour.TermRendererOption{
utils.GlamourStyle(style, isCode),
glamour.WithWordWrap(int(width)), //nolint:gosec
glamour.WithBaseURL(baseURL),
glamour.WithPreservedNewLines(),
)
}
if useImages {
if p := imageProtocolForCLI(); p != ansi.ImageProtocolNone {
options = append(options,
glamour.WithImageProtocol(p),
glamour.WithMaxImageSize(0, imageMaxRows),
)
if loadRemoteImages {
options = append(options, glamour.WithRemoteImages())
} else {
options = append(options, glamour.WithRemoteImageNotLoadedNote(ui.RemoteImageNotLoadedNote))
}
}
}
r, err := glamour.NewTermRenderer(options...)
if err != nil {
return fmt.Errorf("unable to create renderer: %w", err)
}
@ -311,8 +352,6 @@ func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error {
return fmt.Errorf("unable to render markdown: %w", err)
}
out = utils.ApplyTextSizing(out)
// display
switch {
case pager || cmd.Flags().Changed("pager"):
@ -347,9 +386,6 @@ func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error {
}
func runTUI(path string, content string) error {
// detect text sizing support before bubbletea takes over the terminal
_ = utils.TextSizingEnabled()
// Read environment to get debugging stuff
cfg, err := env.ParseAs[ui.Config]()
if err != nil {
@ -367,17 +403,32 @@ func runTUI(path string, content string) error {
cfg.GlamourMaxWidth = width
cfg.EnableMouse = mouse
cfg.PreserveNewLines = preserveNewLines
cfg.Images = viper.GetBool("images")
cfg.ImageMaxRows = viper.GetInt("imageMaxRows")
// The env var is read by env.ParseAs, the config file by Viper.
cfg.LoadRemoteImages = cfg.LoadRemoteImages || viper.GetBool("loadRemoteImages")
// Run Bubble Tea program
prog, cleanup := ui.NewProgram(cfg, content)
defer cleanup()
if _, err := prog.Run(); err != nil {
if _, err := ui.NewProgram(cfg, content).Run(); err != nil {
return fmt.Errorf("unable to run tui program: %w", err)
}
return nil
}
// imageProtocolForCLI detects the terminal's graphics protocol at most once
// per run, so rendering multiple sources doesn't query the terminal
// repeatedly.
func imageProtocolForCLI() ansi.ImageProtocol {
detectOnce.Do(func() {
imageProtocol = utils.DetectImageProtocol()
if imageProtocol != ansi.ImageProtocolNone {
log.Debug("terminal graphics protocol detected", "protocol", imageProtocol)
}
})
return imageProtocol
}
func main() {
closer, err := setupLog()
if err != nil {
@ -412,6 +463,8 @@ func init() {
rootCmd.Flags().BoolVarP(&showAllFiles, "all", "a", false, "show system files and directories (TUI-mode only)")
rootCmd.Flags().BoolVarP(&showLineNumbers, "line-numbers", "l", false, "show line numbers (TUI-mode only)")
rootCmd.Flags().BoolVarP(&preserveNewLines, "preserve-new-lines", "n", false, "preserve newlines in the output")
rootCmd.Flags().BoolVarP(&images, "images", "", true, "render images when the terminal supports it (kitty or sixel graphics; GLOW_IMAGE_PROTOCOL to override)")
rootCmd.Flags().IntVar(&imageMaxRows, "image-max-rows", 20, "maximum number of terminal rows an image may occupy (0 for no limit)")
rootCmd.Flags().BoolVarP(&mouse, "mouse", "m", false, "enable mouse wheel (TUI-mode only)")
_ = rootCmd.Flags().MarkHidden("mouse")
@ -425,10 +478,15 @@ func init() {
_ = viper.BindPFlag("preserveNewLines", rootCmd.Flags().Lookup("preserve-new-lines"))
_ = viper.BindPFlag("showLineNumbers", rootCmd.Flags().Lookup("line-numbers"))
_ = viper.BindPFlag("all", rootCmd.Flags().Lookup("all"))
_ = viper.BindPFlag("images", rootCmd.Flags().Lookup("images"))
_ = viper.BindPFlag("imageMaxRows", rootCmd.Flags().Lookup("image-max-rows"))
viper.SetDefault("style", "auto")
viper.SetDefault("width", 0)
viper.SetDefault("all", true)
viper.SetDefault("images", true)
viper.SetDefault("imageMaxRows", 20)
viper.SetDefault("loadRemoteImages", false)
rootCmd.AddCommand(configCmd, manCmd)
}

View file

@ -11,6 +11,23 @@ type Config struct {
EnableMouse bool
PreserveNewLines bool
// Images controls whether to render images in the pager using the
// terminal's graphics protocol. ImageProtocol can be one of "auto",
// "kitty", or "none" (see utils.ImageProtocol* constants). ImageMaxRows
// limits the number of terminal rows an image may occupy; zero means no
// limit.
Images bool `env:"GLOW_IMAGES" envDefault:"true"`
ImageProtocol string `env:"GLOW_IMAGE_PROTOCOL" envDefault:"auto"`
ImageMaxRows int `env:"GLOW_IMAGE_MAX_ROWS" envDefault:"20"`
// LoadRemoteImages controls whether images referenced by http(s) URLs
// are fetched and rendered. It is disabled by default: fetching remote
// images reveals your IP address to the image's host and uses
// bandwidth, much like a tracking pixel would. While disabled, remote
// images render as a link followed by a note saying they were not
// loaded.
LoadRemoteImages bool `env:"GLOW_LOAD_REMOTE_IMAGES" envDefault:"false"`
// Working directory or file path
Path string

View file

@ -4,12 +4,15 @@ import (
"fmt"
"math"
"path/filepath"
"regexp"
"strings"
"time"
"charm.land/bubbles/v2/spinner"
"charm.land/bubbles/v2/viewport"
tea "charm.land/bubbletea/v2"
"charm.land/glamour/v2"
glamansi "charm.land/glamour/v2/ansi"
"charm.land/glow/v3/utils"
"charm.land/lipgloss/v2"
"github.com/atotto/clipboard"
@ -26,11 +29,85 @@ const (
lineNumberWidth = 4
)
// RemoteImageNotLoadedNote is appended to the URL of a remote image when
// loading remote images is disabled, pointing at the config setting that
// loads them.
const RemoteImageNotLoadedNote = ` (not loaded. Set "loadRemoteImages: true" in your glow config to load remote images)`
// remoteImagePattern matches inline markdown images, i.e.
// ![alt](https://...), and HTML ones, i.e. <img src="https://...">, that are
// fetched over the network.
var remoteImagePattern = regexp.MustCompile(`(?i)!\[[^\]]*\]\(\s*["']?https?://|<img[^>]+src\s*=\s*["']?https?://`)
var (
// referenceImagePattern matches markdown images that point at a link
// reference, i.e. ![alt][badge].
referenceImagePattern = regexp.MustCompile(`!\[[^\]]*\]\[([^\]]*)\]`)
// referenceDefinitionPattern matches the definition of a link
// reference, i.e. [badge]: https://example.com/badge.svg.
referenceDefinitionPattern = regexp.MustCompile(`(?m)^ {0,3}\[([^\]]+)\]:\s*<?(\S+)`)
)
// hasRemoteImages reports whether the markdown references any image by
// http(s) URL, i.e. whether rendering it involves fetching images.
func hasRemoteImages(md string) bool {
if remoteImagePattern.MatchString(md) {
return true
}
// Images can also point at a link reference, e.g. a badge in a README:
// ![build][badge] with [badge]: https://example.com/badge.svg. Match the
// references that are known to be remote; link labels are
// case-insensitive.
var remoteReferences map[string]bool
for _, m := range referenceDefinitionPattern.FindAllStringSubmatch(md, -1) {
if isRemoteURL(m[2]) {
if remoteReferences == nil {
remoteReferences = make(map[string]bool)
}
remoteReferences[strings.ToLower(m[1])] = true
}
}
if len(remoteReferences) == 0 {
return false
}
for _, m := range referenceImagePattern.FindAllStringSubmatch(md, -1) {
if remoteReferences[strings.ToLower(m[1])] {
return true
}
}
return false
}
// isRemoteURL reports whether the given URL is served over http(s).
func isRemoteURL(u string) bool {
return strings.HasPrefix(u, "http://") || strings.HasPrefix(u, "https://")
}
var pagerHelpHeight int
type (
contentRenderedMsg string
reloadMsg struct{}
// contentRenderedMsg is sent when the glamour rendering of a document
// finishes. graphics holds the graphics protocol sequences that must be
// written to the terminal before the content, which references them via
// unicode placeholders, is displayed. body is the markdown that was
// rendered, and remoteImagesPending reports that it was rendered without
// its remote images, which the pager then loads in a second pass.
contentRenderedMsg struct {
content string
graphics []string
body string
remoteImagesPending bool
}
// remoteImagesLoadedMsg is sent when the second rendering pass, which
// loads the document's remote images, finishes. token identifies the
// pass, so a result that was superseded, e.g. by a resize, is ignored.
remoteImagesLoadedMsg struct {
content string
graphics []string
token int
}
reloadMsg struct{}
)
type pagerState int
@ -53,6 +130,20 @@ type pagerModel struct {
// it here so we can re-render it on resize.
currentDocument markdown
// pendingContent is content that is waiting on its graphics protocol
// sequences to be written to the terminal before it can be displayed.
// See the contentRenderedMsg handling in update.
pendingContent string
// remoteImagesLoading reports whether the remote images of the current
// document are still being fetched, and remoteSpinner spins while they
// are; the text is displayed without them in the meantime.
// remoteImagesPass identifies the running fetching pass, so that its
// result can be told apart from those of older passes.
remoteImagesLoading bool
remoteImagesPass int
remoteSpinner spinner.Model
watcher *fsnotify.Watcher
}
@ -60,10 +151,15 @@ func newPagerModel(common *commonModel) pagerModel {
// Init viewport
vp := viewport.New()
sp := spinner.New()
sp.Spinner = spinner.Line
sp.Style = common.styles.statusBarSpinnerStyle
m := pagerModel{
common: common,
state: pagerStateBrowse,
viewport: vp,
common: common,
state: pagerStateBrowse,
viewport: vp,
remoteSpinner: sp,
}
m.initWatcher()
return m
@ -122,6 +218,7 @@ func (m *pagerModel) unload() {
m.statusMessageTimer.Stop()
}
m.state = pagerStateBrowse
m.remoteImagesLoading = false
m.viewport.SetContent("")
m.viewport.SetYOffset(0)
m.unwatchFile()
@ -182,9 +279,70 @@ func (m pagerModel) update(msg tea.Msg) (pagerModel, tea.Cmd) {
case contentRenderedMsg:
log.Info("content rendered", "state", m.state)
m.setContent(string(msg))
if msg.remoteImagesPending {
// The remote images are still being fetched; the content shown
// in the meantime is the text without them. Start the second
// rendering pass that loads and renders them.
m.remoteImagesLoading = true
m.remoteImagesPass++
cmds = append(cmds, m.remoteSpinner.Tick,
loadRemoteImagesCmd(m, msg.body, m.remoteImagesPass))
}
if len(msg.graphics) > 0 {
// The content references images via unicode placeholders, so the
// graphics sequences must be written to the terminal before it
// can be displayed. RawMsg is written out-of-band right before
// this model sees it, so stash the content and wait for it.
m.pendingContent = msg.content
return m, tea.Batch(append(cmds, tea.Raw(strings.Join(msg.graphics, "")))...)
}
m.setContent(msg.content)
cmds = append(cmds, m.watchFile)
// The remote images of the current document have been fetched and
// rendered; swap in the content that displays them.
case remoteImagesLoadedMsg:
if !m.remoteImagesLoading || msg.token != m.remoteImagesPass {
// A newer rendering pass took over, or the user left the
// document while its images were loading; keep what's on screen.
return m, nil
}
m.remoteImagesLoading = false
if len(msg.graphics) > 0 {
m.pendingContent = msg.content
return m, tea.Raw(strings.Join(msg.graphics, ""))
}
m.setContent(msg.content)
// A rendering pass failed, e.g. while fetching the document's remote
// images. Report it and stop the loading indicator, which would
// otherwise stay in the status bar forever.
case errMsg:
var wasLoading bool
wasLoading, m.remoteImagesLoading = m.remoteImagesLoading, false
if wasLoading {
cmds = append(cmds, m.showStatusMessage(pagerStatusMessage{msg.Error(), true}))
}
// Keep the loading indicator spinning while the remote images load.
case spinner.TickMsg:
if m.remoteImagesLoading {
var cmd tea.Cmd
m.remoteSpinner, cmd = m.remoteSpinner.Update(msg)
cmds = append(cmds, cmd)
}
// The graphics sequences for the pending content have been written
case tea.RawMsg:
if m.pendingContent != "" {
m.setContent(m.pendingContent)
m.pendingContent = ""
cmds = append(cmds, m.watchFile)
}
// The file was changed on disk and we're reloading it
case reloadMsg:
return m, loadLocalMarkdown(&m.currentDocument)
@ -212,7 +370,17 @@ func (m pagerModel) update(msg tea.Msg) (pagerModel, tea.Cmd) {
func (m pagerModel) View() string {
var b strings.Builder
fmt.Fprint(&b, m.viewport.View()+"\n")
// The viewport pads its content to the height it was given, but it draws
// nothing at all until it has been sized, i.e. before the first window
// size message. The status bar would then end up at the top of the screen,
// and the lines it doesn't cover would keep the previous frame on screen.
// Fill the gap so the bar always stays at the bottom.
content := m.viewport.View()
if missing := m.common.height - statusBarHeight - (strings.Count(content, "\n") + 1); m.common.height > 0 && missing > 0 {
content += strings.Repeat("\n", missing)
}
fmt.Fprint(&b, content+"\n")
// Footer
m.statusBarView(&b)
@ -255,22 +423,32 @@ func (m pagerModel) statusBarView(b *strings.Builder) {
}
// Note
var note string
if showStatusMessage {
note = m.statusMessage
} else {
note = m.currentDocument.Note
}
note = truncate.StringWithTail(" "+note+" ", uint(max(0, //nolint:gosec
noteWidth := max(0,
m.common.width-
ansi.PrintableRuneWidth(logo)-
ansi.PrintableRuneWidth(scrollPercent)-
ansi.PrintableRuneWidth(helpNote),
)), ellipsis)
if showStatusMessage {
note = styles.statusBarMessageStyle(note)
} else {
note = styles.statusBarNoteStyle(note)
)
// The loading indicator takes the place of the status message, so it's
// styled like the file name rather than like a message.
showMessage := showStatusMessage && !m.remoteImagesLoading
var note string
switch {
case m.remoteImagesLoading:
// The spinner's own styling ends in an ANSI reset which would wipe
// the status bar background of everything after it, so the note is
// styled in segments around the spinner.
spinnerView := m.remoteSpinner.View()
textWidth := max(0, noteWidth-ansi.PrintableRuneWidth(spinnerView)-1)
note = styles.statusBarNoteStyle(" ") + spinnerView +
styles.statusBarNoteStyle(truncate.StringWithTail( //nolint:gosec
" Loading remote images... ", uint(textWidth), ellipsis))
case showMessage:
note = styles.statusBarMessageStyle(truncate.StringWithTail( //nolint:gosec
" "+m.statusMessage+" ", uint(noteWidth), ellipsis))
default:
note = styles.statusBarNoteStyle(truncate.StringWithTail( //nolint:gosec
" "+m.currentDocument.Note+" ", uint(noteWidth), ellipsis))
}
// Empty space
@ -282,7 +460,7 @@ func (m pagerModel) statusBarView(b *strings.Builder) {
ansi.PrintableRuneWidth(helpNote),
)
emptySpace := strings.Repeat(" ", padding)
if showStatusMessage {
if showMessage {
emptySpace = styles.statusBarMessageStyle(emptySpace)
} else {
emptySpace = styles.statusBarNoteStyle(emptySpace)
@ -339,23 +517,73 @@ func (m pagerModel) helpView() (s string) {
// COMMANDS
// renderWithGlamour renders the document for the pager. When remote images
// are enabled and the document references any, the text is rendered without
// them first so it can be displayed right away: fetching them takes a while,
// and the document would otherwise stay off the screen until it's done. The
// pager then starts a second pass that loads and renders the images, see the
// contentRenderedMsg handling in update.
func renderWithGlamour(m pagerModel, md string) tea.Cmd {
pending := remoteImagesEnabled(m) && hasRemoteImages(md)
// Images that don't need fetching are loaded in the first pass.
return renderContent(m, md, m.common.cfg.LoadRemoteImages && !pending, pending)
}
// renderContent renders a document with glamour and reports the result to
// the pager. remote loads images referenced by http(s) URLs; pending marks a
// render that leaves the remote images to a follow-up pass.
func renderContent(m pagerModel, md string, remote, pending bool) tea.Cmd {
return func() tea.Msg {
s, err := glamourRender(m, md)
s, graphics, err := glamourRender(m, md, remote)
if err != nil {
log.Error("error rendering with Glamour", "error", err)
return errMsg{err}
}
return contentRenderedMsg(s)
return contentRenderedMsg{
content: s,
graphics: graphics,
body: md,
remoteImagesPending: pending,
}
}
}
// remoteImagesEnabled reports whether remote images should be loaded when
// rendering the current document.
func remoteImagesEnabled(m pagerModel) bool {
return m.common.cfg.LoadRemoteImages && glamourImages(m) &&
utils.IsMarkdownFile(m.currentDocument.Note)
}
// loadRemoteImagesCmd renders a document a second time, fetching and
// rendering its remote images. token identifies the pass, so a result that a
// newer pass has superseded can be discarded.
func loadRemoteImagesCmd(m pagerModel, md string, token int) tea.Cmd {
return func() tea.Msg {
s, graphics, err := glamourRender(m, md, true)
if err != nil {
log.Error("error loading remote images", "error", err)
return errMsg{err}
}
return remoteImagesLoadedMsg{content: s, graphics: graphics, token: token}
}
}
// glamourImages reports whether to render images in the pager using the
// terminal's graphics protocol.
func glamourImages(m pagerModel) bool {
return m.common.cfg.GlamourEnabled && m.common.cfg.Images &&
m.common.imageProtocol != glamansi.ImageProtocolNone
}
// This is where the magic happens.
func glamourRender(m pagerModel, markdown string) (string, error) {
func glamourRender(m pagerModel, markdown string, loadRemoteImages bool) (string, []string, error) {
images := glamourImages(m)
trunc := lipgloss.NewStyle().MaxWidth(m.viewport.Width() - lineNumberWidth).Render
if !m.common.cfg.GlamourEnabled {
return markdown, nil
return markdown, nil, nil
}
isCode := !utils.IsMarkdownFile(m.currentDocument.Note)
@ -369,12 +597,48 @@ func glamourRender(m pagerModel, markdown string) (string, error) {
glamour.WithWordWrap(width),
}
if images && !isCode {
if width == 0 {
// Without a wrap width, images would be sized to their
// natural dimensions, which can be far larger than the
// viewport.
width = m.viewport.Width()
options[1] = glamour.WithWordWrap(width)
}
if m.common.cfg.ShowLineNumbers {
// Leave room for the line number gutter so the rendered
// content, including image placeholder grids, doesn't get
// truncated.
width = max(0, width-lineNumberWidth)
options[1] = glamour.WithWordWrap(width)
}
options = append(options,
glamour.WithImageProtocol(m.common.imageProtocol),
glamour.WithMaxImageSize(0, m.common.cfg.ImageMaxRows),
)
switch {
case loadRemoteImages:
options = append(options, glamour.WithRemoteImages())
case m.common.cfg.LoadRemoteImages:
// This is the text-only render that precedes the remote image
// loading one, so don't claim the images were not loaded.
options = append(options, glamour.WithRemoteImageNotLoadedNote(""))
default:
options = append(options, glamour.WithRemoteImageNotLoadedNote(RemoteImageNotLoadedNote))
}
}
if m.common.cfg.PreserveNewLines {
options = append(options, glamour.WithPreservedNewLines())
}
if m.currentDocument.localPath != "" {
// Resolve image URLs relative to the document's directory, the
// same way the CLI does.
options = append(options, glamour.WithBaseURL(utils.FileBaseURL(m.currentDocument.localPath)))
}
r, err := glamour.NewTermRenderer(options...)
if err != nil {
return "", fmt.Errorf("error creating glamour renderer: %w", err)
return "", nil, fmt.Errorf("error creating glamour renderer: %w", err)
}
if isCode {
@ -383,13 +647,15 @@ func glamourRender(m pagerModel, markdown string) (string, error) {
out, err := r.Render(markdown)
if err != nil {
return "", fmt.Errorf("error rendering markdown: %w", err)
return "", nil, fmt.Errorf("error rendering markdown: %w", err)
}
// The graphics commands are out-of-band sequences the caller must write
// to the terminal before displaying the rendered content.
graphics := r.GraphicsCommands()
if isCode {
out = strings.TrimSpace(out)
} else {
out = utils.ApplyTextSizing(out)
}
// trim lines
@ -410,7 +676,7 @@ func glamourRender(m pagerModel, markdown string) (string, error) {
}
}
return content.String(), nil
return content.String(), graphics, nil
}
func (m *pagerModel) initWatcher() {

View file

@ -1,43 +0,0 @@
package ui
import (
"strings"
"testing"
)
func TestGlamourRenderTextSizing(t *testing.T) {
t.Setenv("GLOW_TEXT_SIZING", "on")
common := &commonModel{
cfg: Config{
GlamourEnabled: true,
GlamourStyle: "dark",
GlamourMaxWidth: 80,
},
styles: newStyles(true),
width: 80,
height: 24,
}
m := newPagerModel(common)
m.currentDocument = markdown{Note: "test.md"}
m.setSize(80, 24)
out, err := glamourRender(m, "# Hello\n\n## World\n")
if err != nil {
t.Fatal(err)
}
// The dark style's H1 has a background color, which renders broken when
// scaled, so it is left at normal size.
if strings.Contains(out, "\x1b]66;s=3;") {
t.Errorf("expected H1 with background to not be scaled, got %q", out)
}
if !strings.Contains(out, "Hello") {
t.Errorf("expected H1 text in pager output, got %q", out)
}
if !strings.Contains(out, "\x1b]66;s=2;World\x1b\\") {
t.Errorf("expected H2 at 2x scale in pager output, got %q", out)
}
if strings.Contains(out, "\x1b]6666;") {
t.Errorf("expected no leftover markers in pager output, got %q", out)
}
}

View file

@ -1,139 +0,0 @@
package ui
import (
"io"
"os"
"strings"
"sync"
tea "charm.land/bubbletea/v2"
"golang.org/x/term"
)
// rawPainter paints frames directly to the terminal. It is used when kitty
// text sizing support is detected: bubbletea's default renderer parses each
// frame into a cell buffer which discards OSC 66 sequences along with their
// payload text, so the program runs with [tea.WithoutRenderer] and this
// painter drives the terminal instead.
type rawPainter struct {
w io.Writer
tty *os.File
state *term.State
mouse bool
done chan struct{}
mu sync.Mutex
gen int
painted int
}
func newRawPainter(w io.Writer, tty *os.File, state *term.State, mouse bool) *rawPainter {
return &rawPainter{w: w, tty: tty, state: state, mouse: mouse, done: make(chan struct{})}
}
func (p *rawPainter) windowSize() tea.WindowSizeMsg {
if p.tty != nil {
if w, h, err := term.GetSize(int(p.tty.Fd())); err == nil && w > 0 && h > 0 {
return tea.WindowSizeMsg{Width: w, Height: h}
}
}
return tea.WindowSizeMsg{Width: 80, Height: 24}
}
func (p *rawPainter) start() {
p.mu.Lock()
defer p.mu.Unlock()
_, _ = io.WriteString(p.w, "\x1b[?1049h\x1b[?25l")
if p.mouse {
_, _ = io.WriteString(p.w, "\x1b[?1002h\x1b[?1006h")
}
}
func (p *rawPainter) stop() {
p.mu.Lock()
defer p.mu.Unlock()
if p.mouse {
_, _ = io.WriteString(p.w, "\x1b[?1002l\x1b[?1006l")
}
_, _ = io.WriteString(p.w, "\x1b[?25h\x1b[?1049l")
if p.tty != nil {
if p.state != nil {
_ = term.Restore(int(p.tty.Fd()), p.state)
}
_ = p.tty.Close()
}
select {
case <-p.done:
default:
close(p.done)
}
}
// watchResize sends the initial window size to the program and reports
// terminal resizes. Without a renderer bubbletea never initializes the tty,
// so its own size reporting never happens.
func (p *rawPainter) watchResize(prog *tea.Program) {
ch := make(chan os.Signal, 1)
winchNotify(ch)
go func() {
prog.Send(p.windowSize())
for {
select {
case <-p.done:
winchStop(ch)
return
case <-ch:
prog.Send(p.windowSize())
}
}
}()
}
func (p *rawPainter) paint(frame string) tea.Cmd {
p.mu.Lock()
p.gen++
gen := p.gen
p.mu.Unlock()
return func() tea.Msg {
p.mu.Lock()
defer p.mu.Unlock()
if gen <= p.painted {
return nil
}
p.painted = gen
var b strings.Builder
b.WriteString("\x1b[?2026h\x1b[H\x1b[2J")
b.WriteString(strings.ReplaceAll(frame, "\n", "\r\n"))
b.WriteString("\x1b[?2026l")
_, _ = io.WriteString(p.w, b.String())
return nil
}
}
// paintModel wraps the root model, painting a frame after every processed
// message. Bubbletea's renderer never calls View when it is disabled, so the
// wrapper drives painting itself.
type paintModel struct {
inner tea.Model
painter *rawPainter
}
func (m paintModel) Init() tea.Cmd {
m.painter.start()
return tea.Batch(m.inner.Init(), m.painter.paint(m.inner.View().Content))
}
func (m paintModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if ws, ok := msg.(tea.WindowSizeMsg); ok && (ws.Width <= 0 || ws.Height <= 0) {
msg = m.painter.windowSize()
}
inner, cmd := m.inner.Update(msg)
m.inner = inner
return m, tea.Batch(cmd, m.painter.paint(inner.View().Content))
}
func (m paintModel) View() tea.View {
return m.inner.View()
}

View file

@ -1,107 +0,0 @@
package ui
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
"time"
tea "charm.land/bubbletea/v2"
)
func TestRawPainterPaint(t *testing.T) {
var buf bytes.Buffer
p := &rawPainter{w: &buf}
stale := p.paint("stale frame")
fresh := p.paint("fresh\nframe")
fresh()
stale()
got := buf.String()
if strings.Contains(got, "stale") {
t.Errorf("stale frame was painted over a newer one: %q", got)
}
if !strings.Contains(got, "\x1b[?2026h\x1b[H\x1b[2Jfresh\r\nframe\x1b[?2026l") {
t.Errorf("unexpected frame format: %q", got)
}
}
func TestPaintModelRendersDocument(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "test.md")
if err := os.WriteFile(path, []byte("# Hello\n\nSome text here.\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg := Config{
GlamourEnabled: true,
GlamourStyle: "dark",
GlamourMaxWidth: 80,
Path: path,
}
var buf bytes.Buffer
painter := &rawPainter{w: &buf}
var pm tea.Model = paintModel{inner: newModel(cfg, ""), painter: painter}
msgCh := make(chan tea.Msg, 64)
var exec func(cmd tea.Cmd)
exec = func(cmd tea.Cmd) {
if cmd == nil {
return
}
go func() {
switch msg := cmd().(type) {
case tea.BatchMsg:
for _, c := range msg {
exec(c)
}
case nil:
default:
msgCh <- msg
}
}()
}
exec(pm.Init())
msgCh <- tea.WindowSizeMsg{Width: 80, Height: 24}
deadline := time.Now().Add(3 * time.Second)
for {
// Frames are painted asynchronously by the paint command, so poll
// the buffer instead of only checking after processed messages.
painter.mu.Lock()
done := strings.Contains(buf.String(), "Some text")
painter.mu.Unlock()
if done {
return
}
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for content; buf=%q", buf.String())
}
select {
case msg := <-msgCh:
im, cmd := pm.Update(msg)
pm = im
exec(cmd)
case <-time.After(5 * time.Millisecond):
}
}
}
func TestPaintModelZeroSizeSubstitution(t *testing.T) {
var buf bytes.Buffer
painter := &rawPainter{w: &buf}
pm := paintModel{inner: newModel(Config{}, "body"), painter: painter}
im, _ := pm.Update(tea.WindowSizeMsg{Width: 0, Height: 0})
m := im.(paintModel).inner.(model)
if m.common.width != 80 || m.common.height != 24 {
t.Errorf("expected fallback size 80x24, got %dx%d", m.common.width, m.common.height)
}
}

View file

@ -1,32 +0,0 @@
//go:build !windows
package ui
import (
"os"
"os/signal"
"syscall"
"golang.org/x/term"
)
func openRawTerminal() (*os.File, *term.State, error) {
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return nil, nil, err
}
state, err := term.MakeRaw(int(tty.Fd()))
if err != nil {
_ = tty.Close()
return nil, nil, err
}
return tty, state, nil
}
func winchNotify(ch chan os.Signal) {
signal.Notify(ch, syscall.SIGWINCH)
}
func winchStop(ch chan os.Signal) {
signal.Stop(ch)
}

View file

@ -1,16 +0,0 @@
package ui
import (
"errors"
"os"
"golang.org/x/term"
)
func openRawTerminal() (*os.File, *term.State, error) {
return nil, nil, errors.New("raw terminal is not supported on windows")
}
func winchNotify(chan os.Signal) {}
func winchStop(chan os.Signal) {}

View file

@ -660,7 +660,7 @@ func (m stashModel) view() string {
var s string
switch m.viewState {
case stashStateShowingError:
return errorView(m.common.styles, m.err, false)
return fillHeight(errorView(m.common.styles, m.err, false), m.common.height)
case stashStateLoadingDocument:
s += " " + m.spinner.View() + " Loading document..."
case stashStateReady:
@ -733,7 +733,7 @@ func (m stashModel) view() string {
help,
)
}
return "\n" + indent(s, stashIndent)
return fillHeight("\n"+indent(s, stashIndent), m.common.height)
}
func glowLogoView(styles Styles) string {

View file

@ -42,6 +42,7 @@ type Styles struct {
statusBarMessageStyle func(...string) string
statusBarMessageScrollPosStyle func(...string) string
statusBarMessageHelpStyle func(...string) string
statusBarSpinnerStyle lipgloss.Style
helpViewStyle func(...string) string
lineNumberStyle func(...string) string
@ -135,6 +136,10 @@ func newStyles(isDark bool) Styles {
Background(green).
Render
s.statusBarSpinnerStyle = lipgloss.NewStyle().
Foreground(gray).
Background(statusBarBg)
s.helpViewStyle = lipgloss.NewStyle().
Foreground(statusBarNoteFg).
Background(s.adaptive("#f2f2f2", "#1B1B1B")).

View file

@ -9,8 +9,10 @@ import (
"time"
tea "charm.land/bubbletea/v2"
"charm.land/glamour/v2/ansi"
"charm.land/glow/v3/utils"
"github.com/charmbracelet/log"
uv "github.com/charmbracelet/ultraviolet"
"github.com/muesli/gitcha"
)
@ -23,9 +25,8 @@ var markdownExtensions = []string{
"*.md", "*.mdown", "*.mkdn", "*.mkd", "*.markdown",
}
// NewProgram returns a new Tea program. The returned cleanup function
// restores the terminal state and must be called after the program exits.
func NewProgram(cfg Config, content string) (*tea.Program, func()) {
// NewProgram returns a new Tea program.
func NewProgram(cfg Config, content string) *tea.Program {
log.Debug(
"Starting glow",
"glamour",
@ -33,21 +34,7 @@ func NewProgram(cfg Config, content string) (*tea.Program, func()) {
)
m := newModel(cfg, content)
if utils.TextSizingEnabled() {
if tty, state, err := openRawTerminal(); err == nil {
painter := newRawPainter(os.Stdout, tty, state, cfg.EnableMouse)
prog := tea.NewProgram(
paintModel{inner: m, painter: painter},
tea.WithoutRenderer(),
tea.WithInput(tty),
)
painter.watchResize(prog)
return prog, painter.stop
}
}
return tea.NewProgram(m), func() {}
return tea.NewProgram(m)
}
type errMsg struct{ err error }
@ -98,6 +85,12 @@ type commonModel struct {
width int
height int
styles Styles
// imageProtocol is the graphics protocol resolved for the TUI. It is
// ImageProtocolNone until the terminal is known to support displaying
// images (see the kitty graphics query in model.Init), at which point
// documents are re-rendered with it.
imageProtocol ansi.ImageProtocol
}
type model struct {
@ -134,6 +127,14 @@ func newModel(cfg Config, content string) tea.Model {
cfg: cfg,
styles: newStyles(true),
}
if cfg.Images {
switch cfg.ImageProtocol {
case utils.ImageProtocolKitty:
common.imageProtocol = ansi.ImageProtocolKittyPlaceholders
case utils.ImageProtocolNone:
common.imageProtocol = ansi.ImageProtocolNone
}
}
m := model{
common: &common,
@ -163,18 +164,20 @@ func newModel(cfg Config, content string) tea.Model {
} else {
cwd, _ := os.Getwd()
m.state = stateShowDocument
// Keep the raw body around so the pager can re-render the document
// on resize or when image support gets enabled mid-session.
body := content
if body == "" {
if b, err := os.ReadFile(path); err == nil {
body = string(b)
}
}
m.pager.currentDocument = markdown{
localPath: path,
Note: stripAbsolutePath(path, cwd),
Modtime: info.ModTime(),
Body: string(utils.RemoveFrontmatter([]byte(body))),
}
content, err := os.ReadFile(path)
if err != nil {
log.Error("unable to read file", "file", path, "error", err)
m.fatalErr = err
return m
}
m.pager.currentDocument.Body = string(utils.RemoveFrontmatter(content))
}
return m
@ -183,11 +186,23 @@ func newModel(cfg Config, content string) tea.Model {
func (m model) Init() tea.Cmd {
cmds := []tea.Cmd{m.stash.spinner.Tick, tea.RequestBackgroundColor}
// Detect support for the kitty graphics protocol by querying the
// terminal. The response arrives as a uv.KittyGraphicsEvent.
if m.common.cfg.Images && m.common.cfg.ImageProtocol == utils.ImageProtocolAuto {
cmds = append(cmds, tea.Raw(utils.GraphicsQuery()))
}
switch m.state {
case stateShowStash:
cmds = append(cmds, findLocalFiles(*m.common))
case stateShowDocument:
cmds = append(cmds, renderWithGlamour(m.pager, m.pager.currentDocument.Body))
content, err := os.ReadFile(m.common.cfg.Path)
if err != nil {
log.Error("unable to read file", "file", m.common.cfg.Path, "error", err)
return func() tea.Msg { return errMsg{err} }
}
body := string(utils.RemoveFrontmatter(content))
cmds = append(cmds, renderWithGlamour(m.pager, body))
}
return tea.Batch(cmds...)
@ -272,6 +287,19 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
body := string(utils.RemoveFrontmatter([]byte(msg.Body)))
cmds = append(cmds, renderWithGlamour(m.pager, body))
case uv.KittyGraphicsEvent:
// The terminal answered our kitty graphics query from Init. Enable
// images and re-render the current document, if any, with them.
if m.common.cfg.Images && m.common.imageProtocol == ansi.ImageProtocolNone &&
utils.KittyGraphicsOK(msg.Options.ID, msg.Payload) {
m.common.imageProtocol = ansi.ImageProtocolKittyPlaceholders
log.Debug("terminal supports the kitty graphics protocol")
if m.state == stateShowDocument {
body := string(utils.RemoveFrontmatter([]byte(m.pager.currentDocument.Body)))
cmds = append(cmds, renderWithGlamour(m.pager, body))
}
}
case contentRenderedMsg:
m.state = stateShowDocument
@ -322,7 +350,7 @@ func (m model) View() tea.View {
var content string
switch {
case m.fatalErr != nil:
content = errorView(m.common.styles, m.fatalErr, true)
content = fillHeight(errorView(m.common.styles, m.fatalErr, true), m.common.height)
case m.state == stateShowDocument:
content = m.pager.View()
default:
@ -437,6 +465,18 @@ func stripAbsolutePath(fullPath, cwd string) string {
return strings.ReplaceAll(fp, cp+string(os.PathSeparator), "")
}
// fillHeight pads a view with newlines so that it fills the given number of
// terminal lines. Views that don't cover the whole terminal leave whatever the
// previous frame drew on screen, which is visible as stale lines, e.g. the
// status bar of a document stuck at the bottom after going back to the stash.
func fillHeight(s string, height int) string {
missing := height - (strings.Count(s, "\n") + 1)
if height <= 0 || missing <= 0 {
return s
}
return s + strings.Repeat("\n", missing)
}
// Lightweight version of reflow's indent function.
func indent(s string, n int) string {
if n <= 0 || s == "" {

View file

@ -1,24 +1,719 @@
package ui
import (
"bytes"
"errors"
"image"
"image/color"
"image/png"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
tea "charm.land/bubbletea/v2"
"charm.land/glamour/v2/ansi"
)
func TestNewModelLoadsDocumentBody(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "test.md")
if err := os.WriteFile(path, []byte("# Hello\n\nSome text here.\n"), 0o644); err != nil {
// testPNG returns the bytes of a small PNG image.
func testPNG(t *testing.T) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, 16, 8))
for x := 0; x < 16; x++ {
for y := 0; y < 8; y++ {
img.Set(x, y, color.RGBA{R: 255, A: 255})
}
}
var pngBuf bytes.Buffer
if err := png.Encode(&pngBuf, img); err != nil {
t.Fatal(err)
}
return pngBuf.Bytes()
}
// writeTestDocument writes a markdown document to a temporary directory and
// returns its path.
func writeTestDocument(t *testing.T, content string) string {
t.Helper()
mdPath := filepath.Join(t.TempDir(), "test.md")
if err := os.WriteFile(mdPath, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
return mdPath
}
// writeTestFiles creates a markdown document referencing a PNG image and
// returns the markdown file's path.
func writeTestFiles(t *testing.T) string {
t.Helper()
if err := os.WriteFile(filepath.Join(t.TempDir(), "test.png"), testPNG(t), 0o644); err != nil {
t.Fatal(err)
}
m := newModel(Config{Path: path}, "").(model)
if m.state != stateShowDocument {
t.Fatalf("expected stateShowDocument, got %s", m.state)
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "test.png"), testPNG(t), 0o644); err != nil {
t.Fatal(err)
}
if !strings.Contains(m.pager.currentDocument.Body, "Some text") {
t.Errorf("expected document body to be loaded, got %q", m.pager.currentDocument.Body)
mdPath := filepath.Join(dir, "test.md")
if err := os.WriteFile(mdPath, []byte("# Hello\n\n![red](test.png)\n\nBye!\n"), 0o644); err != nil {
t.Fatal(err)
}
return mdPath
}
// TestPagerKittyImages runs the pager on a document with an image and checks
// that the image is transmitted out-of-band before the content, which
// references it via unicode placeholders, is displayed.
func TestPagerKittyImages(t *testing.T) {
mdPath := writeTestFiles(t)
cfg := Config{
GlamourEnabled: true,
GlamourStyle: "dark",
GlamourMaxWidth: 80,
Images: true,
ImageProtocol: "kitty",
Path: mdPath,
}
m := newModel(cfg, "")
var out bytes.Buffer
p := tea.NewProgram(m,
tea.WithOutput(&out),
tea.WithInput(strings.NewReader("")),
tea.WithWindowSize(80, 24),
)
quit := make(chan struct{})
go func() {
// Give the program time to render, then shut it down.
time.Sleep(500 * time.Millisecond)
p.Send(tea.Quit())
close(quit)
}()
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
<-quit
got := out.String()
// The image must have been transmitted with a virtual placement.
transmit := strings.Index(got, "\x1b_G")
if transmit < 0 {
t.Fatalf("no kitty graphics commands in output: %q", got)
}
if !strings.Contains(got, "a=p") || !strings.Contains(got, "U=1") {
t.Errorf("expected a virtual placement command, got: %q", got)
}
// The content must reference the image via unicode placeholders, which
// the terminal replaces with the image as the content scrolls.
placeholder := strings.IndexRune(got, 0x10EEEE)
if placeholder < 0 {
t.Fatalf("no unicode placeholders in output: %q", got)
}
// The transmission must be written to the terminal before the
// placeholders are displayed, otherwise the terminal can't resolve them
// until the next repaint.
if transmit > placeholder {
t.Errorf("expected graphics commands (%d) before placeholders (%d)", transmit, placeholder)
}
}
// TestPagerNoImages checks that with images disabled the output contains
// neither graphics commands nor placeholders.
func TestPagerNoImages(t *testing.T) {
mdPath := writeTestFiles(t)
cfg := Config{
GlamourEnabled: true,
GlamourStyle: "dark",
GlamourMaxWidth: 80,
Images: false,
Path: mdPath,
}
m := newModel(cfg, "")
var out bytes.Buffer
p := tea.NewProgram(m,
tea.WithOutput(&out),
tea.WithInput(strings.NewReader("")),
tea.WithWindowSize(80, 24),
)
go func() {
time.Sleep(500 * time.Millisecond)
p.Send(tea.Quit())
}()
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
got := out.String()
if strings.Contains(got, "\x1b_G") {
t.Errorf("expected no graphics commands, got: %q", got)
}
if strings.ContainsRune(got, 0x10EEEE) {
t.Errorf("expected no placeholders, got: %q", got)
}
}
// TestCommonModelImageProtocol checks the initial protocol resolution from
// the config.
func TestCommonModelImageProtocol(t *testing.T) {
for _, tc := range []struct {
protocol string
images bool
want ansi.ImageProtocol
}{
{"kitty", true, ansi.ImageProtocolKittyPlaceholders},
{"none", true, ansi.ImageProtocolNone},
{"auto", true, ansi.ImageProtocolNone},
{"kitty", false, ansi.ImageProtocolNone},
} {
m := newModel(Config{Images: tc.images, ImageProtocol: tc.protocol}, "")
if got := m.(model).common.imageProtocol; got != tc.want {
t.Errorf("protocol %q, images %v: expected %v, got %v", tc.protocol, tc.images, tc.want, got)
}
}
}
// TestHasRemoteImages checks the detection of images that have to be fetched
// over the network.
func TestHasRemoteImages(t *testing.T) {
for _, tc := range []struct {
markdown string
want bool
}{
{"![alt](https://example.com/img.png)", true},
{"![](http://example.com/img.png)", true},
{`<img src="https://example.com/img.png">`, true},
{"![build][badge]\n\n[badge]: https://example.com/badge.svg", true},
{"![build][BADGE]\n\n[badge]: https://example.com/badge.svg", true},
{"![build][badge]\n\n[badge]: badge.svg", false},
{"[docs]: https://example.com\n\nsee [docs]", false},
{"![alt](img.png)", false},
{"[alt](https://example.com)", false},
{`<img src="img.png">`, false},
{"no images at all", false},
} {
if got := hasRemoteImages(tc.markdown); got != tc.want {
t.Errorf("%q: expected %v, got %v", tc.markdown, tc.want, got)
}
}
}
// TestPagerRemoteImagesDisabled checks that remote images are not fetched by
// default, and that their URL is rendered with a note pointing at the config
// setting that loads them.
func TestPagerRemoteImagesDisabled(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
t.Error("no remote image may be fetched while remote image loading is disabled")
}))
defer srv.Close()
mdPath := writeTestDocument(t, "# Hello\n\n![red]("+srv.URL+"/test.png)\n")
cfg := Config{
GlamourEnabled: true,
GlamourStyle: "dark",
GlamourMaxWidth: 80,
Images: true,
ImageProtocol: "kitty",
Path: mdPath,
}
m := newModel(cfg, "")
var out bytes.Buffer
p := tea.NewProgram(m,
tea.WithOutput(&out),
tea.WithInput(strings.NewReader("")),
tea.WithWindowSize(80, 24),
)
go func() {
time.Sleep(500 * time.Millisecond)
p.Send(tea.Quit())
}()
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
got := out.String()
// The note can wrap or be cut off by the terminal, so check for the
// parts of it that always fit.
if !strings.Contains(got, "not loaded.") {
t.Errorf("expected a note about the image not being loaded, got: %q", got)
}
if !strings.Contains(got, "loadRemoteImage") {
t.Errorf("expected a note about the loadRemoteImages setting, got: %q", got)
}
if strings.Contains(got, "\x1b_G") {
t.Errorf("expected no graphics commands, got: %q", got)
}
if strings.ContainsRune(got, 0x10EEEE) {
t.Errorf("expected no placeholders, got: %q", got)
}
}
// TestGlamourRenderRemoteImages checks how remote images are rendered,
// depending on the config: with loading disabled they are annotated with a
// note, and while they are pending the note is withheld so they aren't
// reported as not loaded.
func TestGlamourRenderRemoteImages(t *testing.T) {
url := "https://example.com/img.png"
md := "![alt](" + url + ")"
newPager := func(loadRemoteImages bool) pagerModel {
common := &commonModel{
cfg: Config{GlamourEnabled: true, Images: true, LoadRemoteImages: loadRemoteImages, GlamourStyle: "dark"},
styles: newStyles(true),
imageProtocol: ansi.ImageProtocolKitty,
}
m := newPagerModel(common)
// No wrap width, so the rendered note stays on a single line and the
// rendering is deterministic.
m.setSize(0, 24)
m.currentDocument = markdown{Note: "test.md", Body: md}
return m
}
// Disabled: the URL is followed by a note pointing at the setting.
out, _, err := glamourRender(newPager(false), md, false)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, RemoteImageNotLoadedNote) {
t.Errorf("expected the not-loaded note, got: %q", out)
}
// Enabled: the first pass renders the text without claiming the images
// weren't loaded; the second pass loads them.
out, _, err = glamourRender(newPager(true), md, false)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, url) {
t.Errorf("expected the image URL to render, got: %q", out)
}
if strings.Contains(out, "not loaded") {
t.Errorf("expected no not-loaded note while the images load, got: %q", out)
}
}
// TestPagerLoadRemoteImages checks that with remote image loading enabled the
// document's remote images are fetched and rendered.
func TestPagerLoadRemoteImages(t *testing.T) {
var requests atomic.Int32
png := testPNG(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
requests.Add(1)
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(png)
}))
defer srv.Close()
mdPath := writeTestDocument(t, "# Hello\n\n![red]("+srv.URL+"/test.png)\n\nBye!\n")
cfg := Config{
GlamourEnabled: true,
GlamourStyle: "dark",
GlamourMaxWidth: 80,
Images: true,
ImageProtocol: "kitty",
LoadRemoteImages: true,
Path: mdPath,
}
m := newModel(cfg, "")
var out bytes.Buffer
p := tea.NewProgram(m,
tea.WithOutput(&out),
tea.WithInput(strings.NewReader("")),
tea.WithWindowSize(80, 24),
)
go func() {
// Leave room for the second rendering pass that fetches the image.
time.Sleep(time.Second)
p.Send(tea.Quit())
}()
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
got := out.String()
if requests.Load() == 0 {
t.Error("expected the remote image to be fetched")
}
// The image may only be transmitted by the second rendering pass, which
// fetched it.
if !strings.Contains(got, "\x1b_G") {
t.Errorf("expected the remote image to be transmitted, got: %q", got)
}
if !strings.ContainsRune(got, 0x10EEEE) {
t.Errorf("expected the image to be displayed via placeholders, got: %q", got)
}
if strings.Contains(got, "loadRemoteImages") {
t.Errorf("expected no not-loaded note, got: %q", got)
}
}
// TestPagerRemoteImagesLoading checks that the pager reports the remote
// images as loading, and only displays the results of the current fetching
// pass.
func TestPagerRemoteImagesLoading(t *testing.T) {
common := commonModel{cfg: Config{GlamourEnabled: true}, styles: newStyles(true), width: 80, height: 24}
m := newPagerModel(&common)
m.setSize(80, 24)
m.currentDocument = markdown{Note: "test.md", Body: "![](https://example.com/img.png)"}
m, cmd := m.update(contentRenderedMsg{
content: "text without images",
body: m.currentDocument.Body,
remoteImagesPending: true,
})
if !m.remoteImagesLoading {
t.Error("expected the remote images to be reported as loading")
}
if cmd == nil {
t.Error("expected a command that fetches the remote images")
}
if !strings.Contains(m.View(), "Loading remote images") {
t.Errorf("expected a loading indicator, got: %q", m.View())
}
// Results of an older pass, e.g. one superseded by a resize, are stale.
m, _ = m.update(remoteImagesLoadedMsg{content: "stale", token: m.remoteImagesPass - 1})
if !m.remoteImagesLoading {
t.Error("expected the stale result to be ignored")
}
if got := m.viewport.GetContent(); got != "text without images" {
t.Errorf("expected the text to stay on screen, got: %q", got)
}
// The result of the current pass replaces the text-only content.
m, _ = m.update(remoteImagesLoadedMsg{content: "text with images", token: m.remoteImagesPass})
if m.remoteImagesLoading {
t.Error("expected the remote images to be reported as loaded")
}
if got := m.viewport.GetContent(); got != "text with images" {
t.Errorf("expected the rendered images on screen, got: %q", got)
}
if strings.Contains(m.View(), "Loading remote images") {
t.Errorf("expected the loading indicator to be gone, got: %q", m.View())
}
}
// TestViewsFillScreen checks that the views shown between documents (loading,
// error) and the pager before it has been sized fill the terminal height.
// Views that don't cover the whole screen leave whatever the previous frame
// drew on it, e.g. a document's status bar stuck at the bottom after going
// back to the stash.
func TestViewsFillScreen(t *testing.T) {
const height = 24
common := commonModel{cfg: Config{GlamourEnabled: true}, styles: newStyles(true), width: 80, height: height}
check := func(name, view string) {
t.Helper()
if got := strings.Count(view, "\n") + 1; got != height {
t.Errorf("expected the %s view to fill the screen, got %d lines, want %d", name, got, height)
}
}
stash := newStashModel(&common)
stash.setSize(80, height)
stash.loaded = true
check("stash", stash.view())
stash.viewState = stashStateLoadingDocument
check("loading", stash.view())
stash.viewState = stashStateShowingError
stash.err = errMsg{err: errors.New("boom")}
check("error", stash.view())
pager := newPagerModel(&common)
check("unsized pager", pager.View())
pager.setSize(80, height)
check("empty pager", pager.View())
pager.setContent("hello\nworld")
check("pager", pager.View())
}
// TestPagerRemoteImagesLoadError checks that a failed loading pass clears the
// loading indicator and reports the error, rather than leaving the indicator
// in the status bar forever.
func TestPagerRemoteImagesLoadError(t *testing.T) {
common := commonModel{cfg: Config{GlamourEnabled: true}, styles: newStyles(true), width: 80, height: 24}
m := newPagerModel(&common)
m.setSize(80, 24)
m.currentDocument = markdown{Note: "test.md", Body: "![](https://example.com/img.png)"}
m, _ = m.update(contentRenderedMsg{
content: "text without images",
body: m.currentDocument.Body,
remoteImagesPending: true,
})
if !m.remoteImagesLoading {
t.Fatal("expected the remote images to be reported as loading")
}
m, cmd := m.update(errMsg{err: errors.New("boom")})
if m.remoteImagesLoading {
t.Error("expected the loading indicator to be cleared")
}
if strings.Contains(m.View(), "Loading remote images") {
t.Errorf("expected the loading indicator to be gone, got: %q", m.View())
}
if !strings.Contains(m.View(), "boom") {
t.Errorf("expected the error to be reported, got: %q", m.View())
}
if cmd == nil {
t.Error("expected a status message timeout")
}
}
// staticViewModel renders a view that never changes, like the loading
// indicator between documents.
type staticViewModel struct{}
func (staticViewModel) Init() tea.Cmd { return nil }
func (m staticViewModel) Update(tea.Msg) (tea.Model, tea.Cmd) { return m, nil }
func (staticViewModel) View() tea.View {
v := tea.NewView("static")
v.AltScreen = true
return v
}
// syncBuffer is a buffer that can be read while the program writes to it.
type syncBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *syncBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *syncBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
// TestResizeRedrawsUnchangedView checks that a window resize redraws the
// screen even when the view doesn't change, e.g. while a document loads. The
// renderer must not skip the screen erase queued by the resize, or the
// terminal keeps whatever the previous frame drew, like a document's status
// bar left stuck at the bottom (fixed in bubbletea v2.0.9, see
// charmbracelet/bubbletea#1755).
func TestResizeRedrawsUnchangedView(t *testing.T) {
var out syncBuffer
p := tea.NewProgram(staticViewModel{},
tea.WithOutput(&out),
tea.WithInput(strings.NewReader("")),
tea.WithWindowSize(80, 24),
)
done := make(chan struct{})
go func() {
defer close(done)
// Wait for the initial frame, then resize to the same dimensions so
// that only the resize can redraw the screen.
time.Sleep(250 * time.Millisecond)
before := strings.Count(out.String(), "static")
p.Send(tea.WindowSizeMsg{Width: 80, Height: 24})
time.Sleep(250 * time.Millisecond)
if after := strings.Count(out.String(), "static"); after <= before {
t.Errorf("expected the screen to be redrawn on resize, got no redraw (frames before=%d, after=%d)",
before, after)
}
p.Send(tea.Quit())
}()
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
<-done
}
// testSVG is a small SVG document used in the SVG tests.
const testSVG = `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20">
<rect width="40" height="20" fill="red"/>
<circle cx="20" cy="10" r="8" fill="blue"/>
</svg>
`
// TestPagerKittySVGImages runs the pager on a document with an SVG image and
// checks that the vector image is rasterized and displayed like other
// images.
func TestPagerKittySVGImages(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "test.svg"), []byte(testSVG), 0o644); err != nil {
t.Fatal(err)
}
mdPath := filepath.Join(dir, "test.md")
if err := os.WriteFile(mdPath, []byte("# Hello\n\n![red](test.svg)\n\nBye!\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg := Config{
GlamourEnabled: true,
GlamourStyle: "dark",
GlamourMaxWidth: 80,
Images: true,
ImageProtocol: "kitty",
Path: mdPath,
}
m := newModel(cfg, "")
var out bytes.Buffer
p := tea.NewProgram(m,
tea.WithOutput(&out),
tea.WithInput(strings.NewReader("")),
tea.WithWindowSize(80, 24),
)
go func() {
time.Sleep(500 * time.Millisecond)
p.Send(tea.Quit())
}()
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
got := out.String()
// The SVG must be rasterized and transmitted as a PNG, and displayed via
// unicode placeholders.
if !strings.Contains(got, "\x1b_G") {
t.Errorf("expected the SVG to be transmitted, got: %q", got)
}
if !strings.ContainsRune(got, 0x10EEEE) {
t.Errorf("expected the SVG to be displayed via placeholders, got: %q", got)
}
// Displayed images don't render their URL next to them.
if strings.Contains(got, "test.svg") {
t.Errorf("expected the SVG URL not to be rendered next to the image, got: %q", got)
}
}
// kittyPlaceholder is the unicode placeholder cell that anchors an image to
// the text grid.
const kittyPlaceholder = '\U0010EEEE'
// escapeSequencePattern matches ANSI SGR, OSC 8 hyperlink, and graphics
// protocol sequences.
var escapeSequencePattern = regexp.MustCompile(`\x1b\]8;[^\x07\x9c]*(\x07|\x9c)|\x1b\[[0-9;:]*[a-zA-Z]|\x1b_G[^\x1b]*\x1b\\|\x1bP[^\x1b]*\x1b\\`)
// visibleText returns the text a terminal would display for the given
// rendered output, i.e. with all escape sequences removed.
func visibleText(s string) string {
return escapeSequencePattern.ReplaceAllString(s, "")
}
// testBadgeSVG is a badge in the shape of the ones served by shields.io: a
// background split in two, and text drawn in scaled groups.
const testBadgeSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="94" height="20">` +
`<g><rect width="49" height="20" fill="#555"/>` +
`<rect x="49" width="45" height="20" fill="#007ec6"/></g>` +
`<g fill="#fff" text-anchor="middle" font-size="110">` +
`<g transform="scale(.1)"><text x="255" y="140">release</text></g>` +
`<g transform="scale(.1)"><text x="705" y="140">v3.0.0</text></g></g></svg>`
// testPathBadgeSVG is a badge whose text is drawn as path outlines, and which
// uses arcs, like the badges served by godoc.org.
const testPathBadgeSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="90" height="20">` +
`<path d="M2 0h26v20H2a2 2 0 01-2-2V2a2 2 0 012-2z" fill="#5C5C5C"/>` +
`<path d="M87.99 0H28v20h59.99a2 2 0 002-2V2a2 2 0 00-2-2z" fill="#007D9C"/>` +
`<path d="M35 14v-3c0-2 2-3 4-3l1 0V14H35z" fill="#FAFAFA"/></svg>`
// TestPagerKittyBadges runs the pager on a README-style list of badges and
// checks that they are rasterized, drawn in the text flow, and rendered next
// to each other on one line, the way a browser renders them.
func TestPagerKittyBadges(t *testing.T) {
dir := t.TempDir()
for name, content := range map[string]string{
"release.svg": testBadgeSVG,
"doc.svg": testPathBadgeSVG,
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
mdPath := filepath.Join(dir, "test.md")
body := "<p>\n" +
" <a href=\"https://example.com\"><img src=\"release.svg\" alt=\"release\"></a>\n" +
" <a href=\"https://example.com\"><img src=\"doc.svg\" alt=\"doc\"></a>\n" +
"</p>\n"
if err := os.WriteFile(mdPath, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
cfg := Config{
GlamourEnabled: true,
GlamourStyle: "dark",
GlamourMaxWidth: 80,
Images: true,
ImageProtocol: "kitty",
}
common := commonModel{cfg: cfg, styles: newStyles(true), width: 80, height: 24}
common.imageProtocol = ansi.ImageProtocolKittyPlaceholders
pager := newPagerModel(&common)
pager.setSize(80, 24)
pager.currentDocument = markdown{Note: "test.md", localPath: mdPath, Body: body}
content, graphics, err := glamourRender(pager, body, false)
if err != nil {
t.Fatal(err)
}
// The two badges are rasterized and transmitted, and their placeholder
// grids are placed on the same line, separated by a space, the way a
// browser renders them.
if len(graphics) != 4 {
t.Errorf("expected transmit and place commands for both badges, got %d", len(graphics))
}
gridLines := 0
for _, line := range strings.Split(content, "\n") {
if !strings.ContainsRune(line, kittyPlaceholder) {
continue
}
gridLines++
grid := strings.TrimLeft(visibleText(line), " ")
if !strings.HasPrefix(grid, string(kittyPlaceholder)) {
t.Errorf("expected the line to start with a badge, got: %q", grid)
}
if got := strings.Count(grid, string(kittyPlaceholder)); got != 19 {
t.Errorf("expected 19 placeholder cells for both badges, got %d", got)
}
if !strings.Contains(grid, string(kittyPlaceholder)+" ") {
t.Errorf("expected a space between the badges, got: %q", grid)
}
}
if gridLines != 1 {
t.Fatalf("expected both badges on one line, got %d lines", gridLines)
}
}

261
utils/graphics.go Normal file
View file

@ -0,0 +1,261 @@
// Package utils provides utility functions.
package utils
import (
"bytes"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"charm.land/glamour/v2/ansi"
xansi "github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/ansi/kitty"
"golang.org/x/term"
)
// Image protocol names as accepted by the GLOW_IMAGE_PROTOCOL environment
// variable.
const (
ImageProtocolEnv = "GLOW_IMAGE_PROTOCOL"
ImageProtocolAuto = "auto"
ImageProtocolKitty = "kitty"
ImageProtocolSixel = "sixel"
ImageProtocolNone = "none"
)
// queryTimeout is how long DetectImageProtocol waits for terminal query
// responses before giving up. Terminals respond within a few milliseconds,
// so this only matters for terminals that don't respond at all.
const queryTimeout = 150 * time.Millisecond
// kittyQueryID is the image id used for the kitty graphics query. The
// terminal echoes it back in its response, and it must not collide with real
// image ids. KittyGraphicsOK reports whether a KittyGraphicsEvent is a
// successful response to [GraphicsQuery].
const kittyQueryID = 31
// DetectImageProtocol returns the graphics protocol the terminal attached to
// os.Stdout and os.Stdin supports.
//
// The GLOW_IMAGE_PROTOCOL environment variable can be set to "kitty",
// "sixel", "auto", or "none" to force a protocol and skip detection. With
// "auto" (the default), known terminals are detected via environment
// variables, and everything else is detected by querying the terminal: a
// kitty graphics query followed by a request for the primary device
// attributes, which also reports sixel support. Terminals that answer
// neither are assumed to not support graphics.
func DetectImageProtocol() ansi.ImageProtocol {
switch p := os.Getenv(ImageProtocolEnv); p {
case ImageProtocolKitty:
return ansi.ImageProtocolKitty
case ImageProtocolSixel:
return ansi.ImageProtocolSixel
case ImageProtocolNone:
return ansi.ImageProtocolNone
}
out, in := os.Stdout, os.Stdin
if !term.IsTerminal(int(out.Fd())) {
// Piping the output elsewhere: don't emit any graphics sequences.
return ansi.ImageProtocolNone
}
// Terminals we can identify by environment alone. This keeps them fast,
// as they don't need to be queried.
if protocol, ok := protocolFromEnvironment(); ok {
return protocol
}
if !term.IsTerminal(int(in.Fd())) {
// No way to read query responses, e.g. when rendering from stdin.
return ansi.ImageProtocolNone
}
resp, err := queryTerminal(out, in, graphicsQuery(), queryTimeout)
if err != nil {
return ansi.ImageProtocolNone
}
if hasKitty, hasSixel := parseQueryResponse(resp); hasKitty {
return ansi.ImageProtocolKitty
} else if hasSixel {
return ansi.ImageProtocolSixel
}
return ansi.ImageProtocolNone
}
// protocolFromEnvironment reports the graphics protocol of terminals that
// identify themselves via environment variables, and whether the terminal
// is known.
func protocolFromEnvironment() (ansi.ImageProtocol, bool) {
if os.Getenv("KITTY_WINDOW_ID") != "" {
return ansi.ImageProtocolKitty, true
}
termVar := os.Getenv("TERM")
switch {
case termVar == "xterm-kitty" || strings.HasPrefix(termVar, "kitty"):
return ansi.ImageProtocolKitty, true
case strings.Contains(termVar, "ghostty"), os.Getenv("GHOSTTY_RESOURCES_DIR") != "":
return ansi.ImageProtocolKitty, true
case os.Getenv("TERM_PROGRAM") == "WezTerm":
return ansi.ImageProtocolKitty, true
case strings.HasPrefix(termVar, "foot"):
// foot supports sixel but not the kitty graphics protocol.
return ansi.ImageProtocolSixel, true
}
return ansi.ImageProtocolNone, false
}
// GraphicsQuery returns a kitty graphics query that can be sent to the
// terminal to detect support for the kitty graphics protocol. Send it via
// tea.Raw and check the response with KittyGraphicsOK. It is the same query
// DetectImageProtocol uses.
// See https://sw.kovidgoyal.net/kitty/graphics-protocol/#checking-for-support
func GraphicsQuery() string {
return graphicsQuery()
}
// KittyGraphicsOK reports whether the given kitty graphics event is a
// successful response to [GraphicsQuery].
func KittyGraphicsOK(optionsID int, payload []byte) bool {
return optionsID == kittyQueryID && bytes.HasPrefix(payload, []byte("OK"))
}
// FileBaseURL returns a file:// URL for the directory containing the given
// file path, suitable as a glamour base URL, so that relative image
// references resolve correctly on all platforms. Relative paths are
// resolved against the current working directory.
func FileBaseURL(path string) string {
dir := filepath.Dir(path)
if !isWindowsDrivePath(dir) {
if abs, err := filepath.Abs(dir); err == nil {
dir = abs
}
}
s := filepath.ToSlash(dir)
if !strings.HasPrefix(s, "/") {
// A Windows drive letter, e.g. C:/Users/x, needs a leading slash to
// form a valid file URL path: /C:/Users/x.
s = "/" + s
}
u := url.URL{Scheme: "file", Path: s}
return u.String() + "/"
}
// isWindowsDrivePath reports whether the path starts with a Windows drive
// letter, like C:/Users/x. Such paths are absolute on Windows, and treated
// as absolute everywhere, so that documents render identically on all
// platforms.
func isWindowsDrivePath(path string) bool {
return len(path) >= 3 && path[1] == ':' && (path[2] == '/' || path[2] == '\\') &&
(path[0] >= 'a' && path[0] <= 'z' || path[0] >= 'A' && path[0] <= 'Z')
}
// graphicsQuery returns a kitty graphics query followed by a request for the
// primary device attributes. Terminals supporting the kitty graphics
// protocol must answer the graphics query immediately, and every terminal
// answers the device attributes request, which terminates the wait and
// reports sixel support.
func graphicsQuery() string {
opts := kitty.Options{
Action: kitty.Query,
ID: kittyQueryID,
// One 1x1 RGB pixel, base64 encoded as the payload.
ImageWidth: 1,
ImageHeight: 1,
Transmission: kitty.Direct,
Format: kitty.RGB,
}
return xansi.KittyGraphics([]byte("AAAA"), opts.Options()...) +
xansi.RequestPrimaryDeviceAttributes
}
// queryTerminal writes query to out, puts in into raw mode, and reads back
// the terminal's response until the primary device attributes response
// arrives. It gives up after the given timeout.
func queryTerminal(out, in *os.File, query string, timeout time.Duration) (string, error) {
fd := int(in.Fd())
oldState, err := term.MakeRaw(fd)
if err != nil {
return "", err
}
defer term.Restore(fd, oldState) //nolint:errcheck
if _, err := out.WriteString(query); err != nil {
return "", err
}
type result struct {
response string
err error
}
done := make(chan result, 1)
go func() {
var buf bytes.Buffer
b := make([]byte, 256)
for {
n, err := in.Read(b)
if n > 0 {
buf.Write(b[:n])
// The device attributes response terminates the query.
if hasDA1Response(buf.Bytes()) {
done <- result{response: buf.String()}
return
}
}
if err != nil {
done <- result{err: err}
return
}
}
}()
select {
case r := <-done:
return r.response, r.err
case <-time.After(timeout):
return "", nil
}
}
// hasDA1Response reports whether data contains a primary device attributes
// response, i.e. ESC [ ? ... c.
func hasDA1Response(data []byte) bool {
for i := 0; i+3 < len(data); i++ {
if data[i] == 0x1b && data[i+1] == '[' && data[i+2] == '?' &&
bytes.ContainsRune(data[i+3:], 'c') {
return true
}
}
return false
}
// parseQueryResponse reports whether the terminal's query response indicates
// support for the kitty graphics protocol and sixel graphics.
func parseQueryResponse(resp string) (hasKitty, hasSixel bool) {
// The kitty graphics protocol responds with _Gi=<id>;OK.
for _, part := range strings.Split(resp, "\x1b_G") {
options, payload, _ := strings.Cut(part, ";")
if strings.Contains(options, "i="+strconv.Itoa(kittyQueryID)) &&
strings.HasPrefix(payload, "OK") {
hasKitty = true
}
}
// DA1 responses are ESC [ ? <attrs> c, where attribute 4 indicates sixel
// support.
for _, part := range strings.Split(resp, "\x1b[?") {
attrs, ok := strings.CutSuffix(part, "c")
if !ok {
continue
}
for _, attr := range strings.Split(attrs, ";") {
if attr == "4" {
hasSixel = true
}
}
}
return hasKitty, hasSixel
}

215
utils/graphics_test.go Normal file
View file

@ -0,0 +1,215 @@
package utils
import (
"net/url"
"os"
"path/filepath"
"runtime"
"testing"
"charm.land/glamour/v2/ansi"
)
func TestProtocolFromEnvironment(t *testing.T) {
// Clear the variables the detection looks at so tests don't depend on
// the environment they run in.
clearEnv := func(env map[string]string) {
for _, k := range []string{"TERM", "TERM_PROGRAM", "KITTY_WINDOW_ID", "GHOSTTY_RESOURCES_DIR"} {
if _, ok := env[k]; !ok {
t.Setenv(k, "")
}
}
}
tests := []struct {
name string
env map[string]string
protocol ansi.ImageProtocol
known bool
}{
{
name: "kitty via KITTY_WINDOW_ID",
env: map[string]string{"KITTY_WINDOW_ID": "1"},
protocol: ansi.ImageProtocolKitty,
known: true,
},
{
name: "kitty via TERM",
env: map[string]string{"TERM": "xterm-kitty"},
protocol: ansi.ImageProtocolKitty,
known: true,
},
{
name: "ghostty via TERM",
env: map[string]string{"TERM": "ghostty"},
protocol: ansi.ImageProtocolKitty,
known: true,
},
{
name: "wezterm via TERM_PROGRAM",
env: map[string]string{"TERM": "xterm-256color", "TERM_PROGRAM": "WezTerm"},
protocol: ansi.ImageProtocolKitty,
known: true,
},
{
name: "foot",
env: map[string]string{"TERM": "foot-extra"},
protocol: ansi.ImageProtocolSixel,
known: true,
},
{
name: "unknown terminal",
env: map[string]string{"TERM": "xterm-256color"},
protocol: ansi.ImageProtocolNone,
known: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
clearEnv(tc.env)
for k, v := range tc.env {
t.Setenv(k, v)
}
protocol, known := protocolFromEnvironment()
if protocol != tc.protocol {
t.Errorf("expected protocol %v, got %v", tc.protocol, protocol)
}
if known != tc.known {
t.Errorf("expected known %v, got %v", tc.known, known)
}
})
}
}
func TestParseQueryResponse(t *testing.T) {
tests := []struct {
name string
resp string
hasKitty bool
hasSixel bool
}{
{
name: "kitty",
resp: "\x1b_Gi=31;OK\x1b\\\x1b[?62;c",
hasKitty: true,
},
{
name: "kitty with other ids",
resp: "\x1b_Gi=1;OK\x1b\\\x1b_Gi=31;OK\x1b\\\x1b[?62;c",
hasKitty: true,
},
{
name: "sixel only",
resp: "\x1b[?62;4;6;9;15;16;17;18;21c",
hasSixel: true,
},
{
name: "no graphics support",
resp: "\x1b[?1;2c",
},
{
name: "kitty error response",
resp: "\x1b_Gi=31;EN\x1b\\\x1b[?62;c",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
hasKitty, hasSixel := parseQueryResponse(tc.resp)
if hasKitty != tc.hasKitty {
t.Errorf("expected kitty %v, got %v", tc.hasKitty, hasKitty)
}
if hasSixel != tc.hasSixel {
t.Errorf("expected sixel %v, got %v", tc.hasSixel, hasSixel)
}
})
}
}
func TestHasDA1Response(t *testing.T) {
if !hasDA1Response([]byte("\x1b[?62;4c")) {
t.Error("expected DA1 response to be detected")
}
if hasDA1Response([]byte("\x1b_Gi=31;OK\x1b\\")) {
t.Error("expected no DA1 response to be detected")
}
if hasDA1Response([]byte("garbage")) {
t.Error("expected no DA1 response to be detected")
}
}
func TestFileBaseURL(t *testing.T) {
tests := []struct {
path string
want string
}{
// Windows-style absolute paths resolve the same everywhere.
{"C:/Users/x/test.md", "file:///C:/Users/x/"},
}
// Unix-style absolute paths are absolute only on Unix; on Windows they
// resolve against the current drive.
if runtime.GOOS != "windows" {
tests = append(tests, struct {
path string
want string
}{"/tmp/docs/test.md", "file:///tmp/docs/"})
}
for _, tc := range tests {
if got := FileBaseURL(tc.path); got != tc.want {
t.Errorf("FileBaseURL(%q) = %q, want %q", tc.path, got, tc.want)
}
}
// Relative paths resolve against the working directory. The expected
// URL is built from os.Getwd, since the working directory is only
// known at runtime, and may differ from the temp dir path on platforms
// with symlinked temporary directories, like macOS.
dir := t.TempDir()
t.Chdir(dir)
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
// Build the expected URL the same way FileBaseURL does: the path is
// slash-separated, and drive-letter paths get a leading slash.
want := fileURL(wd) + "/"
for _, path := range []string{"", "test.md", "./test.md", "sub/../test.md"} {
if got := FileBaseURL(path); got != want {
t.Errorf("FileBaseURL(%q) = %q, want %q", path, got, want)
}
}
want = fileURL(filepath.Join(wd, "img")) + "/"
for _, path := range []string{"sub/../img/test.md"} {
if got := FileBaseURL(path); got != want {
t.Errorf("FileBaseURL(%q) = %q, want %q", path, got, want)
}
}
want = fileURL(filepath.Join(wd, "..", "img")) + "/"
for _, path := range []string{"../img/test.md"} {
if got := FileBaseURL(path); got != want {
t.Errorf("FileBaseURL(%q) = %q, want %q", path, got, want)
}
}
}
func TestGraphicsQuery(t *testing.T) {
q := graphicsQuery()
if want := "\x1b_Gf=24,i=31,s=1,v=1,a=q;AAAA\x1b\\"; q != want+"\x1b[c" {
t.Errorf("unexpected query %q", q)
}
}
// fileURL returns the file URL of a slash-separated path, adding the leading
// slash that drive-letter paths need (see FileBaseURL).
func fileURL(path string) string {
s := filepath.ToSlash(path)
if isWindowsDrivePath(s) {
s = "/" + s
}
return (&url.URL{Scheme: "file", Path: s}).String()
}

View file

@ -1,393 +0,0 @@
package utils
import (
"fmt"
"io"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"charm.land/glamour/v2/ansi"
"github.com/muesli/cancelreader"
"github.com/rivo/uniseg"
"golang.org/x/term"
)
const (
osc66ST = "\x1b\\"
osc66MaxPayload = 4000
markerPrefix = "\x1b]6666;"
markerClose = markerPrefix + "0" + osc66ST
)
var textSizingEnabled = sync.OnceValue(detectTextSizing)
// TextSizingEnabled reports whether the terminal supports kitty's text
// sizing protocol (OSC 66), auto-detecting support on first call and caching
// the result. Set GLOW_TEXT_SIZING to on/off to override detection.
func TextSizingEnabled() bool {
return textSizingEnabled()
}
func detectTextSizing() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("GLOW_TEXT_SIZING"))) {
case "0", "false", "off", "no":
return false
case "1", "true", "on", "yes":
return true
}
if !term.IsTerminal(int(os.Stdout.Fd())) {
return false
}
if termEnv := os.Getenv("TERM"); termEnv == "" || termEnv == "dumb" {
return false
}
if supported, decisive := probeTextSizing(); decisive {
return supported
}
return os.Getenv("KITTY_WINDOW_ID") != "" ||
os.Getenv("TERM_PROGRAM") == "kitty" ||
strings.Contains(os.Getenv("TERM"), "kitty")
}
var cprPattern = regexp.MustCompile(`\x1b\[(\d+);(\d+)R`)
func probeTextSizing() (supported, decisive bool) {
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
return false, false
}
defer func() { _ = tty.Close() }()
fd := int(tty.Fd())
oldState, err := term.MakeRaw(fd)
if err != nil {
return false, false
}
defer func() { _ = term.Restore(fd, oldState) }()
reader, err := cancelreader.NewReader(tty)
if err != nil {
return false, false
}
defer func() { _ = reader.Close() }()
if _, err := io.WriteString(tty, "\r\x1b[6n\x1b]66;w=2; \a\x1b[6n\r"); err != nil {
return false, false
}
timer := time.AfterFunc(800*time.Millisecond, func() { reader.Cancel() })
defer timer.Stop()
var buf []byte
tmp := make([]byte, 128)
nextCol := func() (int, bool) {
for {
if loc := cprPattern.FindSubmatchIndex(buf); loc != nil {
col, _ := strconv.Atoi(string(buf[loc[4]:loc[5]]))
buf = buf[loc[1]:]
return col, true
}
n, rerr := reader.Read(tmp)
if n > 0 {
buf = append(buf, tmp[:n]...)
}
if rerr != nil {
return 0, false
}
}
}
before, ok := nextCol()
if !ok {
return false, false
}
after, ok := nextCol()
if !ok {
return false, true
}
return after-before == 2, true
}
func markerOpen(level int) string {
return markerPrefix + strconv.Itoa(level) + osc66ST
}
func markerLevel(s string) int {
if !strings.HasPrefix(s, markerPrefix) {
return -1
}
rest := s[len(markerPrefix):]
if len(rest) < 1+len(osc66ST) || rest[0] < '0' || rest[0] > '9' || !strings.HasPrefix(rest[1:], osc66ST) {
return -1
}
return int(rest[0] - '0')
}
// AddHeadingSizeMarkers marks the heading styles of levels 1 to 3 in the
// given style config so that ApplyTextSizing can find the rendered heading
// text and scale it. Headings with a background color are left unmarked:
// the background does not cover the scaled glyphs and renders broken.
// The style config is modified in place; pass a copy if the original is
// shared.
func AddHeadingSizeMarkers(cfg *ansi.StyleConfig) {
blocks := []struct {
level int
block *ansi.StyleBlock
}{
{1, &cfg.H1},
{2, &cfg.H2},
{3, &cfg.H3},
}
for _, b := range blocks {
if b.block.BackgroundColor != nil {
continue
}
prefix := b.block.Prefix
if strings.HasPrefix(prefix, "#") {
prefix = strings.TrimPrefix(strings.TrimLeft(prefix, "#"), " ")
}
b.block.Prefix = markerOpen(b.level) + prefix
b.block.Suffix += markerClose
}
}
func headingRows(level int) int {
if level == 1 {
return 3
}
return 2
}
// ApplyTextSizing replaces the heading markers inserted by
// AddHeadingSizeMarkers with kitty text sizing (OSC 66) sequences: level 1
// headings are scaled 3x, level 2 headings 2x, and level 3 headings 1.5x via
// fractional scaling with a tight width so glyphs keep their natural width.
// Output without markers is returned unchanged.
func ApplyTextSizing(s string) string {
if !strings.Contains(s, markerPrefix) {
return s
}
var b strings.Builder
b.Grow(len(s))
for len(s) > 0 {
i := strings.Index(s, markerPrefix)
if i < 0 {
b.WriteString(s)
break
}
b.WriteString(s[:i])
s = s[i:]
level := markerLevel(s)
if level < 0 {
b.WriteString(markerPrefix)
s = s[len(markerPrefix):]
continue
}
s = s[len(markerOpen(level)):]
if level < 1 || level > 3 {
continue
}
end := strings.Index(s, markerClose)
if end < 0 {
b.WriteString(s)
break
}
writeSizedSpan(&b, level, s[:end])
s = s[end+len(markerClose):]
b.WriteString(strings.Repeat("\n", headingRows(level)-1))
}
return b.String()
}
func writeSizedSpan(b *strings.Builder, level int, span string) {
lines := strings.Split(span, "\n")
for i, ln := range lines {
if i > 0 {
b.WriteString(strings.Repeat("\n", headingRows(level)))
}
writeSizedLine(b, level, ln, i > 0)
}
}
type segment struct {
escape bool
value string
}
func writeSizedLine(b *strings.Builder, level int, ln string, continuation bool) {
var segs []segment
for len(ln) > 0 {
i := strings.IndexByte(ln, '\x1b')
if i < 0 {
segs = append(segs, segment{value: ln})
break
}
if i > 0 {
segs = append(segs, segment{value: ln[:i]})
ln = ln[i:]
continue
}
seq := scanEscape(ln)
segs = append(segs, segment{escape: true, value: seq})
ln = ln[len(seq):]
}
firstContent, lastContent := -1, -1
for i, sg := range segs {
if !sg.escape && strings.Trim(sg.value, " \t") != "" {
if firstContent < 0 {
firstContent = i
}
lastContent = i
}
}
for i, sg := range segs {
if sg.escape || firstContent < 0 {
b.WriteString(sg.value)
continue
}
text := sg.value
switch {
case i < firstContent && continuation:
b.WriteString(text)
continue
case i > lastContent:
b.WriteString(text)
continue
}
if i == firstContent && continuation {
trimmed := strings.TrimLeft(text, " \t")
b.WriteString(text[:len(text)-len(trimmed)])
text = trimmed
}
var trail string
if i == lastContent {
trimmed := strings.TrimRight(text, " \t")
trail = text[len(trimmed):]
text = trimmed
}
if text != "" {
b.WriteString(sizedChunk(level, text))
}
b.WriteString(trail)
}
}
func scanEscape(s string) string {
if len(s) < 2 {
return s
}
switch s[1] {
case '[':
for i := 2; i < len(s); i++ {
if s[i] >= 0x40 && s[i] <= 0x7e {
return s[:i+1]
}
}
return s
case ']':
for i := 2; i < len(s); i++ {
if s[i] == '\a' {
return s[:i+1]
}
if s[i] == '\x1b' && i+1 < len(s) && s[i+1] == '\\' {
return s[:i+2]
}
}
return s
default:
i := 1
for i < len(s) && s[i] >= 0x20 && s[i] <= 0x2f {
i++
}
if i < len(s) {
i++
}
return s[:i]
}
}
func sizedChunk(level int, text string) string {
text = strings.Map(func(r rune) rune {
if r < 0x20 || (r >= 0x7f && r <= 0x9f) {
return -1
}
return r
}, text)
if text == "" {
return ""
}
switch level {
case 1:
return osc66Chunks("s=3", text)
case 2:
return osc66Chunks("s=2", text)
default:
return osc66TightChunks(text)
}
}
func osc66Chunks(meta, text string) string {
var b strings.Builder
var chunk strings.Builder
g := uniseg.NewGraphemes(text)
for g.Next() {
cluster := g.Str()
if chunk.Len() > 0 && chunk.Len()+len(cluster) > osc66MaxPayload {
writeOSC66(&b, meta, chunk.String())
chunk.Reset()
}
chunk.WriteString(cluster)
}
if chunk.Len() > 0 {
writeOSC66(&b, meta, chunk.String())
}
return b.String()
}
func osc66TightChunks(text string) string {
var b strings.Builder
var chunk strings.Builder
width := 0
flush := func() {
if chunk.Len() == 0 {
return
}
w := (width*3 + 3) / 4
writeOSC66(&b, fmt.Sprintf("s=2:n=3:d=4:w=%d", w), chunk.String())
chunk.Reset()
width = 0
}
g := uniseg.NewGraphemes(text)
for g.Next() {
cluster := g.Str()
cw := uniseg.StringWidth(cluster)
if width > 0 && width+cw > 4 {
flush()
}
chunk.WriteString(cluster)
width += cw
}
flush()
return b.String()
}
func writeOSC66(b *strings.Builder, meta, text string) {
b.WriteString("\x1b]66;")
b.WriteString(meta)
b.WriteByte(';')
b.WriteString(text)
b.WriteString(osc66ST)
}

View file

@ -1,222 +0,0 @@
package utils
import (
"strings"
"sync"
"testing"
"charm.land/glamour/v2"
"charm.land/glamour/v2/styles"
)
func renderPlainAndSized(t *testing.T, markdown string, wordWrap int) (string, string) {
t.Helper()
cfg := styles.DarkStyleConfig
// Headings with a background are not scaled, so drop the dark style's
// H1 background to exercise H1 scaling.
cfg.H1.BackgroundColor = nil
r, err := glamour.NewTermRenderer(
glamour.WithStyles(cfg),
glamour.WithWordWrap(wordWrap),
)
if err != nil {
t.Fatal(err)
}
plain, err := r.Render(markdown)
if err != nil {
t.Fatal(err)
}
AddHeadingSizeMarkers(&cfg)
r, err = glamour.NewTermRenderer(
glamour.WithStyles(cfg),
glamour.WithWordWrap(wordWrap),
)
if err != nil {
t.Fatal(err)
}
marked, err := r.Render(markdown)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(marked, markerPrefix) {
t.Fatal("rendered output does not contain heading markers")
}
return plain, ApplyTextSizing(marked)
}
func TestAddHeadingSizeMarkersSkipsBackground(t *testing.T) {
cfg := styles.DarkStyleConfig
AddHeadingSizeMarkers(&cfg)
if strings.Contains(cfg.H1.Prefix, markerPrefix) || strings.Contains(cfg.H1.Suffix, markerPrefix) {
t.Errorf("expected H1 with background color to be left unmarked, got %q/%q", cfg.H1.Prefix, cfg.H1.Suffix)
}
if !strings.HasPrefix(cfg.H2.Prefix, markerOpen(2)) {
t.Errorf("expected H2 to be marked, got %q", cfg.H2.Prefix)
}
if !strings.HasPrefix(cfg.H3.Prefix, markerOpen(3)) {
t.Errorf("expected H3 to be marked, got %q", cfg.H3.Prefix)
}
}
func TestApplyTextSizingPassthrough(t *testing.T) {
in := "hello \x1b[1mworld\x1b[0m"
if got := ApplyTextSizing(in); got != in {
t.Errorf("expected output unchanged, got %q", got)
}
}
func TestApplyTextSizingMalformedMarker(t *testing.T) {
in := "a" + markerPrefix // truncated marker at end of string
if got := ApplyTextSizing(in); got != in {
t.Errorf("expected malformed marker preserved verbatim, got %q", got)
}
in = "a" + markerPrefix + "x" // non-digit level
if got := ApplyTextSizing(in); got != in {
t.Errorf("expected malformed marker preserved verbatim, got %q", got)
}
}
func TestApplyTextSizingLevels(t *testing.T) {
_, sized := renderPlainAndSized(t, "# Hello\n\n## World\n\n### Third\n", 80)
if !strings.Contains(sized, "\x1b]66;s=3;Hello\x1b\\") {
t.Errorf("expected H1 text at 3x scale, got %q", sized)
}
if !strings.Contains(sized, "\x1b]66;s=3; \x1b\\") {
t.Errorf("expected H1 prefix space at 3x scale, got %q", sized)
}
if !strings.Contains(sized, "\x1b]66;s=2;World\x1b\\") {
t.Errorf("expected H2 text at 2x scale, got %q", sized)
}
if !strings.Contains(sized, "\x1b]66;s=2:n=3:d=4:w=3;Thir\x1b\\") {
t.Errorf("expected H3 chunks at tight 1.5x scale, got %q", sized)
}
if !strings.Contains(sized, "\x1b]66;s=2:n=3:d=4:w=1;d\x1b\\") {
t.Errorf("expected H3 remainder chunk at tight 1.5x scale, got %q", sized)
}
if strings.Contains(sized, markerPrefix) {
t.Errorf("expected all markers to be replaced, got %q", sized)
}
}
func TestApplyTextSizingCompensationLines(t *testing.T) {
plain, sized := renderPlainAndSized(t, "# Hello\n\n## World\n\n### Third\n\nparagraph\n", 80)
if diff := strings.Count(sized, "\n") - strings.Count(plain, "\n"); diff != 4 {
t.Errorf("expected 4 extra newlines (2 for H1, 1 each for H2/H3), got %d", diff)
}
}
func TestApplyTextSizingWrappedHeading(t *testing.T) {
plain, sized := renderPlainAndSized(t, "# aaa bbb ccc\n\npara\n", 8)
plainLines := strings.Split(plain, "\n")
sizedLines := strings.Split(sized, "\n")
plainHead := lineIndex(t, plainLines, "aaa")
plainPara := lineIndex(t, plainLines, "para")
sizedHead := lineIndex(t, sizedLines, "aaa")
sizedPara := lineIndex(t, sizedLines, "para")
headLines := plainPara - plainHead - 1
if headLines < 2 {
t.Fatalf("expected heading to wrap, got %d line(s)", headLines)
}
if got, want := sizedPara-sizedHead, headLines*3+1; got != want {
t.Errorf("expected wrapped heading to occupy %d rows, got %d", want, got)
}
}
func TestApplyTextSizingNestedStyles(t *testing.T) {
_, sized := renderPlainAndSized(t, "# Hello *World*\n", 80)
if !strings.Contains(sized, "\x1b]66;s=3;Hello \x1b\\") {
t.Errorf("expected first chunk at 3x scale, got %q", sized)
}
if !strings.Contains(sized, "\x1b]66;s=3;World\x1b\\") {
t.Errorf("expected emphasized chunk at 3x scale, got %q", sized)
}
}
func TestDetectTextSizingEnvOverride(t *testing.T) {
t.Setenv("GLOW_TEXT_SIZING", "off")
if detectTextSizing() {
t.Error("expected detection to be disabled")
}
t.Setenv("GLOW_TEXT_SIZING", "on")
if !detectTextSizing() {
t.Error("expected detection to be forced on")
}
}
func TestGlamourStyleTextSizing(t *testing.T) {
render := func(t *testing.T) string {
t.Helper()
r, err := glamour.NewTermRenderer(
GlamourStyle(styles.DarkStyle, false),
glamour.WithWordWrap(80),
)
if err != nil {
t.Fatal(err)
}
out, err := r.Render("# Hello\n\n## World\n")
if err != nil {
t.Fatal(err)
}
return out
}
textSizingEnabled = sync.OnceValue(detectTextSizing)
t.Setenv("GLOW_TEXT_SIZING", "off")
if out := render(t); strings.Contains(out, markerPrefix) {
t.Errorf("expected no heading markers when disabled, got %q", out)
}
textSizingEnabled = sync.OnceValue(detectTextSizing)
t.Setenv("GLOW_TEXT_SIZING", "on")
out := render(t)
if strings.Contains(out, markerOpen(1)) {
t.Errorf("expected no H1 markers (background color), got %q", out)
}
if !strings.Contains(out, markerOpen(2)) {
t.Errorf("expected H2 markers when enabled, got %q", out)
}
sized := ApplyTextSizing(out)
if strings.Contains(sized, "\x1b]66;s=3;") {
t.Errorf("expected no 3x scaling for H1, got %q", sized)
}
if !strings.Contains(sized, "\x1b]66;s=2;") {
t.Errorf("expected OSC 66 sequences after ApplyTextSizing, got %q", sized)
}
}
func TestScanEscape(t *testing.T) {
tt := []struct{ in, want string }{
{"\x1b[1;31mfoo", "\x1b[1;31m"},
{"\x1b[0m", "\x1b[0m"},
{"\x1b]66;s=2;hi\a rest", "\x1b]66;s=2;hi\a"},
{"\x1b]6666;1\x1b\\x", "\x1b]6666;1\x1b\\"},
{"\x1b(B", "\x1b(B"},
}
for _, tc := range tt {
if got := scanEscape(tc.in); got != tc.want {
t.Errorf("scanEscape(%q) = %q, want %q", tc.in, got, tc.want)
}
}
}
func lineIndex(t *testing.T, lines []string, substr string) int {
t.Helper()
for i, ln := range lines {
if strings.Contains(ln, substr) {
return i
}
}
t.Fatalf("no line contains %q", substr)
return -1
}

View file

@ -2,8 +2,6 @@
package utils
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
@ -73,66 +71,43 @@ func IsMarkdownFile(filename string) bool {
// GlamourStyle returns a glamour.TermRendererOption based on the given style.
func GlamourStyle(style string, isCode bool) glamour.TermRendererOption {
return func(tr *glamour.TermRenderer) error {
styleConfig, err := styleConfigFor(style, isCode)
if err != nil {
return err
}
if !isCode && TextSizingEnabled() {
AddHeadingSizeMarkers(&styleConfig)
}
if err := glamour.WithStyles(styleConfig)(tr); err != nil {
return fmt.Errorf("glamour: error applying styles: %w", err)
}
return nil
}
}
func styleConfigFor(style string, isCode bool) (ansi.StyleConfig, error) {
if !isCode {
if style == "auto" {
style = styles.DarkStyle
return glamour.WithStandardStyle("dark")
}
if cfg, ok := styles.DefaultStyles[style]; ok {
return *cfg, nil
}
return styleConfigFromFile(style)
return glamour.WithStylePath(style)
}
// If we are rendering a pure code block, we need to modify the style to
// remove the indentation.
var styleConfig ansi.StyleConfig
switch style {
case "auto":
if lipgloss.HasDarkBackground(os.Stdin, os.Stdout) {
style = styles.DarkStyle
styleConfig = styles.DarkStyleConfig
} else {
style = styles.LightStyle
styleConfig = styles.LightStyleConfig
}
case styles.DarkStyle:
styleConfig = styles.DarkStyleConfig
case styles.LightStyle:
styleConfig = styles.LightStyleConfig
case styles.PinkStyle:
styleConfig = styles.PinkStyleConfig
case styles.NoTTYStyle:
styleConfig = styles.NoTTYStyleConfig
case styles.DraculaStyle:
styleConfig = styles.DraculaStyleConfig
case styles.TokyoNightStyle:
style = styles.DraculaStyle
case styles.DarkStyle, styles.LightStyle, styles.PinkStyle,
styles.NoTTYStyle, styles.DraculaStyle:
styleConfig = styles.DraculaStyleConfig
default:
return styleConfigFromFile(style)
return glamour.WithStylesFromJSONFile(style)
}
styleConfig := *styles.DefaultStyles[style]
var margin uint
styleConfig.CodeBlock.Margin = &margin
return styleConfig, nil
}
func styleConfigFromFile(path string) (ansi.StyleConfig, error) {
jsonBytes, err := os.ReadFile(path) //nolint:gosec
if err != nil {
return ansi.StyleConfig{}, fmt.Errorf("glamour: error reading file: %w", err)
}
var styleConfig ansi.StyleConfig
if err := json.Unmarshal(jsonBytes, &styleConfig); err != nil {
return ansi.StyleConfig{}, fmt.Errorf("glamour: error parsing style file: %w", err)
}
return styleConfig, nil
return glamour.WithStyles(styleConfig)
}