// Package paste handles writing text to the system clipboard and simulating // Ctrl+V / Cmd+V to paste into the currently focused application. package paste import ( "fmt" "log/slog" "runtime" "time" "github.com/go-vgo/robotgo" "golang.design/x/clipboard" ) const keyDelay = 50 * time.Millisecond // Init initializes the clipboard subsystem. Must be called once at startup. func Init() error { return clipboard.Init() } // Paste writes text to the clipboard and simulates a paste keystroke. // Falls back to clipboard-only if key simulation fails. func Paste(text string) error { // Write to clipboard clipboard.Write(clipboard.FmtText, []byte(text)) // Small delay to ensure clipboard is ready time.Sleep(keyDelay) // Simulate paste keystroke if err := simulatePaste(); err != nil { slog.Warn("key simulation failed, text is in clipboard", "err", err) return fmt.Errorf("key simulation failed (text is in clipboard): %w", err) } return nil } // ClipboardOnly writes text to clipboard without simulating a keystroke. func ClipboardOnly(text string) { clipboard.Write(clipboard.FmtText, []byte(text)) } func simulatePaste() error { var modifier, key string switch runtime.GOOS { case "darwin": modifier, key = "command", "v" case "linux", "windows": modifier, key = "ctrl", "v" default: return fmt.Errorf("unsupported platform: %s", runtime.GOOS) } robotgo.KeyDown(modifier) time.Sleep(20 * time.Millisecond) robotgo.KeyTap(key) time.Sleep(20 * time.Millisecond) robotgo.KeyUp(modifier) return nil }