This is just using simple(?!) vimscript, so you can put it into your vimrc
,
now it works for .c
files, but can be modified pretty easily for .cpp
(obviously), it even has some "error handling" in the inner if-statements (that is probably pointless), but if anyone needs it, hey, it's there! Without it it's way much shorter (just leave the :e %<.h
, for example), so choose whatever you want.
function! HeaderToggle() " bang for overwrite when saving vimrc
let file_path = expand("%")
let file_name = expand("%<")
let extension = split(file_path, '\.')[-1] " '\.' is how you really split on dot
let err_msg = "There is no file "
if extension == "c"
let next_file = join([file_name, ".h"], "")
if filereadable(next_file)
:e %<.h
else
echo join([err_msg, next_file], "")
endif
elseif extension == "h"
let next_file = join([file_name, ".c"], "")
if filereadable(next_file)
:e %<.c
else
echo join([err_msg, next_file], "")
endif
endif
endfunction
then add further to your vimrc
something along these lines:
let mapleader = "," " <Leader>
nnoremap <Leader>h :call HeaderToggle()<CR>
Now whenever you're in normal mode, you press comma ,
(this is our <Leader>
button) then h
and function from the above gets called, and you will toggle between files. Tada!
include/
andsrc/
), so what you ask for doesn't happen (unless looking for the file in../include/
or../src/
). What I usually do is open two terminals, keep the header file open in one, and the source file in the other, since usually I go back and forth between the files. – Zaibatsu:e
, then hit ctrl-r %. This will put the current filename on the line, then you can replace the extension. – Zemstvo