Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening files in the same folder as the current file, in vim

Tags:

vim

vi

unix

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
like image 832
cloudhead Avatar asked Nov 10 '09 15:11

cloudhead


4 Answers

:Ex short for :Explore does exactly what you asked for.

like image 85
sumek Avatar answered Sep 22 '22 05:09

sumek


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.

like image 40
hgmnz Avatar answered Sep 22 '22 05:09

hgmnz


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
like image 43
gregf Avatar answered Sep 22 '22 05:09

gregf


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.

like image 22
Cory Engebretson Avatar answered Sep 22 '22 05:09

Cory Engebretson