tags:

views:

93

answers:

2

I want to execute a command automatically after cd'ing to a new directory from within vim. For example, I open gvim and run:

:cd ~/src/player

I would like vim at this point to automatically source a file that is in that directory.

Is this possible?

+4  A: 

You can write an alias for that in your .vimrc:

command -nargs=1 Mycd call MyCd(<args>)
function MyCd(path)
  cd a:path
  e somefile.ext
endfunction

Then just type:

:Mycd /some/path/
Lucas Oman
User commands must begin with a capital letter.
jamessan
Whoops, thanks!
Lucas Oman
I was hoping for some sort of autocommand event like BufRead and friends, but it looks like there is not currently anything like that. So this will do! Thanks.
cygnl7
A: 

Not exactly what you're asking for, but

:au BufEnter,BufFilePost * lc <afile>:h

will make it so that whenever you open a new file (e.g. with :e ~/src/player/README), you will automatically change directories to ~/src/player. If you open multiple buffers, you will be changed to the directory containing the local buffer as you change between them, and if you open multiple tabs, they will remain in their respective directories.

ephemient
I have used this approach before, and liked it. However, went back to staying at a top-level directory for what I do. There are a lot of things I've become accustomed to and have set up for working from a top-level directory (custom makeprg, grep, etc.) now and therefore don't really want to be changing directories around a lot. Thanks anyway, though.
cygnl7