diff --git a/README.md b/README.md
index a4bf082..e6253a5 100644
--- a/README.md
+++ b/README.md
@@ -182,6 +182,14 @@ 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
@@ -236,6 +244,8 @@ preserveNewLines: false
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
diff --git a/config_cmd.go b/config_cmd.go
index 390a1db..38ff048 100644
--- a/config_cmd.go
+++ b/config_cmd.go
@@ -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{
diff --git a/glow_test.go b/glow_test.go
index 8743be2..9f5a5d6 100644
--- a/glow_test.go
+++ b/glow_test.go
@@ -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")
+ }
+}
diff --git a/go.mod b/go.mod
index 03d6437..144a6b9 100644
--- a/go.mod
+++ b/go.mod
@@ -1,6 +1,6 @@
module charm.land/glow/v3
-go 1.26.6
+go 1.26.7
require (
charm.land/bubbles/v2 v2.1.1
@@ -75,3 +75,5 @@ require (
golang.org/x/sync v0.22.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
)
+
+replace charm.land/glamour/v2 => ../glamour
diff --git a/go.sum b/go.sum
index 96b355d..f7766cf 100644
--- a/go.sum
+++ b/go.sum
@@ -2,8 +2,6 @@ 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.2-0.20260914112920-7bb50a2ac56e h1:67sj0XF2s+6HQB0qTHRr85jn2bH+VO4J8C13IrNAc3Y=
-charm.land/glamour/v2 v2.0.2-0.20260914112920-7bb50a2ac56e/go.mod h1:DVWY5TvsW6XwY/15kxvfvSxXWO+hZLaPCD5e8cyxwwY=
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=
diff --git a/main.go b/main.go
index 7a66d29..eb49445 100644
--- a/main.go
+++ b/main.go
@@ -47,6 +47,7 @@ var (
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.
@@ -183,6 +184,7 @@ func validateOptions(cmd *cobra.Command) error {
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")
@@ -327,6 +329,11 @@ func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error {
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...)
@@ -398,6 +405,8 @@ func runTUI(path string, content string) error {
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
if _, err := ui.NewProgram(cfg, content).Run(); err != nil {
@@ -477,6 +486,7 @@ func init() {
viper.SetDefault("all", true)
viper.SetDefault("images", true)
viper.SetDefault("imageMaxRows", 20)
+ viper.SetDefault("loadRemoteImages", false)
rootCmd.AddCommand(configCmd, manCmd)
}
diff --git a/ui/config.go b/ui/config.go
index 53acd5f..bc3348f 100644
--- a/ui/config.go
+++ b/ui/config.go
@@ -20,6 +20,14 @@ type Config struct {
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
diff --git a/ui/pager.go b/ui/pager.go
index f770711..7cdb82e 100644
--- a/ui/pager.go
+++ b/ui/pager.go
@@ -4,9 +4,11 @@ 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"
@@ -27,16 +29,83 @@ 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.
+// , and HTML ones, i.e.
, that are
+// fetched over the network.
+var remoteImagePattern = regexp.MustCompile(`(?i)!\[[^\]]*\]\(\s*["']?https?://|
]+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 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.
+ // 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{}
)
@@ -66,6 +135,15 @@ type pagerModel struct {
// 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
}
@@ -73,10 +151,15 @@ func newPagerModel(common *commonModel) pagerModel {
// Init viewport
vp := viewport.New()
+ sp := spinner.New()
+ sp.Spinner = spinner.Line
+ sp.Style = common.styles.stashSpinnerStyle
+
m := pagerModel{
- common: common,
- state: pagerStateBrowse,
- viewport: vp,
+ common: common,
+ state: pagerStateBrowse,
+ viewport: vp,
+ remoteSpinner: sp,
}
m.initWatcher()
return m
@@ -135,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()
@@ -195,18 +279,52 @@ func (m pagerModel) update(msg tea.Msg) (pagerModel, tea.Cmd) {
case contentRenderedMsg:
log.Info("content rendered", "state", m.state)
+ 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.Raw(strings.Join(msg.graphics, ""))
+ 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)
+
+ // 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 != "" {
@@ -286,9 +404,12 @@ func (m pagerModel) statusBarView(b *strings.Builder) {
// Note
var note string
- if showStatusMessage {
+ switch {
+ case m.remoteImagesLoading:
+ note = m.remoteSpinner.View() + " Loading remote images..."
+ case showStatusMessage:
note = m.statusMessage
- } else {
+ default:
note = m.currentDocument.Note
}
note = truncate.StringWithTail(" "+note+" ", uint(max(0, //nolint:gosec
@@ -297,7 +418,10 @@ func (m pagerModel) statusBarView(b *strings.Builder) {
ansi.PrintableRuneWidth(scrollPercent)-
ansi.PrintableRuneWidth(helpNote),
)), ellipsis)
- if showStatusMessage {
+ // 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
+ if showMessage {
note = styles.statusBarMessageStyle(note)
} else {
note = styles.statusBarNoteStyle(note)
@@ -312,7 +436,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)
@@ -369,14 +493,56 @@ 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, graphics, 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{content: s, graphics: graphics}
+ 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}
}
}
@@ -388,7 +554,7 @@ func glamourImages(m pagerModel) bool {
}
// This is where the magic happens.
-func glamourRender(m pagerModel, markdown string) (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
@@ -426,6 +592,16 @@ func glamourRender(m pagerModel, markdown string) (string, []string, error) {
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 {
diff --git a/ui/ui_test.go b/ui/ui_test.go
index 6f1332b..6782420 100644
--- a/ui/ui_test.go
+++ b/ui/ui_test.go
@@ -5,9 +5,12 @@ import (
"image"
"image/color"
"image/png"
+ "net/http"
+ "net/http/httptest"
"os"
"path/filepath"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -15,9 +18,8 @@ import (
"charm.land/glamour/v2/ansi"
)
-// writeTestFiles creates a markdown document referencing a PNG image and
-// returns the markdown file's path.
-func writeTestFiles(t *testing.T) string {
+// 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))
@@ -30,12 +32,32 @@ func writeTestFiles(t *testing.T) string {
if err := png.Encode(&pngBuf, img); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(filepath.Join(t.TempDir(), "test.png"), pngBuf.Bytes(), 0o644); err != nil {
+ 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)
}
dir := t.TempDir()
- if err := os.WriteFile(filepath.Join(dir, "test.png"), pngBuf.Bytes(), 0o644); err != nil {
+ if err := os.WriteFile(filepath.Join(dir, "test.png"), testPNG(t), 0o644); err != nil {
t.Fatal(err)
}
mdPath := filepath.Join(dir, "test.md")
@@ -165,3 +187,232 @@ func TestCommonModelImageProtocol(t *testing.T) {
}
}
}
+
+// 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
+ }{
+ {"", true},
+ {"", true},
+ {`
`, 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},
+ {"", false},
+ {"[alt](https://example.com)", false},
+ {`
`, 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\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 := ""
+
+ 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\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: ""}
+
+ 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())
+ }
+}