This mapping uses the special :s
filename modifier (:help filename-modifiers
) to swap the file extensions.
Because all substitutions are executed sequentially, the .h
extension is first transformed into the .X123X
placeholder value, so that the following .cpp
→ .h
transformation doesn't apply to it.
This trick works well for a single pair; if you want to add alternatives, I would rather switch to a Vim function that does the swapping.
function! SwappedExtension()
let [rest, ext] = [expand('%:r'), expand('%:e')]
if ext ==? 'h'
let ext = 'cpp'
elseif ext ==? 'cpp'
let ext = 'h'
endif
return rest . '.' . ext
endfunction
:nnoremap <F4> :e <C-r><C-r>SwappedExtension()<CR><CR>
Also, there are plugins that do this, e.g. the a.vim - Alternate Files quickly (.c --> .h etc).