murungu
murungu

Reputation: 2230

Vim: How to read from one buffer into another

In vim it easy to read a file into the current buffer with the read command:

:r my.file

But if the path to the file is really long, and the file is open in another buffer, how can I read in the contents of the buffer instead i.e.

:r {buffer_number}

Is there a way of reading from one buffer directly into another without using the yank buffer??

Upvotes: 5

Views: 2894

Answers (2)

Luc Hermitte
Luc Hermitte

Reputation: 32926

You can store the content of the buffer either directly with getline(1,'$'), or with readfile(bufname(buffnumber)). But I guess the latter cannot be used in your context otherwise, you'd have used it directly with :r.

So, you need

  • first to remember where your are. -> getwinid(), or with bufnr('%')
  • then, go to a window with the right buffer, or simply to change the current buffer
  • read its content
  • return where you were (i.e. restore the initial buffer)
  • and finally paste what you have read

It could be something like that:

" untested
function s:ReadBuffer(b) abort
  " + add test to be sure the buffer exists
  let b0 = bufnr('%')
  exe 'b ' . a:b
  let lines = getline(1, '$')
  exe 'b ' . b0
  $put=lines
endfunction

command! -nargs=1 -complete=buffer ReadBuffer call s:ReadBuffer(<f-args>)

Upvotes: 2

romainl
romainl

Reputation: 196456

In the command-line, you can use #n to address the file linked to buffer number n:

:ls      " list buffers
:r #3    " read from file associated with buffer 3

Note that :r reads from a file, not from a buffer and that the content of a buffer may be different from the content of its associated file.

You can't really avoid scripting (as in Luc Hermitte's answer) if you want to access the content of a buffer.

Upvotes: 11

Related Questions