Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim set working directory

When I switch buffers in Vim (using :bn and :bp), I want it to automatically set the working directory, BUT not to be the directory of the opened file. I want Vim to search recursively upwards for a file called "tags", and when it finds that file, set the working directory to the directory with the "tags" file.

Example:

:e ~/programming/projects/foobar/src/js/scripts.js

As you can see, "foobar" is kind of the "project root". Let's assume the "tags" file is in the foobar directory. Now Vim should look in "js", but there's no tags file. Then it should look in "src", no tags file there. Then it should look in "foobar" and find the "tags" file, then do:

:cd ~/programming/projects/foobar/

Is there a simple way to do this? :)

like image 886
basteln Avatar asked Oct 09 '11 07:10

basteln


1 Answers

If your whole point is to get to the correct "tags"-file then this could be done easier:

set tags=./tags,tags;$HOME/programming,$HOME/programming/your/global/tags

The tags option accepts a comma (or space) delimited list of entries. In my example I have the following entries:

  • ./tags this means it should look first for a tags-file in the current directory
  • tags;$HOME/programming this means look for a tags-file from the current directory up to $HOME/programming (that's what the semicolon does, see file-searching). If you don't specify the "stop"-directory using the semicolon then it searches up to the root directory /
  • $HOME/programming/your/global/tags lastly this is a tags file referred to by absolute file name

My example is probably overkill for your purpose from your description you only need this:

set tags=tags;$HOME/programming

But if you really need to change the working directory then you could add something like this (change lcd to cd if you have to) to your .vimrc:

au BufNewFile,BufRead *.js execute ":lcd " . fnamemodify(findfile("tags", ".;"), ":p:h")
like image 147
vstm Avatar answered Oct 07 '22 05:10

vstm