Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim copy and paste via a shared file

Tags:

vim

vi

How to augment vim yank and paste, so when I yank, vim writes the content to a file. When I paste, it uses the content from the file. I want to have a system wide file which serves as a global buffer.

Context: I run vim in different tmux splits on a remote server (over ssh). I want seamlessly copy and paste between vims in tmux splits. I tried a bunch of plugins, but none of them worked, thus the question.

like image 974
ashim Avatar asked Aug 22 '17 20:08

ashim


People also ask

Can you copy and paste from Vim?

You can use a movement command or up, down, right, and left arrow keys. Press y to copy, or d to cut the selection. Move the cursor to the location where you want to paste the contents. Press P to paste the contents before the cursor, or p to paste it after the cursor.

How do I select and copy an entire file in Vim?

If you're using Vim in visual mode, the standard cut and paste keys also apply, at least with Windows. CTRL A means "Mark the entire file. CTRL C means "Copy the selection.


2 Answers

I believe vim allows you to do it like this:

  1. Yank someting in file A
  2. :wv and hit enter
  3. Go to file B
  4. :rv and hit enter
  5. Hit p to paste the content of your (now) global clipboard

This should work across your different vim sessions independently of whether they run in different tmux panes or not.

like image 97
Malik Alimoekhamedov Avatar answered Sep 26 '22 00:09

Malik Alimoekhamedov


You want to have a look at:

  • map-operator because y is an operator: a motion pending command
  • readfile() and writefile() cause the r or w are commands, nice to use but not for scripts
  • visualmode() to get the selection

The shared file was hardcoded /tmp/yank.txt:

function! Yank(type, ...)
  " Invoked from Visual mode, use gv command.
  if a:0
    silent exe "normal! gvy"
  elseif a:type == 'line'
    silent exe "normal! '[V']y"
  else
    silent exe "normal! `[v`]y"
  endif

  call writefile([@@], '/tmp/yank.txt')
endfunction


function! Paste(is_back)
  let @t = join(readfile('/tmp/yank.txt'), '')
  if a:is_back
    normal! "tP
  else
    normal! "tp
  endif
endfunction


nnoremap y :set opfunc=Yank<CR>g@
nmap Y Vy
vnoremap y :call Yank(visualmode(), 1)<CR>
vnoremap Y :call Yank(visualmode(), 1)<CR>


nnoremap p :call Paste(0)<CR>
nnoremap P :call Paste(1)<CR>
like image 36
Tinmarino Avatar answered Sep 23 '22 00:09

Tinmarino