Working on a Project in Vim

Many of the modern editors have the concept of working on a “Project”. Usually this is just a fancy way of saying “files in a specific folder”.

Vim does the same thing. Wherever you the first file from is assumed to be the top level of whatever you’re working on.

Imagine this is your project’s directory:

my_project/
├── controllers
│   └── controller_a.rb
├── models
│   └── model_a.rb
└── views
    └── view_a.erb

It doesn’t really matter what folder my_projects lives under. Now, most people who are new to the command line tend to cd down to the directory that has the file they work on. If we wanted to edit model_a.rb they might cd my_project/models/ and then mvim model_a.rb. That would work, but it’s not the way Vim (or most editors these days) expect to work in a “project”.

Instead cd to the top directory of your project and then open the files from there. So cd my_project and then mvim models/model_a.rb

Think Projects, not Files

Why? Well, Vim pays attention to the directory you opened it from, and from then on (in that window) it considers that same directory to be the “root” of your project. So, let’s say I’d opened models/model_a.rb and I wanted to edit controllers/controller_a.rb I’d simply tell Vim

	:edit controllers/controller_a.rb

Every file is going to be relative to the root that was set when I first invoked Vim. This is also why you should always launch it from the command line. Just because you have a fancy app icon somewhere doesn’t mean you have to click it.

But I do think in terms of files…

If it’s easier for you to think about directory navigation and open files as if your current directory was the same as the current file then Vim has you covered. Add the following to your .vimrc.

set autochdir

What does this mean practically? Well if you were editing model_a.rb in the example project you would have to type this to open view_a.erb: :edit ../views/view_a.erb. Without this you’d type :edit views/view_a.erb. If you usually use the visual folder structure to navigate then it will start by showing the same directory as the current file when you open it.

If you open a new tab without specifying a file that new tab will be working from the same directory as the file you were looking at when you opened it.