unixvimvi

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

Solution

  • 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