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

How do I quickly switch between the current file and the last file I was editing?

Answer

:e #

Explanation

:e # opens the alternate file — the file you were editing just before the current one. It is Vim's built-in equivalent of a "go back" button between two files. The # symbol is a special filename modifier that always expands to the alternate file's path.

How it works

  • :e # — switch to the alternate file (same as <C-^> in normal mode)
  • <C-^> (or <C-6> on some keyboards) — the normal-mode shortcut for the same action
  • :b# — switch to the alternate buffer specifically (by buffer number)
  • The alternate file is shown as # in :ls output

The alternate file is set whenever you switch files: opening a new file with :e, :find, :b, or even following a tag with <C-]> updates it.

Example

:e src/main.go       " open main.go (current)
:e src/handler.go    " open handler.go (current); main.go becomes alternate
:e #                 " back to main.go; handler.go is now alternate
:e #                 " back to handler.go — toggle back and forth

Tips

  • Use <C-^> in normal mode for the fastest toggle — no need to enter command mode
  • :e # also works in :r # to read the alternate file's contents into the current buffer
  • % expands to the current filename; # expands to the alternate — both work in Ex commands
  • For quick toggling between a source file and its test file, set up a mapping: :nnoremap <leader>a <C-^>

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?