sponsor Vim development Vim logo Vim Book Ad

basic Tip #666: switch between a *.cpp and matching .h file

 tip karma   Rating 26/14, Viewed by 1026 

created:   March 1, 2004 5:12      complexity:   basic
author:   Joerg Beyer      as of Vim:   5.7

For programmers, that want to switch from foo.cpp to foo.h (or vice versa)
on a single key stroke, this might help:

map <F4> :e %:p:s,.h$,.X123X,:s,.cpp$,.h,:s,.X123X$,.cpp,<CR>

it maps (on F4) the change of the current filename. The endings
".h" and ".cpp" are exchanged (via the magic ending ".X123X").
You could use ".hpp" or ".c" filename endings by changing
it in the replacement statemtents.

    comments are welcome
    Joerg (j.beyer@web.de)

 rate this tip  Life Changing Helpful Unfulfilling 

<<Hide & Toggle GUI widgets | Navigate large CSV files more easily >>

Additional Notes

loveunixnet@to.com, March 1, 2004 5:36
there are a.vim

I'd like use it to switch fbetween .c and .h
for it can find .h where not in same directory with ,c
leifw at bigfoot , com, March 1, 2004 7:18
What the previous poster was saying is that there is a script on vimonline called a.vim which has the functionality of this tip plus more.  It's available at vimscript #31.
toto@tttot.fr, March 2, 2004 1:58
efefefefe
http://www.cs.albany.edu/~mosh, March 24, 2004 18:20
Put these lines in ~/.vimrc and F2 will flip between
.c and .h, .hxx and .cxx, etc. Moreover the .h file need
not be in the same dir, it can be found via path variable.

- Mohsin

set  path=.,,..,../..,./*,./*/*,../*,~/,~/**,/usr/include/*

function! Mosh_Flip_Ext()
    " Switch editing between .c* and .h* files (and more).
    " Since .h file can be in a different dir, call find.
    :if match(expand("%"),"\\.c") > 0
        let s:flipname = substitute(expand("%"),"\\.c\\(.*\\)",".h\\1","")
        :exe ":find " s:flipname
    :elseif match(expand("%"),"\\.h") > 0
        let s:flipname = substitute(expand("%"),"\\.h\\(.*\\)",".c\\1","")
        :exe ":sp " s:flipname
    :endif
endfun

:map <F2> :call Mosh_Flip_Ext()<CR>    
    
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to vim@vim.org after searching the archive. Help Bram help Uganda.
Sponsored by Web Concept Group Inc. SourceForge Logo