sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #64: Always set your working directory to the file you're editing

 tip karma   Rating 164/68, Viewed by 6854 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   March 28, 2001 9:12      complexity:   intermediate
author:   William Lee      as of Vim:   5.7

Sometimes I think it's helpful if your working directory is always the same as the buffer you are editing.  You need to put this in your .vimrc:

function! CHANGE_CURR_DIR()
let _dir = expand("%:p:h")
exec "cd " . _dir
unlet _dir
endfunction

autocmd BufEnter * call CHANGE_CURR_DIR()

Doing this will make a "cd" command to your the current buffer each time you switch to it.  This is actually similar to vimtip#2 but more automatic.

You should see for more details:
:help autocmd
:help expand
:help function

Note: This tip was contributed by somebody on the list a while ago (sorry for no reference) and it has been extremely helpful to me. Thanks!

 rate this tip  Life Changing Helpful Unfulfilling 

<< Applying substitutes to a visual block | Insert line number into the actuall text of the file. >>

Additional Notes

Alexey Marinichev, June 5, 2001 10:54
Autocommand that calls CHANGE_CURR_DIR can be rewritten like this:

autocmd BufEnter * cd %:p:h
Anonymous, July 19, 2001 12:19
Another approach is to keep VIM's starting directory, but have the capability to easily change directory to the file being edited.  The mapping below does that.

map ,cd :exe 'cd ' . expand ("%:p:h")<CR>
[email protected], September 29, 2001 10:39
I've found it useful to not change the directory if one is editing in /tmp (useful for things like editing CVS commit entries). Suitable modification is thus:

function! CHANGE_CURR_DIR()
    let _dir = expand("%:p:h")
    if _dir !~ '^/tmp'
      exec "cd " . _dir
    endif
    unlet _dir
endfunction
Anonymous, January 15, 2005 19:09
The above tip is great, but it does not work with directories that have space characters in the name.
Simply changing:

exec "cd " . _dir

to

exec "cd %:p:h"

fixes the issue. And perhaps the initial expand() isn't needed either?
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to the maillist. Help Bram help Uganda.
   
SourceForge.net Logo