In Vim how to switch quickly between .h and .cpp files with the same name?

后端 未结 6 2028
太阳男子
太阳男子 2020-12-23 16:55

Suppose I have a folder with lots of .h and .cpp files. I frequently need to do the following:

  1. open a file prefix_SomeReallyLongFileName.h,
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-23 17:23

    Adding my two cents ;) to the above great answers:

    1. Install Exuberant Ctags
    2. Put the following code into your .vimrc
    " Jump to a file whose extension corresponds to the extension of the current
    " file. The `tags' file, created with:
    " $ ctags --extra=+f -R .
    " has to be present in the current directory.
    function! JumpToCorrespondingFile()
        let l:extensions = { 'c': 'h', 'h': 'c', 'cpp': 'hpp', 'hpp': 'cpp' }
        let l:fe = expand('%:e')
        if has_key(l:extensions, l:fe)
            execute ':tag ' . expand('%:t:r') . '.' . l:extensions[l:fe]
        else
            call PrintError(">>> Corresponding extension for '" . l:fe . "' is not specified") 
        endif
    endfunct
    
    " jump to a file with the corresponding extension ( aka )
    nnoremap  :call JumpToCorrespondingFile()
    inoremap  :call JumpToCorrespondingFile()
    
    " Print error message.
    function! PrintError(msg) abort
        execute 'normal! \'
        echohl ErrorMsg
        echomsg a:msg
        echohl None
    endfunction
    

提交回复
热议问题