vimtricks.wiki Concise Vim tricks, one at a time.

How do I read or modify the lines of a buffer that is not currently displayed without switching to it?

Answer

getbufline() / setbufline()

Explanation

The getbufline() and setbufline() functions let you inspect and update any loaded buffer's contents from Vimscript without switching the active window. This is essential for scripts that process multiple buffers — switching back and forth would pollute the jump list, trigger autocommands, and disrupt the user's view.

How it works

Reading lines:

" Get lines 1–5 from the buffer named 'foo.txt'
let lines = getbufline(bufnr('foo.txt'), 1, 5)
" Returns a List of strings, one per line

Writing a line:

" Replace line 3 in buffer 2 with new content
call setbufline(2, 3, 'replacement text')

Appending lines:

" Append multiple lines after line 10
call appendbufline(bufnr('%'), 10, ['new line 1', 'new line 2'])

Example: stamp a header on every loaded buffer

function! StampHeader(bufnr) abort
  if getbufline(a:bufnr, 1, 1) != ['# AUTO-GENERATED']
    call appendbufline(a:bufnr, 0, '# AUTO-GENERATED')
  endif
endfunction

bufdo call StampHeader(bufnr('%'))

Tips

  • The buffer must already be loaded (:badd loads it without displaying).
  • Use bufnr({name}) to convert a filename to a buffer number.
  • deletebufline({buf}, {first}, {last}) removes a line range from an inactive buffer.
  • Changes made via setbufline() are undoable in the target buffer.

Next

How do I open the directory containing the current file in netrw from within Vim?