When editing a directory, cd into it and source a project-specific vim file

2 Points

Andrew Radev Andrew Radev

4 years ago

A nice textmate functionality I'm aware of is the ability to just mate some/directory to open the editor with the file tree based in the given directory. Or at least I think that's what it does, I've only seen other people do it.

That's quite easy to replicate in Vim, of course. With this autocommand, editing a directory cds into it and then opens netrw, or, in my case, the NERDTree. For good measure, I've also added the ability to source a project-specific file that happens to be in this directory called _project.vim (replace "_project.vim" in the snippet with whatever different filename you'd prefer).

This means that I can just vim projects/some_project in order to set up all the tools I need for that project. Or, if I happen to be in that directory twiddling on the command-line, a simple vim . pops up the project code.

augroup maybe_enter_directory
  autocmd!
  autocmd BufEnter,VimEnter * call s:MaybeEnterDirectory(expand("<amatch>"))
autocmd END

function! s:MaybeEnterDirectory(file)
  if a:file != '' && isdirectory(a:file)
    let dir = a:file
    exe "cd ".dir

    if filereadable('_project.vim')
      source _project.vim
      echo "Loaded project file"
    endif
  endif
endfunction

Florian Beer

Florian Beer 3 years ago

Thanks, this is really handy to set the path per project and also always have the right working directory.

One typo in above snippet: Line number 4 should read augroup END