Search code examples
vim

How to simplify file path containing ".." when opening file


I have some .h files in inc folder and their corresponding .cpp files in lib folder.

D:\gitroot\Project\inc\A.h
D:\gitroot\Project\inc\B.h
D:\gitroot\Project\lib\A.cpp
D:\gitroot\Project\lib\B.cpp

I want to quickly open the corresponding .cpp file when working on the .h file, and vice-versa, so I put below maps in vimrc.

map \tdc :tabnew %:h/../lib/%:t:r.cpp<CR>
map \tdh :tabnew %:h/../inc/%:t:r.h<CR>

The problem is, when I use this to open the corresponding file, the file name of the tab is Project\inc\..\lib\A.cpp instead of Project\lib\A.cpp. How to simplify the file path?


Solution

  • You can use :h multiple times to remove both the file name and the containing subdirectory from the path.

    map \tdc :tabnew %:h:h/lib/%:t:r.cpp<CR>
    map \tdh :tabnew %:h:h/inc/%:t:r.h<CR>
    

    (An example of this usage can be found in the documentation; see :help filename-modifiers.)