Opening files in the same folder as the current file, in vim
In vim, when I have a buffer open, I often need to load another file in the same directory that file is in, but since I don't usually cd
into it, the pwd
is a parent folder, so I have to retype the path every time. Is there a shortcut for this? or a way to change the pwd to the directory the file is in?
example:
cd /src
vi lib/foo/file.js
lib/foo has two files: file.js
and file2.js
in vi:
:e file2.js # doesn't work
:Ex short for :Explore does exactly what you asked for.
I have the following three lines on my .vimrc
:
map ,e :e <C-R>=expand("%:p:h") . "/" <CR>
map ,t :tabe <C-R>=expand("%:p:h") . "/" <CR>
map ,s :split <C-R>=expand("%:p:h") . "/" <CR>
Now ,e <some-file>
opens on this buffer. ,t
and ,s
do the same but on a new tab/split window.
Newer versions of vim have a autochdir command built in, if not you can fall back to a BufEnter like setup.
" set vim to chdir for each file
if exists('+autochdir')
set autochdir
else
autocmd BufEnter * silent! lcd %:p:h:gs/ /\\ /
endif
A simple idea is to use the autochdir setting. Try this in your .vimrc:
set autochdir
This will change the working directory of vim to the directory of the file you opened.
Note: I'm not sure what version added this feature. I updated from vim 6 to 7.2 to get this to work.
Try the following:
:e %:p:h/file2.js