Changing the working directory of VIM

时间:2023-03-09 00:23:13
Changing the working directory of VIM

Sometimes we want to open another file in the same folder with current editing file, what we can do to avoid typing the whole path?

For better understanding, it's better to know the info showing in the table. (when making the table, i learned how to rotate a table in Excel)
Changing the working directory of VIM
Now let's see how to edit a file in the same folder with current document quickly and easily.
1. Edit directly
:edit %:p:h/<anotherfile.txt>
using Tab key to show the complete path.
%:p:h indicates the absolute folder path of current file.
2. Change current working directory
:lcd %:p:h or :cd %:p:h
:cd is to set the working directory for all windows; while :lcd only change the working directory for current window.
3. Key mapping
in .vimrc/_vimrc, map the keystrokes ,c to do that.
nnoremap ,c :cd %:p:h<CR>
4. Using a command
in .vimrc/_vimrc, define command CD to do that.
command CD cd %:p:h
The advantage of this way is that you can customize multi commands for different directories. (As well as key mapping)
e.g.
command WORK cd D:\Work
command GAME cd E:\Game
5. autocmd
if you want it changes the working directory to the file editing automatically, adding following content in your .vimrc/_vimrc file.
autocmd BufEnter * silent! lcd %:p:h
There is another cmd can be added in vimrc,
set autochdir
But it may cause conflict with some plug-ins.
6. Add file directory to Vim path
References: