Skip to content

Clipboard Functions - Cross-Platform Clipboard Operations

Enterprise-grade clipboard operations with automatic platform detection, retry logic, backups, and comprehensive logging.

Overview

The clipboard functions provide a unified, cross-platform interface for clipboard operations across:

  • Wayland (wl-clipboard: wl-copy / wl-paste)
  • X11 (xclip, xsel)
  • macOS (pbcopy / pbpaste)
  • WSL (clip.exe / PowerShell Get-Clipboard)

Functions

clipboard_copy

Copy content to the system clipboard with automatic backups and verification.

Usage:

# From stdin
echo "hello world" | clipboard_copy

# From arguments
clipboard_copy "hello world"
clipboard_copy "line1" "line2" "line3"

# With options
clipboard_copy --no-backup "sensitive data"
clipboard_copy --timeout 5 "data with custom timeout"
```bash

**Options:**

- `--no-backup`: Disable automatic backup creation
- `--timeout N`: Set timeout in seconds (default: 2)

**Features:**

- **Automatic Backups:** Creates `$TMPDIR/zshand_clipboard_backup_$$.txt` by default
- **Retry Logic:** 3 attempts with exponential backoff (0.1s, 0.2s delays)
- **Content Verification:** Verifies clipboard content after copy using `clipboard_paste`
- **Size Validation:** Warns if content exceeds 10MB
- **Platform Auto-Detection:** Automatically selects the best tool for your platform
- **Secure Permissions:** Sets chmod 600 on backup files

**Environment Variables:**

```zsh
# Enable comprehensive logging
export ZSHAND_CLIPBOARD_LOG=1

# Custom log directory (default: $ZSHAND_CACHE/clips)
export ZSHAND_CLIPBOARD_LOG_DIR="$HOME/.cache/clipboard"
```bash

**Exit Codes:**

- `0`: Success
- `1`: Copy failed or verification failed
- `2`: No clipboard tool available

---

### clipboard_paste

Paste content from the system clipboard with caching and normalization.

**Usage:**

```zsh
# Basic paste
clipboard_paste

# With caching (1-second TTL)
clipboard_paste --cache

# Without line ending normalization
clipboard_paste --no-normalize

# With fallback text if clipboard is empty
clipboard_paste --fallback "default content"

# With custom timeout
clipboard_paste --timeout 3
```bash

**Options:**

- `--cache`: Enable 1-second cache to avoid repeated clipboard reads
- `--no-normalize`: Disable CRLF→LF line ending normalization
- `--fallback TEXT`: Return TEXT if clipboard is empty or inaccessible
- `--timeout N`: Set timeout in seconds (default: 2)

**Features:**

- **Smart Caching:** Optional 1-second TTL cache for performance
- **Line Ending Normalization:** Converts CRLF (Windows) to LF (Unix) by default
- **Retry Logic:** 3 attempts with exponential backoff
- **Fallback Support:** Return default text if clipboard operations fail
- **Clipboard History:** Saves paste operations when logging enabled
- **Platform Auto-Detection:** Automatically selects the best tool for your platform

**Environment Variables:**

```zsh
# Enable comprehensive logging
export ZSHAND_CLIPBOARD_LOG=1

# Custom log directory (default: $ZSHAND_CACHE/clips)
export ZSHAND_CLIPBOARD_LOG_DIR="$HOME/.cache/clipboard"
```bash

**Exit Codes:**

- `0`: Success
- `1`: Paste failed (unless --fallback provided)
- `2`: No clipboard tool available

---

## Logging

When `ZSHAND_CLIPBOARD_LOG=1` is set, all clipboard operations are logged comprehensively.

**Log Structure:**

```bash
$ZSHAND_CLIPBOARD_LOG_DIR/
├── clips/
   ├── copys/
      └── YYYYMMDD_HHMMSS_hash.txt
   └── pastes/
       └── YYYYMMDD_HHMMSS_hash.txt
└── clipboard.log
```bash

**Log Format:**

```bash
2026-02-02T20:30:45-07:00 COPY wl-copy wayland 1234 abc123def456
2026-02-02T20:30:50-07:00 PASTE wl-paste wayland 5678 def789abc012
```bash

**Fields:**

1. Timestamp (ISO 8601 with timezone)
2. Operation (COPY/PASTE)
3. Tool used (wl-copy, xclip, pbcopy, etc.)
4. Platform (wayland, x11, darwin, wsl)
5. Size (bytes)
6. MD5 hash (first 12 chars)

**Limits:**

- Only logs content ≤1MB in size
- All log files have chmod 600 (secure permissions)
- Individual copy/paste files are named with timestamp and content hash

---

## Platform Detection

The functions automatically detect the platform and select the best available tool:

### Wayland

**Primary:** wl-copy / wl-paste (wl-clipboard package)

```zsh
# Install on various distros
sudo pacman -S wl-clipboard     # Arch/Manjaro
sudo apt install wl-clipboard   # Ubuntu/Debian
sudo dnf install wl-clipboard   # Fedora
```bash

### X11

**Primary:** xclip
**Fallback:** xsel

```zsh
# Install on various distros
sudo pacman -S xclip xsel       # Arch/Manjaro
sudo apt install xclip xsel     # Ubuntu/Debian
sudo dnf install xclip xsel     # Fedora
```bash

### macOS

**Built-in:** pbcopy / pbpaste (no installation needed)

### WSL (Windows Subsystem for Linux)

**Built-in:** clip.exe (copy) / PowerShell Get-Clipboard (paste)

No additional installation needed - uses Windows clipboard tools.

---

## Examples

### Basic Operations

```zsh
# Copy and verify
echo "deployment-key-xyz" | clipboard_copy
clipboard_paste  # Verify it's there

# Copy with no backup (for temporary data)
clipboard_copy --no-backup "temporary text"

# Paste with fallback
config=$(clipboard_paste --fallback "default-config")
```bash

### Integration with Widgets

```zsh
# Widget: Copy buffer to clipboard
zle-copy-buffer() {
    clipboard_copy "${BUFFER}"
    zle -M "Buffer copied to clipboard"
}
zle -N zle-copy-buffer
bindkey '^X^C' zle-copy-buffer

# Widget: Paste from clipboard
zle-paste-buffer() {
    local content=$(clipboard_paste --cache)
    BUFFER="${content}"
    CURSOR=$#BUFFER
}
zle -N zle-paste-buffer
bindkey '^X^V' zle-paste-buffer
```bash

### Logging for Debugging

```zsh
# Enable logging for troubleshooting
export ZSHAND_CLIPBOARD_LOG=1

# Copy something
echo "debug data" | clipboard_copy

# Check the log
tail "$ZSHAND_CACHE/clips/clipboard.log"

# Inspect the actual content
ls -lh "$ZSHAND_CACHE/clips/copys/"
```bash

### Automated Backup Workflow

```zsh
# Copy important data with automatic backup
cat config.json | clipboard_copy

# If clipboard is lost, restore from backup
if ! clipboard_paste --cache | grep -q "expected content"; then
    echo "Clipboard lost, restoring from backup"
    cp "$TMPDIR/zshand_clipboard_backup_$$.txt" config.json
fi
```bash

### Size Handling

```zsh
# Copy large file (warns if >10MB)
cat large-file.txt | clipboard_copy

# Paste large content with extended timeout
clipboard_paste --timeout 10 > restored-file.txt
```bash

---

## Troubleshooting

### "No clipboard tool available"

**Cause:** No supported clipboard tool is installed for your platform.

**Solution:**

```zsh
# Wayland
sudo pacman -S wl-clipboard  # or apt/dnf

# X11
sudo pacman -S xclip xsel

# Check installed tools
command -v wl-copy wl-paste xclip xsel pbcopy pbpaste
```bash

### Clipboard operations hang or timeout

**Cause:** Clipboard tool is unresponsive or clipboard daemon is frozen.

**Solution:**

```zsh
# Increase timeout
clipboard_copy --timeout 10 "data"

# Restart clipboard daemon (Wayland)
killall wl-copy wl-paste
systemctl --user restart pipewire

# Check for clipboard lock files
ls -la /tmp/.clipboard*
```bash

### Content verification fails

**Cause:** Clipboard content was modified or cleared immediately after copy.

**Solution:**

```zsh
# Disable verification by not checking return code
clipboard_copy "data" || true

# Or investigate what's clearing the clipboard
export ZSHAND_CLIPBOARD_LOG=1
clipboard_copy "test"
clipboard_paste  # Check if content matches
```bash

### Line endings are wrong

**Cause:** Content came from Windows and still has CRLF line endings.

**Solution:**

```zsh
# clipboard_paste normalizes by default
clipboard_paste > file.txt  # Will have LF endings

# To preserve CRLF (rare)
clipboard_paste --no-normalize > file.txt
```bash

### Permissions denied writing backup

**Cause:** `$TMPDIR` is read-only or doesn't exist.

**Solution:**

```zsh
# Set writable TMPDIR
export TMPDIR="$HOME/.cache/tmp"
mkdir -p "$TMPDIR"

# Or disable backups
clipboard_copy --no-backup "data"
```bash

---

## Performance Considerations

### Caching

Use `--cache` on `clipboard_paste` when reading the same clipboard content multiple times within a second:

```zsh
# Efficient: Only reads clipboard once
local data=$(clipboard_paste --cache)
echo "$data" | process1
echo "$data" | process2
```bash

### Large Content

For content >10MB:

- Copy operations will warn but continue
- Paste operations may be slow
- Consider using files instead of clipboard for very large data

### Retry Delays

Default retry delays: 0.1s, 0.2s (exponential backoff)

- First attempt: immediate
- Second attempt: after 0.1s
- Third attempt: after 0.2s (total 0.3s delay)

---

## Migration from Direct Tool Usage

**Before (platform-specific):**

```zsh
# Direct wl-copy usage
echo "data" | wl-copy

# Direct xclip usage
echo "data" | xclip -selection clipboard

# Direct pbcopy usage
echo "data" | pbcopy
```bash

**After (cross-platform):**

```zsh
# Works everywhere
echo "data" | clipboard_copy
```bash

**Benefits:**

- Cross-platform compatibility
- Automatic fallbacks
- Built-in error handling
- Optional backups and logging
- Content verification

---

## See Also

- [`shared_functions/17_clipboard_copy.zsh`](../../shared_functions/17_clipboard_copy.zsh) - Source code
- [`shared_functions/18_clipboard_paste.zsh`](../../shared_functions/18_clipboard_paste.zsh) - Source code
- [`tests/shared_functions/test_clipboard_copy.zsh`](../../tests/shared_functions/test_clipboard_copy.zsh) - Tests
- [`tests/shared_functions/test_clipboard_paste.zsh`](../../tests/shared_functions/test_clipboard_paste.zsh) - Tests
- [Wayland Clipboard Protocol](https://wayland.freedesktop.org/)
- [X11 Clipboard (ICCCM)](https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html)