From d52e838819e847cc78d0d1ffe5d0c2a75361c487 Mon Sep 17 00:00:00 2001 From: Ted Kulp Date: Tue, 20 Oct 2026 07:11:41 -0400 Subject: [PATCH 1/4] Yank and put use the system clipboard Every write to the unnamed register also goes to the system clipboard, and puts from the unnamed register, "+ and "* read it back. Text equal to the unnamed register is pholio's own, so the register keeps its shape. seam.SystemClipboard runs wl-copy/xclip/xsel/pbcopy; when writing fails the app sends the text with OSC 52 instead. Closes #75 Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 3 + cmd/pholio/main.go | 2 +- go.sum | 6 ++ internal/app/app.go | 14 ++- internal/app/clipboard.go | 37 +++++++ internal/app/clipboard_test.go | 92 +++++++++++++++++ internal/engine/clipboard.go | 40 ++++++++ internal/engine/clipboard_test.go | 154 +++++++++++++++++++++++++++++ internal/engine/engine.go | 4 + internal/engine/operators.go | 9 +- internal/seam/clipboard.go | 80 +++++++++++++++ internal/seam/clipboard_test.go | 68 +++++++++++++ internal/seam/seam.go | 9 +- internal/seam/seamtest/seamtest.go | 50 ++++++++++ 14 files changed, 563 insertions(+), 5 deletions(-) create mode 100644 internal/app/clipboard.go create mode 100644 internal/app/clipboard_test.go create mode 100644 internal/engine/clipboard.go create mode 100644 internal/engine/clipboard_test.go create mode 100644 internal/seam/clipboard.go create mode 100644 internal/seam/clipboard_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index d7d740c..7ceec59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Added +- Yank, delete and put use the system clipboard, like vim's `clipboard=unnamedplus`: every write to the unnamed register also goes to the clipboard, and `p`/`P` paste what's on it, so text moves between pholio and other apps. `"+` and `"*` name the clipboard; `"a`–`"z` and `"0`–`"9` stay internal. Text copied in another app pastes as lines when it ends in a newline, else inline; pholio's own yanks keep their shape (lines or a block). pholio uses `wl-copy`/`wl-paste`, `xclip` or `xsel`, or `pbcopy`/`pbpaste`, and without them (as over SSH) writes the clipboard with OSC 52, where puts use the internal register. + ## [0.6.1] - 2026-10-12 ### Added diff --git a/cmd/pholio/main.go b/cmd/pholio/main.go index c266ae4..e9c4039 100644 --- a/cmd/pholio/main.go +++ b/cmd/pholio/main.go @@ -64,7 +64,7 @@ func run(args []string) error { // With no file argument this opens (or creates) today's Daily Note. deps := app.Deps{ FS: fsys, Clock: clock, Watch: vault, Opener: seam.SystemOpener{}, Index: ix, - Trash: seam.NewSystemTrash(os.Getenv, home, clock), + Trash: seam.NewSystemTrash(os.Getenv, home, clock), Clipboard: seam.NewSystemClipboard(os.Getenv), } m, err := app.Start(deps, s) if err != nil { diff --git a/go.sum b/go.sum index 118e44c..16a533d 100644 --- a/go.sum +++ b/go.sum @@ -14,6 +14,7 @@ github.com/arran4/golang-ical v0.3.7 h1:ONEzzLJqP9aQpXzO6ArsdRshApsWIr6hkMV28RdI github.com/arran4/golang-ical v0.3.7/go.mod h1:OnguFgjN0Hmx8jzpmWcC+AkHio94ujmLHKoaef7xQh8= github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o= github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w= +github.com/bits-and-blooms/bitset v1.24.6/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 h1:rdnVWKgJpTVXKuKuJyxDJ+NFJdUaUqGvyGy61OcvlbA= @@ -36,6 +37,7 @@ github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2 github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k= github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA= github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -48,12 +50,14 @@ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU= github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= @@ -72,5 +76,7 @@ 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.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/app/app.go b/internal/app/app.go index 3def29e..578c005 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -31,6 +31,9 @@ type Deps struct { Index *index.Index // Trash takes deleted Notes and folders (d in the tree, :delete). Trash seam.Trash + // Clipboard, if set, is the system clipboard that yank and put use. + // When writing to it fails, the text is sent with OSC 52 instead. + Clipboard seam.Clipboard } // focus is the pane that receives keys. @@ -45,6 +48,7 @@ const ( // message lines, and at most one prompt or palette on top. type Model struct { deps Deps + clip *clipboard // nil without Deps.Clipboard vault string file *noteFile // the open Note's file; shared by copies, like the engine ed editor.Model @@ -99,6 +103,9 @@ func New(deps Deps, path string) (Model, error) { exq: &exQueue{}, appearance: defaultAppearance(), feeds: &feeds{byURL: map[string]*feed{}}, } + if deps.Clipboard != nil { + m.clip = &clipboard{sys: deps.Clipboard} + } file, e, err := m.openEngine(path) if err != nil { return Model{}, err @@ -121,6 +128,9 @@ func (m Model) openEngine(path string) (*noteFile, *engine.Engine, error) { } file.e = e e.Msg = "" // the message line is the app's + if m.clip != nil { + e.Clipboard = m.clip + } m.registerEx(e) return file, e, nil } @@ -306,9 +316,11 @@ func (m Model) editorKey(msg tea.KeyPressMsg) (Model, tea.Cmd) { m.quitAfterWrite = true } m, cmd := m.drainEx() + cmd = tea.Batch(cmd, m.clip.osc52()) if e.Quit { // :wq and :x, once written e.Quit = false - return m.requestQuit() + m, quit := m.requestQuit() + return m, tea.Batch(cmd, quit) } return m, cmd } diff --git a/internal/app/clipboard.go b/internal/app/clipboard.go new file mode 100644 index 0000000..379604f --- /dev/null +++ b/internal/app/clipboard.go @@ -0,0 +1,37 @@ +package app + +import ( + tea "charm.land/bubbletea/v2" + + "github.com/tedkulp/pholio/internal/seam" +) + +// clipboard is the engines' clipboard: the system one, with OSC 52 for +// writes it can't take (no clipboard tool, as over SSH). OSC 52 can't be +// read back reliably, so reads still go to the system clipboard, and on +// failure the engine uses its own register. It is shared by Model copies. +type clipboard struct { + sys seam.Clipboard + pending *string // text waiting to go out as OSC 52 +} + +func (c *clipboard) Read() (string, error) { return c.sys.Read() } + +func (c *clipboard) Write(text string) error { + err := c.sys.Write(text) + if err != nil { + c.pending = &text + } + return err +} + +// osc52 takes the text waiting for OSC 52 and returns the command that +// sends it, or nil. +func (c *clipboard) osc52() tea.Cmd { + if c == nil || c.pending == nil { + return nil + } + text := *c.pending + c.pending = nil + return tea.SetClipboard(text) +} diff --git a/internal/app/clipboard_test.go b/internal/app/clipboard_test.go new file mode 100644 index 0000000..75b61df --- /dev/null +++ b/internal/app/clipboard_test.go @@ -0,0 +1,92 @@ +package app_test + +import ( + "reflect" + "testing" + + tea "charm.land/bubbletea/v2" + + "github.com/tedkulp/pholio/internal/app" + "github.com/tedkulp/pholio/internal/seam" + "github.com/tedkulp/pholio/internal/seam/seamtest" +) + +func clipApp(t *testing.T, cb *seamtest.Clipboard) app.Model { + t.Helper() + fsys := seamtest.NewMemFS(map[string]string{"/vault/a.md": "hello\n", "/vault/b.md": "bye\n"}) + m, err := app.New(app.Deps{FS: fsys, Clipboard: cb}, "/vault/a.md") + if err != nil { + t.Fatal(err) + } + return resize(m, 80, 12) +} + +// msgs runs cmd and returns the messages it gives, batches flattened. +func msgs(cmd tea.Cmd) []tea.Msg { + if cmd == nil { + return nil + } + msg := cmd() + if batch, ok := msg.(tea.BatchMsg); ok { + var out []tea.Msg + for _, c := range batch { + out = append(out, msgs(c)...) + } + return out + } + return []tea.Msg{msg} +} + +func setsClipboard(cmd tea.Cmd, text string) bool { + want := tea.SetClipboard(text)() + for _, msg := range msgs(cmd) { + if reflect.DeepEqual(msg, want) { + return true + } + } + return false +} + +func TestYankAndPutUseTheClipboard(t *testing.T) { + cb := &seamtest.Clipboard{} + m := clipApp(t, cb) + m, cmd := pressing(typeKeys(m, "y"), tea.KeyPressMsg{Code: 'y', Text: "y"}) + if w := cb.Writes(); len(w) != 1 || w[0] != "hello\n" { + t.Errorf("writes = %q", w) + } + if setsClipboard(cmd, "hello\n") { + t.Error("OSC 52 sent although the clipboard tool worked") + } + cb.Set("X") + if m = typeKeys(m, "P"); m.Text() != "Xhello\n" { + t.Errorf("text = %q", m.Text()) + } +} + +func TestOpenedNoteUsesTheClipboard(t *testing.T) { + cb := &seamtest.Clipboard{} + m := clipApp(t, cb) + m = typeKeys(m, ":e /vault/b.md") + m = press(m, enter) + cb.Set("X") + if m = typeKeys(m, "P"); m.Text() != "Xbye\n" { + t.Errorf("text = %q", m.Text()) + } +} + +func TestNoClipboardToolFallsBackToOSC52(t *testing.T) { + cb := &seamtest.Clipboard{WriteErr: seam.ErrNoClipboard, ReadErr: seam.ErrNoClipboard} + m := clipApp(t, cb) + m, cmd := pressing(typeKeys(m, "y"), tea.KeyPressMsg{Code: 'y', Text: "y"}) + if !setsClipboard(cmd, "hello\n") { + t.Errorf("no OSC 52 write in %#v", msgs(cmd)) + } + // A put uses the register; the message line stays empty. + m, cmd = pressing(m, tea.KeyPressMsg{Code: 'p', Text: "p"}) + if m.Text() != "hello\nhello\n" { + t.Errorf("text = %q", m.Text()) + } + if setsClipboard(cmd, "hello\n") { + t.Error("OSC 52 sent again by a put") + } +} diff --git a/internal/engine/clipboard.go b/internal/engine/clipboard.go new file mode 100644 index 0000000..b8534a9 --- /dev/null +++ b/internal/engine/clipboard.go @@ -0,0 +1,40 @@ +package engine + +import "strings" + +// Clipboard is the system clipboard. It is a seam.Clipboard, so the app +// passes its own. +type Clipboard interface { + Read() (string, error) + Write(text string) error +} + +// clipReg reports whether reg is one of the registers that are the +// clipboard: unnamed, "+ and "*. +func clipReg(reg rune) bool { return reg == '"' || reg == '+' || reg == '*' } + +// toClipboard writes r to the clipboard. A failed write is ignored: the +// registers still hold the text. +func (e *Engine) toClipboard(r register) { + if e.Clipboard != nil { + _ = e.Clipboard.Write(r.text) + } +} + +// fromClipboard is the register a put from the clipboard uses. Text that +// matches the unnamed register is pholio's own, so the register is used +// and keeps its shape (lines or a block). Other text is pasted as lines +// when it ends in a newline, else inline. Without a readable, non-empty +// clipboard it falls back to the unnamed register. +func (e *Engine) fromClipboard() (register, bool) { + r, ok := e.regs['"'] + if e.Clipboard == nil { + return r, ok + } + text, err := e.Clipboard.Read() + if err != nil || text == "" || (ok && text == r.text) { + return r, ok + } + text = strings.ReplaceAll(text, "\r\n", "\n") + return register{text: text, linewise: strings.HasSuffix(text, "\n")}, true +} diff --git a/internal/engine/clipboard_test.go b/internal/engine/clipboard_test.go new file mode 100644 index 0000000..38b69a5 --- /dev/null +++ b/internal/engine/clipboard_test.go @@ -0,0 +1,154 @@ +package engine + +import ( + "errors" + "slices" + "testing" + + "github.com/tedkulp/pholio/internal/seam/seamtest" +) + +// loadClip is load with a fake clipboard attached. +func loadClip(in string) (*Engine, *seamtest.Clipboard) { + e := load(in) + cb := &seamtest.Clipboard{} + e.Clipboard = cb + return e, cb +} + +func TestYankWritesClipboard(t *testing.T) { + for _, c := range []struct{ name, in, keys, want string }{ + {"yy", "|ab\ncd", "yy", "ab\n"}, + {"dw", "|ab cd", "dw", "ab "}, + {"visual y", "|abc", "vly", "ab"}, + {"x", "|abc", "x", "a"}, + {"cw", "|ab cd", "cwX", "ab"}, + {"block y", "|ab\ncd", "jy", "a\nc"}, + {"named register", "|ab\ncd", `"ayy`, "ab\n"}, + {"plus register", "|ab\ncd", `"+yy`, "ab\n"}, + } { + t.Run(c.name, func(t *testing.T) { + e, cb := loadClip(c.in) + feed(e, c.keys) + if w := cb.Writes(); len(w) != 1 || w[0] != c.want { + t.Errorf("writes = %q, want [%q]", w, c.want) + } + }) + } +} + +func TestPasteFromClipboard(t *testing.T) { + for _, c := range []struct{ name, in, before, clip, keys, want string }{ + {"inline after cursor", "|ab", "", "XY", "p", "aX|Yb"}, + {"inline before cursor", "a|b", "", "XY", "P", "aX|Yb"}, + {"lines below", "|ab\ncd", "", "X\nY\n", "p", "ab\n|X\nY\ncd"}, + {"lines above", "ab\n|cd", "", "X\n", "P", "ab\n|X\ncd"}, + {"CRLF lines", "|ab", "", "X\r\nY\r\n", "p", "ab\n|X\nY"}, + {"plus register", "|ab", "", "XY", `"+p`, "aX|Yb"}, + {"star register", "|ab", "", "XY", `"*p`, "aX|Yb"}, + {"explicit unnamed", "|ab", "", "XY", `""p`, "aX|Yb"}, + {"copied after a yank", "|ab", "yl", "XY", "p", "aX|Yb"}, + } { + t.Run(c.name, func(t *testing.T) { + e, cb := loadClip(c.in) + feed(e, c.before) + cb.Set(c.clip) // another app copies + feed(e, c.keys) + if g := show(e); g != c.want { + t.Errorf("got %q, want %q", g, c.want) + } + }) + } +} + +func TestPasteKeepsShapeOfOwnClipboard(t *testing.T) { + // Blockwise: the clipboard holds "ab\nxy" (no trailing newline), which + // read cold would paste inline. pholio wrote it, so the block wins. + e, _ := loadClip("|abc\nxyz\n12\n3") + feed(e, "jlyjjlp") + if g, want := show(e), "abc\nxyz\n12|ab\n3 xy"; g != want { + t.Errorf("block: got %q, want %q", g, want) + } + // Linewise yank of a line pastes below even with p at line end. + e, _ = loadClip("|a\nb") + feed(e, "yyjp") + if g, want := show(e), "a\nb\n|a"; g != want { + t.Errorf("line: got %q, want %q", g, want) + } +} + +func TestNamedRegisterIgnoresClipboard(t *testing.T) { + e, cb := loadClip("|a\nb") + feed(e, `"ayyj`) + cb.Set("other") + feed(e, `"ap`) + if g, want := show(e), "a\nb\n|a"; g != want { + t.Errorf("got %q, want %q", g, want) + } + // "0 is internal too. + feed(e, `"0p`) + if g, want := show(e), "a\nb\na\n|a"; g != want { + t.Errorf(`"0p: got %q, want %q`, g, want) + } + if w := cb.Writes(); !slices.Equal(w, []string{"a\n"}) { + t.Errorf("writes = %q", w) + } +} + +func TestPlusRegisterIsUnnamed(t *testing.T) { + // "+yy stores like an unnamed yank: p (no register) gets it back, + // with the clipboard broken too. + e, cb := loadClip("|a\nb") + cb.ReadErr = errors.New("no clipboard") + feed(e, `"+yyjp`) + if g, want := show(e), "a\nb\n|a"; g != want { + t.Errorf("got %q, want %q", g, want) + } +} + +func TestClipboardErrors(t *testing.T) { + e, cb := loadClip("|ab\ncd") + cb.ReadErr = errors.New("read failed") + cb.WriteErr = errors.New("write failed") + feed(e, "yyjp") + if g, want := show(e), "ab\ncd\n|ab"; g != want { + t.Errorf("p: got %q, want %q", g, want) + } + feed(e, `"+P`) + if g, want := show(e), "ab\ncd\n|ab\nab"; g != want { + t.Errorf(`"+P: got %q, want %q`, g, want) + } + if e.Msg != "" { + t.Errorf("msg = %q, want none", e.Msg) + } +} + +func TestEmptyClipboardUsesRegister(t *testing.T) { + e, cb := loadClip("|ab") + feed(e, "yl") + cb.Set("") + feed(e, "p") + if g, want := show(e), "a|ab"; g != want { + t.Errorf("got %q, want %q", g, want) + } +} + +func TestNothingToPaste(t *testing.T) { + e, _ := loadClip("|ab") + feed(e, "p") + if g := show(e); g != "|ab" { + t.Errorf("got %q", g) + } + if e.Msg != `E353: Nothing in register "` { + t.Errorf("msg = %q", e.Msg) + } +} + +func TestDotRepeatsClipboardPaste(t *testing.T) { + e, cb := loadClip("|ab") + cb.Set("X") + feed(e, "p.") + if g, want := show(e), "aX|Xb"; g != want { + t.Errorf("got %q, want %q", g, want) + } +} diff --git a/internal/engine/engine.go b/internal/engine/engine.go index eef90cb..59995b7 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -55,6 +55,10 @@ type Engine struct { // Fixup, when set, runs as each change completes (see FixupFunc). Fixup FixupFunc + // Clipboard, when set, is the system clipboard, kept in step with the + // unnamed register (see clipboard.go). + Clipboard Clipboard + fs FS exCmds map[string]ExFunc diff --git a/internal/engine/operators.go b/internal/engine/operators.go index e24f520..3806490 100644 --- a/internal/engine/operators.go +++ b/internal/engine/operators.go @@ -145,15 +145,17 @@ func (e *Engine) operate(op string, reg rune, a, z Pos, linewise bool) { } // store puts r in the unnamed register and in reg, if one was given. A -// yank also goes in register 0. +// yank also goes in register 0. The unnamed register is copied to the +// clipboard, so "+ and "* need no slot of their own. func (e *Engine) store(r register, reg rune, yank bool) { e.regs['"'] = r - if reg != 0 { + if reg != 0 && !clipReg(reg) { e.regs[reg] = r } if yank { e.regs['0'] = r } + e.toClipboard(r) } // deleteLines removes lines a..z, including their line breaks. @@ -175,6 +177,9 @@ func (e *Engine) paste(p parsed, after bool) { reg = '"' } r, ok := e.regs[reg] + if clipReg(reg) { + r, ok = e.fromClipboard() + } if !ok { e.Msg = "E353: Nothing in register " + string(reg) return diff --git a/internal/seam/clipboard.go b/internal/seam/clipboard.go new file mode 100644 index 0000000..9635aa4 --- /dev/null +++ b/internal/seam/clipboard.go @@ -0,0 +1,80 @@ +package seam + +import ( + "context" + "errors" + "os/exec" + "runtime" + "strings" + "time" +) + +// ErrNoClipboard is returned by a SystemClipboard that found no clipboard +// tool, as over SSH. +var ErrNoClipboard = errors.New("no clipboard tool") + +// clipTimeout bounds each clipboard tool run, so a stuck selection owner +// can't hang the editor. +const clipTimeout = time.Second + +// SystemClipboard is the real Clipboard: it runs the platform's clipboard +// tools (pbcopy/pbpaste on macOS, wl-copy/wl-paste on Wayland, xclip or +// xsel on X11). The zero value has no tools and returns ErrNoClipboard. +type SystemClipboard struct { + copy, paste []string // the commands that write and read the clipboard +} + +var _ Clipboard = SystemClipboard{} + +// NewSystemClipboard returns the clipboard of the platform and display +// that getenv describes, using the first tool found on $PATH. +func NewSystemClipboard(getenv func(string) string) SystemClipboard { + return pickClipboard(runtime.GOOS, getenv, exec.LookPath) +} + +func pickClipboard(goos string, getenv func(string) string, lookPath func(string) (string, error)) SystemClipboard { + var tools []SystemClipboard + switch { + case goos == "darwin": + tools = append(tools, SystemClipboard{[]string{"pbcopy"}, []string{"pbpaste"}}) + case getenv("WAYLAND_DISPLAY") != "": + tools = append(tools, SystemClipboard{[]string{"wl-copy"}, []string{"wl-paste", "--no-newline"}}) + } + if getenv("DISPLAY") != "" { + tools = append(tools, + SystemClipboard{[]string{"xclip", "-selection", "clipboard", "-in"}, []string{"xclip", "-selection", "clipboard", "-out"}}, + SystemClipboard{[]string{"xsel", "--clipboard", "--input"}, []string{"xsel", "--clipboard", "--output"}}, + ) + } + for _, t := range tools { + if _, err := lookPath(t.copy[0]); err == nil { + return t + } + } + return SystemClipboard{} +} + +// Read returns the clipboard text. +func (c SystemClipboard) Read() (string, error) { + if c.paste == nil { + return "", ErrNoClipboard + } + ctx, cancel := context.WithTimeout(context.Background(), clipTimeout) + defer cancel() + out, err := exec.CommandContext(ctx, c.paste[0], c.paste[1:]...).Output() //nolint:gosec // a fixed clipboard tool + return string(out), err +} + +// Write puts text on the clipboard. +func (c SystemClipboard) Write(text string) error { + if c.copy == nil { + return ErrNoClipboard + } + ctx, cancel := context.WithTimeout(context.Background(), clipTimeout) + defer cancel() + cmd := exec.CommandContext(ctx, c.copy[0], c.copy[1:]...) //nolint:gosec // a fixed clipboard tool + cmd.Stdin = strings.NewReader(text) + // No stdout or stderr: wl-copy and xclip leave a child serving the + // selection, and a pipe it inherits would keep Run waiting for it. + return cmd.Run() +} diff --git a/internal/seam/clipboard_test.go b/internal/seam/clipboard_test.go new file mode 100644 index 0000000..9a31e88 --- /dev/null +++ b/internal/seam/clipboard_test.go @@ -0,0 +1,68 @@ +package seam + +import ( + "errors" + "path/filepath" + "slices" + "testing" +) + +func TestPickClipboard(t *testing.T) { + for _, c := range []struct { + name, goos string + env map[string]string + path []string // tools on $PATH + want string // the copy tool, or "" for none + }{ + {"macOS", "darwin", nil, []string{"pbcopy"}, "pbcopy"}, + {"Wayland", "linux", map[string]string{"WAYLAND_DISPLAY": "wayland-0", "DISPLAY": ":0"}, []string{"wl-copy", "xclip"}, "wl-copy"}, + {"Wayland without wl-copy uses XWayland", "linux", map[string]string{"WAYLAND_DISPLAY": "wayland-0", "DISPLAY": ":0"}, []string{"xclip"}, "xclip"}, + {"X11 xclip", "linux", map[string]string{"DISPLAY": ":0"}, []string{"xclip", "xsel"}, "xclip"}, + {"X11 xsel", "linux", map[string]string{"DISPLAY": ":0"}, []string{"xsel"}, "xsel"}, + {"no display (SSH)", "linux", nil, []string{"wl-copy", "xclip"}, ""}, + {"display but no tool", "linux", map[string]string{"DISPLAY": ":0"}, nil, ""}, + } { + t.Run(c.name, func(t *testing.T) { + getenv := func(k string) string { return c.env[k] } + lookPath := func(name string) (string, error) { + if slices.Contains(c.path, name) { + return "/usr/bin/" + name, nil + } + return "", errors.New("not found") + } + cb := pickClipboard(c.goos, getenv, lookPath) + got := "" + if cb.copy != nil { + got = cb.copy[0] + } + if got != c.want { + t.Errorf("copy tool = %q, want %q", got, c.want) + } + if (cb.copy == nil) != (cb.paste == nil) { + t.Errorf("copy %q but paste %q", cb.copy, cb.paste) + } + }) + } +} + +func TestNoClipboardTool(t *testing.T) { + var cb SystemClipboard + if err := cb.Write("x"); !errors.Is(err, ErrNoClipboard) { + t.Errorf("Write: %v", err) + } + if _, err := cb.Read(); !errors.Is(err, ErrNoClipboard) { + t.Errorf("Read: %v", err) + } +} + +func TestSystemClipboardRunsTheTools(t *testing.T) { + f := filepath.Join(t.TempDir(), "clip") + cb := SystemClipboard{copy: []string{"sh", "-c", `cat > "$0"`, f}, paste: []string{"cat", f}} + if err := cb.Write("a\nb"); err != nil { + t.Fatal(err) + } + got, err := cb.Read() + if err != nil || got != "a\nb" { + t.Errorf("Read = %q, %v", got, err) + } +} diff --git a/internal/seam/seam.go b/internal/seam/seam.go index e7b687a..905b76b 100644 --- a/internal/seam/seam.go +++ b/internal/seam/seam.go @@ -1,5 +1,6 @@ // Package seam holds the interfaces pholio uses to reach the outside world: -// the clock, the filesystem, the URL opener, the trash and the file watcher. +// the clock, the filesystem, the URL opener, the trash, the file watcher and +// the clipboard. // Production code receives them injected, and tests pass the fakes from // package seamtest. package seam @@ -39,6 +40,12 @@ type Trash interface { Trash(path string) error } +// Clipboard is the system clipboard. +type Clipboard interface { + Read() (string, error) + Write(text string) error +} + // Op is the kind of change a WatchEvent reports. Ops can be combined. type Op uint8 diff --git a/internal/seam/seamtest/seamtest.go b/internal/seam/seamtest/seamtest.go index d4d91aa..a8eaabc 100644 --- a/internal/seam/seamtest/seamtest.go +++ b/internal/seam/seamtest/seamtest.go @@ -315,3 +315,53 @@ func (w *Watcher) Close() error { close(w.errs) return nil } + +// Clipboard is a fake seam.Clipboard. Set stands in for another app +// copying text; Writes lists what was written through the seam. +type Clipboard struct { + mu sync.Mutex + text string + writes []string + // ReadErr and WriteErr, if set, are returned from Read and Write. + // A failed Write leaves the text unchanged. + ReadErr, WriteErr error +} + +var _ seam.Clipboard = (*Clipboard)(nil) + +// Read returns the clipboard text. +func (c *Clipboard) Read() (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.ReadErr != nil { + return "", c.ReadErr + } + return c.text, nil +} + +// Write records text and, unless WriteErr is set, puts it on the clipboard. +func (c *Clipboard) Write(text string) error { + c.mu.Lock() + defer c.mu.Unlock() + c.writes = append(c.writes, text) + if c.WriteErr != nil { + return c.WriteErr + } + c.text = text + return nil +} + +// Set puts text on the clipboard without recording a write, as another +// app copying it would. +func (c *Clipboard) Set(text string) { + c.mu.Lock() + defer c.mu.Unlock() + c.text = text +} + +// Writes returns the texts written so far, oldest first. +func (c *Clipboard) Writes() []string { + c.mu.Lock() + defer c.mu.Unlock() + return append([]string(nil), c.writes...) +} From b9979fb549540733148face419991f3eef4eae4f Mon Sep 17 00:00:00 2001 From: Ted Kulp Date: Tue, 20 Oct 2026 07:13:24 -0400 Subject: [PATCH 2/4] Don't paste a stale clipboard after a failed write When a clipboard write fails but reads work, the clipboard still holds older text; puts now use the unnamed register until a write succeeds. Also rename clipReg to isClipboardReg and reuse msgsOf in app tests. Closes #75 Co-Authored-By: Claude Opus 5.5 (1M context) --- internal/app/clipboard_test.go | 20 ++------------------ internal/engine/clipboard.go | 17 +++++++++-------- internal/engine/clipboard_test.go | 20 ++++++++++++++++++++ internal/engine/engine.go | 3 ++- internal/engine/operators.go | 4 ++-- 5 files changed, 35 insertions(+), 29 deletions(-) diff --git a/internal/app/clipboard_test.go b/internal/app/clipboard_test.go index 75b61df..2a9417c 100644 --- a/internal/app/clipboard_test.go +++ b/internal/app/clipboard_test.go @@ -21,25 +21,9 @@ func clipApp(t *testing.T, cb *seamtest.Clipboard) app.Model { return resize(m, 80, 12) } -// msgs runs cmd and returns the messages it gives, batches flattened. -func msgs(cmd tea.Cmd) []tea.Msg { - if cmd == nil { - return nil - } - msg := cmd() - if batch, ok := msg.(tea.BatchMsg); ok { - var out []tea.Msg - for _, c := range batch { - out = append(out, msgs(c)...) - } - return out - } - return []tea.Msg{msg} -} - func setsClipboard(cmd tea.Cmd, text string) bool { want := tea.SetClipboard(text)() - for _, msg := range msgs(cmd) { + for _, msg := range msgsOf(cmd) { if reflect.DeepEqual(msg, want) { return true } @@ -79,7 +63,7 @@ func TestNoClipboardToolFallsBackToOSC52(t *testing.T) { m := clipApp(t, cb) m, cmd := pressing(typeKeys(m, "y"), tea.KeyPressMsg{Code: 'y', Text: "y"}) if !setsClipboard(cmd, "hello\n") { - t.Errorf("no OSC 52 write in %#v", msgs(cmd)) + t.Errorf("no OSC 52 write in %#v", msgsOf(cmd)) } // A put uses the register; the message line stays empty. m, cmd = pressing(m, tea.KeyPressMsg{Code: 'p', Text: "p"}) diff --git a/internal/engine/clipboard.go b/internal/engine/clipboard.go index b8534a9..42e532e 100644 --- a/internal/engine/clipboard.go +++ b/internal/engine/clipboard.go @@ -9,26 +9,27 @@ type Clipboard interface { Write(text string) error } -// clipReg reports whether reg is one of the registers that are the +// isClipboardReg reports whether reg is one of the registers that are the // clipboard: unnamed, "+ and "*. -func clipReg(reg rune) bool { return reg == '"' || reg == '+' || reg == '*' } +func isClipboardReg(reg rune) bool { return reg == '"' || reg == '+' || reg == '*' } -// toClipboard writes r to the clipboard. A failed write is ignored: the -// registers still hold the text. +// toClipboard writes r to the clipboard. A failed write is not reported: +// the registers still hold the text, and puts use them until a write +// succeeds, since the clipboard then holds something older. func (e *Engine) toClipboard(r register) { if e.Clipboard != nil { - _ = e.Clipboard.Write(r.text) + e.clipStale = e.Clipboard.Write(r.text) != nil } } // fromClipboard is the register a put from the clipboard uses. Text that // matches the unnamed register is pholio's own, so the register is used // and keeps its shape (lines or a block). Other text is pasted as lines -// when it ends in a newline, else inline. Without a readable, non-empty -// clipboard it falls back to the unnamed register. +// when it ends in a newline, else inline. Without a readable, non-empty, +// up-to-date clipboard it falls back to the unnamed register. func (e *Engine) fromClipboard() (register, bool) { r, ok := e.regs['"'] - if e.Clipboard == nil { + if e.Clipboard == nil || e.clipStale { return r, ok } text, err := e.Clipboard.Read() diff --git a/internal/engine/clipboard_test.go b/internal/engine/clipboard_test.go index 38b69a5..aaa0f5e 100644 --- a/internal/engine/clipboard_test.go +++ b/internal/engine/clipboard_test.go @@ -152,3 +152,23 @@ func TestDotRepeatsClipboardPaste(t *testing.T) { t.Errorf("got %q, want %q", g, want) } } + +func TestFailedWriteDoesNotPasteOldClipboard(t *testing.T) { + // The write fails but the read works: the clipboard still holds the + // old text, so p must use what was just yanked. + e, cb := loadClip("|ab") + cb.Set("old") + cb.WriteErr = errors.New("timed out") + feed(e, "ylp") + if g, want := show(e), "a|ab"; g != want { + t.Errorf("got %q, want %q", g, want) + } + // Once a write succeeds, the clipboard is read again. + cb.WriteErr = nil + feed(e, "yl") + cb.Set("X") + feed(e, "p") + if g, want := show(e), "aa|Xb"; g != want { + t.Errorf("after recovery: got %q, want %q", g, want) + } +} diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 59995b7..1a72860 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -81,7 +81,8 @@ type Engine struct { recording bool // still appending insert-mode keys to dot replaying bool - regs map[rune]register + regs map[rune]register + clipStale bool // the last clipboard write failed undo, redo []change pending *change // edits of the command in progress diff --git a/internal/engine/operators.go b/internal/engine/operators.go index 3806490..276cdb7 100644 --- a/internal/engine/operators.go +++ b/internal/engine/operators.go @@ -149,7 +149,7 @@ func (e *Engine) operate(op string, reg rune, a, z Pos, linewise bool) { // clipboard, so "+ and "* need no slot of their own. func (e *Engine) store(r register, reg rune, yank bool) { e.regs['"'] = r - if reg != 0 && !clipReg(reg) { + if reg != 0 && !isClipboardReg(reg) { e.regs[reg] = r } if yank { @@ -177,7 +177,7 @@ func (e *Engine) paste(p parsed, after bool) { reg = '"' } r, ok := e.regs[reg] - if clipReg(reg) { + if isClipboardReg(reg) { r, ok = e.fromClipboard() } if !ok { From 232807effa531b6a43b3ba5c0e1162d22f94892b Mon Sep 17 00:00:00 2001 From: Ted Kulp Date: Tue, 20 Oct 2026 07:53:29 -0400 Subject: [PATCH 3/4] Find the Wayland display when a multiplexer pane drops it A herdr or tmux server started outside the desktop gives its panes no WAYLAND_DISPLAY or DISPLAY, so no clipboard tool was picked: copies went out over OSC 52 but puts found nothing. With neither set, use the one wayland-* socket in $XDG_RUNTIME_DIR that accepts a connection. With none or several, don't guess: a copy sent to a nested compositor would be lost without an error. Closes #75 Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 2 +- internal/seam/clipboard.go | 76 +++++++++++++++++++++++++++++---- internal/seam/clipboard_test.go | 61 ++++++++++++++++++++++++++ 3 files changed, 130 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ceec59..eca3f5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] ### Added -- Yank, delete and put use the system clipboard, like vim's `clipboard=unnamedplus`: every write to the unnamed register also goes to the clipboard, and `p`/`P` paste what's on it, so text moves between pholio and other apps. `"+` and `"*` name the clipboard; `"a`–`"z` and `"0`–`"9` stay internal. Text copied in another app pastes as lines when it ends in a newline, else inline; pholio's own yanks keep their shape (lines or a block). pholio uses `wl-copy`/`wl-paste`, `xclip` or `xsel`, or `pbcopy`/`pbpaste`, and without them (as over SSH) writes the clipboard with OSC 52, where puts use the internal register. +- Yank, delete and put use the system clipboard, like vim's `clipboard=unnamedplus`: every write to the unnamed register also goes to the clipboard, and `p`/`P` paste what's on it, so text moves between pholio and other apps. `"+` and `"*` name the clipboard; `"a`–`"z` and `"0`–`"9` stay internal. Text copied in another app pastes as lines when it ends in a newline, else inline; pholio's own yanks keep their shape (lines or a block). pholio uses `wl-copy`/`wl-paste`, `xclip` or `xsel`, or `pbcopy`/`pbpaste`, and without them (as over SSH) writes the clipboard with OSC 52, where puts use the internal register. In a terminal multiplexer pane with no `WAYLAND_DISPLAY` or `DISPLAY` (a herdr or tmux server started outside the desktop), pholio uses the Wayland display if exactly one live `wayland-*` socket is in `$XDG_RUNTIME_DIR`. ## [0.6.1] - 2026-10-12 diff --git a/internal/seam/clipboard.go b/internal/seam/clipboard.go index 9635aa4..467e116 100644 --- a/internal/seam/clipboard.go +++ b/internal/seam/clipboard.go @@ -3,7 +3,11 @@ package seam import ( "context" "errors" + "io/fs" + "net" + "os" "os/exec" + "path/filepath" "runtime" "strings" "time" @@ -22,28 +26,75 @@ const clipTimeout = time.Second // xsel on X11). The zero value has no tools and returns ErrNoClipboard. type SystemClipboard struct { copy, paste []string // the commands that write and read the clipboard + env []string // added to the tools' environment, as "KEY=value" } var _ Clipboard = SystemClipboard{} // NewSystemClipboard returns the clipboard of the platform and display -// that getenv describes, using the first tool found on $PATH. +// that getenv describes, using the first tool found on $PATH. With no +// display set, as in a multiplexer pane started outside the desktop, it +// uses the Wayland display found by fallbackDisplay. func NewSystemClipboard(getenv func(string) string) SystemClipboard { - return pickClipboard(runtime.GOOS, getenv, exec.LookPath) + d := fallbackDisplay(getenv) + if d == "" { + return pickClipboard(runtime.GOOS, getenv, exec.LookPath) + } + c := pickClipboard(runtime.GOOS, func(k string) string { + if k == "WAYLAND_DISPLAY" { + return d + } + return getenv(k) + }, exec.LookPath) + c.env = []string{"WAYLAND_DISPLAY=" + d} + return c +} + +// fallbackDisplay is the Wayland display to use when neither +// WAYLAND_DISPLAY nor DISPLAY is set: the one wayland-* socket in +// $XDG_RUNTIME_DIR that accepts a connection. With none, or several (a +// nested compositor, say), it returns "" rather than guess, since copies +// sent to the wrong compositor would vanish without an error. +func fallbackDisplay(getenv func(string) string) string { + dir := getenv("XDG_RUNTIME_DIR") + if getenv("WAYLAND_DISPLAY") != "" || getenv("DISPLAY") != "" || dir == "" { + return "" + } + entries, err := os.ReadDir(dir) + if err != nil { + return "" + } + var live []string + for _, ent := range entries { + name := ent.Name() + if !strings.HasPrefix(name, "wayland-") || ent.Type() != fs.ModeSocket { + continue + } + conn, err := net.DialTimeout("unix", filepath.Join(dir, name), 100*time.Millisecond) + if err != nil { + continue // stale: the compositor is gone + } + _ = conn.Close() + live = append(live, name) + } + if len(live) != 1 { + return "" + } + return live[0] } func pickClipboard(goos string, getenv func(string) string, lookPath func(string) (string, error)) SystemClipboard { var tools []SystemClipboard switch { case goos == "darwin": - tools = append(tools, SystemClipboard{[]string{"pbcopy"}, []string{"pbpaste"}}) + tools = append(tools, SystemClipboard{copy: []string{"pbcopy"}, paste: []string{"pbpaste"}}) case getenv("WAYLAND_DISPLAY") != "": - tools = append(tools, SystemClipboard{[]string{"wl-copy"}, []string{"wl-paste", "--no-newline"}}) + tools = append(tools, SystemClipboard{copy: []string{"wl-copy"}, paste: []string{"wl-paste", "--no-newline"}}) } if getenv("DISPLAY") != "" { tools = append(tools, - SystemClipboard{[]string{"xclip", "-selection", "clipboard", "-in"}, []string{"xclip", "-selection", "clipboard", "-out"}}, - SystemClipboard{[]string{"xsel", "--clipboard", "--input"}, []string{"xsel", "--clipboard", "--output"}}, + SystemClipboard{copy: []string{"xclip", "-selection", "clipboard", "-in"}, paste: []string{"xclip", "-selection", "clipboard", "-out"}}, + SystemClipboard{copy: []string{"xsel", "--clipboard", "--input"}, paste: []string{"xsel", "--clipboard", "--output"}}, ) } for _, t := range tools { @@ -61,7 +112,7 @@ func (c SystemClipboard) Read() (string, error) { } ctx, cancel := context.WithTimeout(context.Background(), clipTimeout) defer cancel() - out, err := exec.CommandContext(ctx, c.paste[0], c.paste[1:]...).Output() //nolint:gosec // a fixed clipboard tool + out, err := c.command(ctx, c.paste).Output() return string(out), err } @@ -72,9 +123,18 @@ func (c SystemClipboard) Write(text string) error { } ctx, cancel := context.WithTimeout(context.Background(), clipTimeout) defer cancel() - cmd := exec.CommandContext(ctx, c.copy[0], c.copy[1:]...) //nolint:gosec // a fixed clipboard tool + cmd := c.command(ctx, c.copy) cmd.Stdin = strings.NewReader(text) // No stdout or stderr: wl-copy and xclip leave a child serving the // selection, and a pipe it inherits would keep Run waiting for it. return cmd.Run() } + +// command makes the command for a clipboard tool, with c.env added. +func (c SystemClipboard) command(ctx context.Context, args []string) *exec.Cmd { + cmd := exec.CommandContext(ctx, args[0], args[1:]...) //nolint:gosec // a fixed clipboard tool + if c.env != nil { + cmd.Env = append(os.Environ(), c.env...) + } + return cmd +} diff --git a/internal/seam/clipboard_test.go b/internal/seam/clipboard_test.go index 9a31e88..5840d85 100644 --- a/internal/seam/clipboard_test.go +++ b/internal/seam/clipboard_test.go @@ -2,6 +2,8 @@ package seam import ( "errors" + "net" + "os" "path/filepath" "slices" "testing" @@ -66,3 +68,62 @@ func TestSystemClipboardRunsTheTools(t *testing.T) { t.Errorf("Read = %q, %v", got, err) } } + +// socket makes a unix socket at dir/name. A live one accepts connections +// until the test ends; a stale one is left behind with nothing listening. +func socket(t *testing.T, dir, name string, live bool) { + t.Helper() + l, err := net.Listen("unix", filepath.Join(dir, name)) + if err != nil { + t.Fatal(err) + } + if live { + t.Cleanup(func() { _ = l.Close() }) + return + } + l.(*net.UnixListener).SetUnlinkOnClose(false) + _ = l.Close() +} + +func TestFallbackDisplay(t *testing.T) { + for _, c := range []struct { + name string + live, stale []string + files []string + display, want string + }{ + {name: "one live socket", live: []string{"wayland-1"}, files: []string{"wayland-1.lock"}, want: "wayland-1"}, + {name: "stale socket skipped", live: []string{"wayland-1"}, stale: []string{"wayland-0"}, want: "wayland-1"}, + {name: "two live sockets", live: []string{"wayland-0", "wayland-1"}, want: ""}, + {name: "only stale", stale: []string{"wayland-0"}, want: ""}, + {name: "lock file is not a socket", files: []string{"wayland-1"}, want: ""}, + {name: "other sockets ignored", live: []string{"wayland-1", "herdr-nvim"}, want: "wayland-1"}, + {name: "a display is already set", live: []string{"wayland-1"}, display: ":0", want: ""}, + } { + t.Run(c.name, func(t *testing.T) { + dir := t.TempDir() + for _, n := range c.live { + socket(t, dir, n, true) + } + for _, n := range c.stale { + socket(t, dir, n, false) + } + for _, n := range c.files { + if err := os.WriteFile(filepath.Join(dir, n), nil, 0o600); err != nil { + t.Fatal(err) + } + } + env := map[string]string{"XDG_RUNTIME_DIR": dir, "DISPLAY": c.display} + if got := fallbackDisplay(func(k string) string { return env[k] }); got != c.want { + t.Errorf("fallbackDisplay = %q, want %q", got, c.want) + } + }) + } +} + +func TestToolsGetTheFallbackDisplay(t *testing.T) { + cb := SystemClipboard{paste: []string{"sh", "-c", `printf %s "$WAYLAND_DISPLAY"`}, env: []string{"WAYLAND_DISPLAY=wayland-9"}} + if got, err := cb.Read(); err != nil || got != "wayland-9" { + t.Errorf("Read = %q, %v", got, err) + } +} From d0ee4067921367b01b412930b6c8f25340dd3cb7 Mon Sep 17 00:00:00 2001 From: Ted Kulp Date: Tue, 20 Oct 2026 08:23:30 -0400 Subject: [PATCH 4/4] Skip the Wayland fallback on macOS; fix its test there macOS has pbcopy, so it never needs the fallback. The test's sockets now live in a short temp dir: macOS caps unix socket paths at 104 bytes and t.TempDir there exceeds it. Closes #75 Co-Authored-By: Claude Opus 5.5 (1M context) --- internal/seam/clipboard.go | 8 ++++---- internal/seam/clipboard_test.go | 22 ++++++++++++++++++++-- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/internal/seam/clipboard.go b/internal/seam/clipboard.go index 467e116..11b69e6 100644 --- a/internal/seam/clipboard.go +++ b/internal/seam/clipboard.go @@ -36,7 +36,7 @@ var _ Clipboard = SystemClipboard{} // display set, as in a multiplexer pane started outside the desktop, it // uses the Wayland display found by fallbackDisplay. func NewSystemClipboard(getenv func(string) string) SystemClipboard { - d := fallbackDisplay(getenv) + d := fallbackDisplay(runtime.GOOS, getenv) if d == "" { return pickClipboard(runtime.GOOS, getenv, exec.LookPath) } @@ -51,13 +51,13 @@ func NewSystemClipboard(getenv func(string) string) SystemClipboard { } // fallbackDisplay is the Wayland display to use when neither -// WAYLAND_DISPLAY nor DISPLAY is set: the one wayland-* socket in +// WAYLAND_DISPLAY nor DISPLAY is set, off macOS (which has pbcopy): the one wayland-* socket in // $XDG_RUNTIME_DIR that accepts a connection. With none, or several (a // nested compositor, say), it returns "" rather than guess, since copies // sent to the wrong compositor would vanish without an error. -func fallbackDisplay(getenv func(string) string) string { +func fallbackDisplay(goos string, getenv func(string) string) string { dir := getenv("XDG_RUNTIME_DIR") - if getenv("WAYLAND_DISPLAY") != "" || getenv("DISPLAY") != "" || dir == "" { + if goos == "darwin" || getenv("WAYLAND_DISPLAY") != "" || getenv("DISPLAY") != "" || dir == "" { return "" } entries, err := os.ReadDir(dir) diff --git a/internal/seam/clipboard_test.go b/internal/seam/clipboard_test.go index 5840d85..f45ca6d 100644 --- a/internal/seam/clipboard_test.go +++ b/internal/seam/clipboard_test.go @@ -69,6 +69,18 @@ func TestSystemClipboardRunsTheTools(t *testing.T) { } } +// shortTempDir is a temporary directory with a path short enough for unix +// sockets: macOS allows 104 bytes, and t.TempDir there is too long. +func shortTempDir(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("", "wl") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + return dir +} + // socket makes a unix socket at dir/name. A live one accepts connections // until the test ends; a stale one is left behind with nothing listening. func socket(t *testing.T, dir, name string, live bool) { @@ -88,6 +100,7 @@ func socket(t *testing.T, dir, name string, live bool) { func TestFallbackDisplay(t *testing.T) { for _, c := range []struct { name string + goos string // "" is linux live, stale []string files []string display, want string @@ -99,9 +112,10 @@ func TestFallbackDisplay(t *testing.T) { {name: "lock file is not a socket", files: []string{"wayland-1"}, want: ""}, {name: "other sockets ignored", live: []string{"wayland-1", "herdr-nvim"}, want: "wayland-1"}, {name: "a display is already set", live: []string{"wayland-1"}, display: ":0", want: ""}, + {name: "not on macOS", goos: "darwin", live: []string{"wayland-1"}, want: ""}, } { t.Run(c.name, func(t *testing.T) { - dir := t.TempDir() + dir := shortTempDir(t) for _, n := range c.live { socket(t, dir, n, true) } @@ -114,7 +128,11 @@ func TestFallbackDisplay(t *testing.T) { } } env := map[string]string{"XDG_RUNTIME_DIR": dir, "DISPLAY": c.display} - if got := fallbackDisplay(func(k string) string { return env[k] }); got != c.want { + goos := c.goos + if goos == "" { + goos = "linux" + } + if got := fallbackDisplay(goos, func(k string) string { return env[k] }); got != c.want { t.Errorf("fallbackDisplay = %q, want %q", got, c.want) } })