I really like my vim to change its working dir to the file I'm currently working on. For this I use in my vimrc: autocmd BufEnter * if bufname("") !~ "^\[A-Za-z0-9\]*://" | lcd %:p:h | endif

What I also like is using gF(*) in vim to open files under the cursor in a new buffer.

This combination, however, induces a problem in my preferred workflow:

  1. Let's say I want to find all occurrences of "foo" in a project, so with my shell I cd to the folder path/to/project/src and execute: grep -Ern 'foo' * | vim -. For the sake of the argument the output, which is opened in vim is: a/file1.c:42: foo b/file2.c:13: foo
  2. Now I want to inspect the hit in file1 so I use gF to jump into it. This action changes the working directory to path/to/project/src/a

  3. When I go back to the tab with the output of grep the working directory stays at path/to/project/src/a because %:p:h apparently cannot resolve a path for something read from stdin.

  4. Problem: I now cannot jump into file2 via gF since the relative path is now wrong.

It would be nice to make vim automatically change its working directory to the location where it was invoked when switching to a buffer. For this example, this means when switching to the grep buffer I expect my working directory to be path/to/project/src.

I would be grateful for any ideas on how to achieve this.

(*) Full disclosure: I use spf-13 vim but the basic problem should apply to vim in general.

  • You can execute grep -Ern 'foo' $PWD/* | vim -. Grep prints full path then and vim jumps to the file regardless the current directory. – Zaboj Campula May 25 '18 at 10:20
  • Thanks for the workaround! A real solution through vim would however still be appreciated :) – Seriously May 26 '18 at 14:27
  • Instead of your :autocmd, you can simply use :set autochdir in your ~/.vimrc. Vim has this feature built-in since many versions.
  • Instead of using grep externally, try the built-in :grep (or :vimgrep) commands. The results will populate the quickfix list; the nice thing about that is that paths will automatically be adapted to changes in the working directory.
  • :grep and then using the quickfix list is actually a pretty decent solution. Didn't know about that one. Thx. – Seriously Sep 3 '18 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.