Vim file name completion relative to current file

8

3

In Vim, when I am in insert mode, and I want to use file-name completion, I want the search path to be relative to the current file, not the current working directory. For instance, if in insert mode I type the following:

./^X^F

The completion menu is showing me files in the :pwd, but I would rather see the files in %:p:h listed.

Is there an option that I can set to fix this, and if not what do you suggest as a workaround?

kzh

Posted 2013-06-05T17:16:05.733

Reputation: 3 213

Answers

13

If you

:set autochdir

you'll get the behavior you desire. However, if you need to keep the working directory (e.g. to easily open other project files), you'd have to save / restore the CWD with autocmds:

:autocmd InsertEnter * let save_cwd = getcwd() | set autochdir
:autocmd InsertLeave * set noautochdir | execute 'cd' fnameescape(save_cwd)

Ingo Karkat

Posted 2013-06-05T17:16:05.733

Reputation: 19 513

2Thank you! autochdir was great for C-X, C-F, but annoying when I'm 4 levels deep in a project and I want to :tabe – Mark K Cowan – 2015-05-28T10:15:05.273

4

@Ingo Karkat's answer is nice, but I am a little hesitant to put that in my vimrc, because even the help page for 'autochdir' gives a note that it's useage will break some plugins.

I have come up with my own solution which may be very niche to my use-cases:

inoremap ./<C-X><C-F> <C-O>:lcd %:p:h<CR><C-X><C-F>

I plan on extracting it out into a function and setting a variable for the pwd before the lcs command is issued and then resetting it at some point in time. It would be nice if there was a menu autocmd.

I may or may not use this, but I thought I would throw out another solution.

kzh

Posted 2013-06-05T17:16:05.733

Reputation: 3 213