Question

I came across very helpful mapping for VIM in vim Wiki

The mapping says:

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

I wanted to expand it - For example cc/h files

But I couldn't understand the script. Mainly the X123X

Following pattern, I just did this:

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

Now, it maps .CC->.H but not from .H->.CC instead it maps .H->.CPP.

Can any one help?

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top