Opening a directory in vim

Abhi Beckert picture Abhi Beckert · May 8, 2011 · Viewed 27.2k times · Source

I'm a mac user giving vim a serious try. Most of the GUI editors I'm used to allow me to open a directory as a "project" by executing a command like:

edit ~/www/example.com/

The vim equivalent vim ~/www/example.com/ will show me a list of files in the directory, and I can open them. But it does not set vim's working directory to that path, I have to run :cd . to set the working directory.

Is there some way, perhaps with a shell script, to open vim and have it's working directory set to a given path?

I'm actually using MacVim, if that makes any difference.

Answer

Abhi Beckert picture Abhi Beckert · May 10, 2011

Thanks to @sehe's suggestions, I came up with this. Not sure if it's the best solution, but it seems to work.

#!/bin/bash

if [ "$#" -eq 1 ];then # is there a path argument?
  if test -d $1;then # open directory in vim
    vim $1 +':cd %'
  else # open file in vim
    vim $1 +':cd %:h'
  fi
else # no path argument, just open vim
  vim 
fi