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

How do I add a file to Vim's buffer list without opening or displaying it?

Answer

:badd {file}

Explanation

:badd adds a file to the buffer list silently — it loads the file's metadata but does not open a window or read the file contents until you actually switch to it. This is useful for pre-loading a set of files you intend to edit, setting them up for :bnext/:bprev navigation, or ensuring they appear in completion lists without disrupting your current window layout.

How it works

  • :badd {file} — adds {file} to the buffer list without switching to it
  • :badd +{lnum} {file} — adds the file and sets the initial cursor position to line {lnum} when it is first opened
  • The buffer gets a number and appears in :ls output with the u (unlisted? no — it IS listed) flag
  • Switch to it later with :buffer {n}, :bnext, or :b {partial-name}
  • :badd accepts glob patterns on some systems: :badd src/*.py

Example

Add all Python files in the project before starting a session:

:badd src/main.py
:badd src/utils.py
:badd tests/test_main.py
:ls

Now :bnext cycles through them. Or in a script:

:args src/**/*.py
" which also adds them to the buffer list via :badd internally

Tips

  • :badd is safe to use multiple times on the same file — if the buffer already exists, it is a no-op
  • Unlike :edit, :badd does not read the file immediately, so it is fast even for many files
  • Combine with :bufdo after adding files: :badd *.log then :bufdo /{pattern} to search across all
  • Use :bdelete {n} to remove a buffer from the list; :bwipeout removes it and its undo history entirely

Next

How do I run a search and replace only within a visually selected region?