diff --git a/ansi/cwd.go b/ansi/cwd.go new file mode 100644 index 00000000..b03ac1bb --- /dev/null +++ b/ansi/cwd.go @@ -0,0 +1,26 @@ +package ansi + +import ( + "net/url" + "path" +) + +// NotifyWorkingDirectory returns a sequence that notifies the terminal +// of the current working directory. +// +// OSC 7 ; Pt BEL +// +// Where Pt is a URL in the format "file://[host]/[path]". +// Set host to "localhost" if this is a path on the local computer. +// +// See: https://wezfurlong.org/wezterm/shell-integration.html#osc-7-escape-sequence-to-set-the-working-directory +// See: https://iterm2.com/documentation-escape-codes.html#:~:text=RemoteHost%20and%20CurrentDir%3A-,OSC%207,-%3B%20%5BPs%5D%20ST +func NotifyWorkingDirectory(host string, paths ...string) string { + path := path.Join(paths...) + u := &url.URL{ + Scheme: "file", + Host: host, + Path: path, + } + return "\x1b]7;" + u.String() + "\x07" +} diff --git a/ansi/cwd_test.go b/ansi/cwd_test.go new file mode 100644 index 00000000..381becee --- /dev/null +++ b/ansi/cwd_test.go @@ -0,0 +1,21 @@ +package ansi_test + +import ( + "testing" + + "github.com/charmbracelet/x/ansi" +) + +func TestNotifyWorkingDirectory_LocalFile(t *testing.T) { + h := ansi.NotifyWorkingDirectory("localhost", "path", "to", "file") + if h != "\x1b]7;file://localhost/path/to/file\x07" { + t.Errorf("Unexpected url: %s", h) + } +} + +func TestNotifyWorkingDirectory_RemoteFile(t *testing.T) { + h := ansi.NotifyWorkingDirectory("example.com", "path", "to", "file") + if h != "\x1b]7;file://example.com/path/to/file\x07" { + t.Errorf("Unexpected url: %s", h) + } +}