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

How do I edit a file without overwriting the alternate buffer?

Answer

:keepalt e {file}

Explanation

Every time you open a file with :edit, Vim updates the alternate file register (#) to the previous buffer. The keepalt modifier suppresses that update, so the alternate buffer remains unchanged after the command runs. This is critical when writing macros, functions, or scripts that open helper files mid-workflow without breaking the <C-^> / # toggle you rely on.

How it works

  • # holds the alternate file: the last buffer you switched away from
  • <C-^> (or :e #) toggles between the current and alternate file — a very common quick-switch idiom
  • :edit file normally sets # to whatever was current before the edit
  • :keepalt {cmd} runs {cmd} while freezing # at its current value
  • Works with any command that would otherwise change the alternate file: :keepalt split, :keepalt read, :keepalt write, etc.

Example

You are editing main.go and toggling to main_test.go with <C-^>. You run a macro that temporarily reads a template file:

:keepalt e templates/header.tmpl
" ... copy what you need ...
:keepalt e#

After this, # still points to main_test.go, so your <C-^> workflow is undisturbed.

Tips

  • Inspect the alternate file at any time with :echo expand('#') or :ls
  • Use :keepalt in Vimscript functions that open temporary buffers to avoid surprising users
  • Combine with :keepjumps to also prevent the jumplist from being polluted: :keepjumps keepalt e {file}

Next

How do I replace every character in a visual block selection with the same character?