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

后端 未结 6 2047
太阳男子
太阳男子 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:28

    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 = "," " 
    nnoremap h :call HeaderToggle()
    

    Now whenever you're in normal mode, you press comma , (this is our button) then h and function from the above gets called, and you will toggle between files. Tada!

提交回复
热议问题