summaryrefslogtreecommitdiff
path: root/copy
blob: ecd371bb3b3cd0a615b4b871dbac8ef4951ad322 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/bin/sh

# Usage: echo "text" | copy [register]
# Example: echo "Hello" | copy a

TARGET_REG=$1
RAW_INPUT=$(cat)
B64_TEXT=$(echo "$RAW_INPUT" | base64 | tr -d '\n')

# 1. Validate Register (Must be a single letter a-z or A-Z)
# This prevents malicious or malformed register names.
if [ -n "$TARGET_REG" ]; then
    if ! echo "$TARGET_REG" | grep -q '^[a-zA-Z]$'; then
        echo "Error: Register must be a single letter [a-zA-Z]." >&2
        exit 1
    fi

    # 2. Update Neovim Register via internal Lua decoder
    if [ -n "$NVIM" ]; then
        # <C-\><C-N> ensures we are in Normal mode.
        # 'i' at the end returns us to Terminal-Insert mode.
        nvim --server "$NVIM" --remote-send \
            "<C-\><C-N>:lua vim.fn.setreg('$TARGET_REG', vim.base64.decode('$B64_TEXT'))<CR>i"
    fi
fi

# 3. Dynamic TTY Detection (Fixes stale SSH_TTY in Tmux)
if [ -n "$TMUX" ]; then
    OUTPUT=$(tmux display-message -p '#{client_tty}')
elif [ -n "$SSH_TTY" ]; then
    OUTPUT="$SSH_TTY"
else
    OUTPUT="/dev/stdout"
fi

# 4. Send OSC 52 Sequence to the Terminal
if [ -n "$TMUX" ]; then
    # Double-wrapped for Tmux passthrough (DCS)
    printf "\033Ptmux;\033\033]52;c;%s\007\033\\" "$B64_TEXT" > "$OUTPUT"
elif [ -n "$NVIM" ]; then
    # Wrapped for Neovim terminal passthrough
    printf "\033P\033]52;c;%s\007\033\\" "$B64_TEXT" > "$OUTPUT"
else
    # Standard OSC 52
    printf "\033]52;c;%s\007" "$B64_TEXT" > "$OUTPUT"
fi