In Vim how to switch quickly between .h and .cpp files with the same name?

According to the Vim wiki there are quite a few suggested ways.

I will outline a few options from the article:

  • a.vim or FSwitch.vim plugins
  • using ctags
  • :e %<.c or :e %<.h. %< represents the current file w/o the extension
  • A quick mapping nnoremap <F4> :e %:p:s,.h$,.X123X,:s,.cpp$,.h,:s,.X123X$,.cpp,<CR>. Add this to your ~/.vimrc.

You can use the :r (root) filename modifier which removes the last extension (check out :h filename-modifiers for more information)

:e %:r.cpp

where

  • % is shorthand for current filename.
  • :r removes the extension
  • .cpp simply appends that string at the end.

This effectively substitutes the current file's extension with another, then open the file with the newer extension.


An even shorter way (courtesy of Peter Rincker),

:e %<.cpp

Relevant documentation at :h extension-removal

Tags:

Vim