pat/pkg/clip/coppy.go
2025-04-02 16:23:15 +02:00

45 lines
947 B
Go

package clip
import (
"os"
"os/exec"
"golang.design/x/clipboard"
)
// Copy copies a given string to the clipboard, handling both Wayland and X11 environments.
// If WAYLAND_DISPLAY is set, it uses wl-copy to copy the string in a Wayland environment.
// Otherwise, it initializes the clipboard and writes the string using the clipboard package for X11.
// Parameters:
//
// str: The string to be copied to the clipboard.
//
// Returns:
//
// error: If an error occurs during copying (e.g., command execution or clipboard initialization fails).
func Copy(str string) error {
if os.Getenv("WAYLAND_DISPLAY") != "" {
cmd := exec.Command("wl-copy")
p, err := cmd.StdinPipe()
if err != nil {
return err
}
if err := cmd.Start(); err == nil {
p.Write([]byte(str))
p.Close()
return cmd.Wait()
}
}
if err := clipboard.Init(); err != nil {
return err
}
clipboard.Write(clipboard.FmtText, []byte(str))
return nil
}