Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening a directory in vim

Tags:

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.

like image 969
Abhi Beckert Avatar asked May 08 '11 21:05

Abhi Beckert


People also ask

How do I open a file in Vim?

Open a new or existing file with vim filename . Type i to switch into insert mode so that you can start editing the file. Enter or modify the text with your file. Once you're done, press the escape key Esc to get out of insert mode and back to command mode.

How do I navigate files in Vim?

Using windows. Ctrl-W w to switch between open windows, and Ctrl-W h (or j or k or l ) to navigate through open windows. Ctrl-W c to close the current window, and Ctrl-W o to close all windows except the current one. Starting vim with a -o or -O flag opens each file in its own split.

How do I open a file in Vim in terminal?

Launching Vim In order to launch Vim, open a terminal, and type the command vim . You can also open a file by specifying a name: vim foo. txt .

How do I change the current directory in Vim?

Vim has an option for this. Here's the documentation: 'autochdir' 'acd' boolean (default off) global When on, Vim will change the current working directory whenever you open a file, switch buffers, delete a buffer or open/close a window. It will change to the directory containing the file which was opened or selected.


2 Answers

$ cd ~/my/working/directory $ vim . 
like image 51
kzh Avatar answered Sep 25 '22 13:09

kzh


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 
like image 23
Abhi Beckert Avatar answered Sep 23 '22 13:09

Abhi Beckert