Skip to content

Instantly share code, notes, and snippets.

@TroyFletcher
Last active February 8, 2022 21:05
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save TroyFletcher/f1e7f572cbcfbad3d88e to your computer and use it in GitHub Desktop.
Save TroyFletcher/f1e7f572cbcfbad3d88e to your computer and use it in GitHub Desktop.
Sharing clipboards between vim and tmux without xsel or xclip or X forwarding
" Share clipboards between vim and tmux without xsel or xclip (which require X and
" X forwarding with SSH) and without changing tmux shortcuts. Requires only tail.
"
" Great for an ssh session to you linode or droplet.
"
" Uses z buffer in vim and writes output to ~/.clipboard and then to tmux's paste
" buffer, and reads it back in cleanly for putting (puddin').
"
" NOTE: tmux has an undocumented command limit! https://github.com/tmux/tmux/issues/254
" this means if you mean to copy larger bits of code (entire functions) tmux will
" not copy the data into its buffer. In those cases, it's better to read from the
" ~/.clipboard file.
" IE: Python interactive shell: def put(): exec(open('~/.clipboard').read());
" Example vimrc mappings
" Visual mode yank selected area to tmux paste buffer (clipboard)
"vnoremap <leader>c "zy:silent! call SendZBufferToHomeDotClipboard()<cr>
" Put from tmux clipboard
"map <leader>v :silent! call HomeDotClipboardPut()<cr>
function! SendZBufferToHomeDotClipboard()
" Yank the contents buffer z to file ~/.clipboard and tmux paste buffer
" For use with HomeDotClipboardPut()
silent! redir! > ~/.clipboard
silent! echo @z
silent! redir END
" the redir has a newline in front, so tail -n+2 skips first line
silent! !tail -n+2 ~/.clipboard > ~/.clipboard.1;mv ~/.clipboard.1 ~/.clipboard
silent! !tmux load-buffer ~/.clipboard
silent! redraw!
endfunction
function! HomeDotClipboardPut()
" Paste/Put the contents of file ~/.clipboard
" For use with SendZBufferToHomeDotClipboard()
silent! !tmux save-buffer ~/.clipboard
silent! redraw!
silent! let @z = system("cat ~/.clipboard")
" put the z buffer on the line below
silent! exe "norm o\<ESC>\"zp"
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment