#!/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 # ensures we are in Normal mode. # 'i' at the end returns us to Terminal-Insert mode. nvim --server "$NVIM" --remote-send \ ":lua vim.fn.setreg('$TARGET_REG', vim.base64.decode('$B64_TEXT'))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