Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

Suppose I have a folder with lots of .h and .cpp files. I frequently need to do the following:

  1. open a file prefix_SomeReallyLongFileName.h,
  2. make some changes to it,
  3. and then open prefix_SomeReallyLongFileName.cpp.

I can do this using :e <filename> using auto-complete, but as the prefix is same for many of the files, this becomes inconvenient.

Is there a quick way to open a file with same name as current file, but a different extension?

Do other people come across this situation too, and if so what is your preferred way of navigating the C++ files in a directory? Thanks.

like image 708
Neha Karanjkar Avatar asked Jun 18 '13 13:06

Neha Karanjkar


People also ask

How do I open a header file in Vim?

h" , type CTRL-W f to split the window and show the original C program and the header file. Pro: No need of changing anything – works with every Vim.

What is the difference between .cpp and .h files?

. h files, or header files, are used to list the publicly accessible instance variables and methods in the class declaration. .cpp files, or implementation files, are used to actually implement those methods and use those instance variables.

Does every .h file need a .cpp file?

Cpp files don't always have to have a header file associated with it but it usually does as the header file acts like a bridge between cpp files so each cpp file can use code from another cpp file. One thing that should be strongly enforced is the no use of code within a header file!

How do I include a .h file in another folder in CPP?

You can find this option under Project Properties->Configuration Properties->C/C++->General->Additional Include Directories. and having it find it even in lib\headers. You can give the absolute or relative path to the header file in the #include statement.


1 Answers

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

like image 157
doubleDown Avatar answered Sep 28 '22 18:09

doubleDown