Copying to the clipboard in Vim is easy: "*y
.
What if you want to copy to your local keyboard from a vim session over ssh? "*y
no longer works here.
Highlighting text in iTerm could theoretically work. I’m using tmux with Vim over ssh, and highlighting text really doesn’t work, for whatever reason. Until now, I was stuck retyping everything, or settling for a screenshot.
But I found a nice solution with the help of this stackoverflow post: https://stackoverflow.com/questions/1152362/how-to-send-data-to-local-clipboard-from-a-remote-ssh-session
There are two components:
- a vim mapping which yanks to a “personal vim clipboard” at ~/.vim/clip.txt
- a command run locally which ssh’s in and grabs the text from the vim clipboard,
The vim mapping:
noremap <LEADER>a :e ~/.vim/clip.txt<CR>:%d<CR>"0P:w<CR>:bd<CR>:echo "copied clipboard to ~/.vim/clip.txt"<CR>
This puts whatever you have currently yanked in the default register into the clipboard file. I imagine there is a way to configure yanking to “this clipboard” the way you would any other clipboard (doing "cy
or something), but this works fine for me.
The ssh command is:
alias clip='ssh -Y salford@my_remote "cat ~/.vim/clip.txt" | pbcopy'
which I put in my bash/zsh environment so that I can get the clipboard text easily. I really only use one remote server often, so I’m content having an alias for that address specifically.
The vim mapping does the following in order:
:e ~/.vim/clip.txt<CR>
(open the clipboard in a buffer):%d<CR>
(delete the old clipboard text)"0P
(paste the yanked text into the clipboard—we do “0 since the last command filled up the default register):w<CR>:bd<CR>
(write and close the clipboard buffer):echo "copied clipboard to ~/.vim/clip.txt"<CR>
(give some feedback that this happened)
The ssh command ssh’s into the remote server, cat’s the clipboard, and pipes the output into pbcopy
, which copies the input into the system keyboard.
Maybe this will be helpful to someone. I was pleased with the vim mapping.