Brendan Dawes

Analogue + Digital

Process

Simple Header File Switching in Vim

I've recently been working on a project in OpenFrameworks which uses .cpp and their associated header (.h) files. I wanted to find a way to quickly switch to the header file for a source file. I had a look if there were any solutions out there, and whilst there is some plugins, it seemed overkill to install a plugin just to switch to a .h file from a .cpp file.

Instead, I created a mapping in my .vimrc so I can press ,h and Vim will automatically pull up the associated header file:

nnoremap <leader>h :e %:r.h<cr>

The percentage sign means the current file path and :r strips out the extension. Then I just add .h followed by a carriage return to execute the command and voila! Works like a charm.

Toggling Source and Header

What about if you wanted to do it the other way around and switch to the .cpp file from a .h file? We could introduce a new mapping that does the same as above but opens .cpp files but there's a better way, using a toggle function. In my .vimrc I created a function called HeaderToggle() like this:


function! HeaderToggle()
    let filename = expand("%:t")
    if filename =~ ".cpp"
        execute "e %:r.h"
    else
        execute "e %:r.cpp"
    endif
endfunction

When this function is called it grabs the file name and puts it in the variable filename. I then use an if statement to bring up the header file if the file name contains .cpp or the source file if the filename contains .h. I then change my mapping from earlier to be:

nnoremap <leader>h :call HeaderToggle()<cr>

I now have a nice source / header toggle function simply by pressing ,h