开发者

vim set working directory

开发者 https://www.devze.com 2023-04-12 06:00 出处:网络
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 f

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/project开发者_StackOverflow社区s/foobar/

Is there a simple way to do this? :)


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")


Disclaimer: I'm the author of the mentioned plugin.

I think you could use the little codepath.vim. I wrote it because I was in need of a little function that would help me to reach my project root. The plugin makes the assumption you have a folder with all your code. Something like $HOME/code. Well, it provides the following function:

codepath#path()

I use in combinations with plugins like NERDTree or command-t. So I can open a NERDTree window in my project root. It really is a little plugin but I use it all the time.

0

精彩评论

暂无评论...
验证码 换一张
取 消