7

If I open a file that isn't in the current directly, when I used Vim to autocomplete a filename, Vim provides files relative to the location where I launched Vim, not the currently edited file.

Example

$ find .
  nice-file.xml
  xml/
      messy-file.xml
      ok-file.xml
$ vim xml/messy-file.xml

Now if I type Ctrl+x,Ctrl+f, Vim provides "nice-file.xml" as a complete option. It doesn't offer ok-file.xml, even though it's in the same directory as the file I'm currently editing.

I'd like Vim to complete filenames relative to whatever file I'm editing. Is that possible?

7

You can :cd in Vim to change the current directory:

:cd xml

Or more generally, if you want to set it sometimes:

nnoremap gp :cd %:p:h<CR>

Or if you want to always be in the current file's directory:

set autochdir

Please note that this may break some plugins, because they may rely on the current directory, you can use in place:

autocmd BufEnter * silent! lcd %:p:h

If you don't want to change the current directory, you can also add the current folder to your completion path:

autocmd BufRead *
  \ let s:tempPath=escape(escape(expand("%:p:h"), ' '), '\ ') |
  \ exec "set path+=".s:tempPath
  • 2
    I cringe at overriding the wonderfully useful gf mapping. I would suggest overriding something like gs or maybe using a <leader> mapping – Peter Rincker Jul 28 '16 at 18:13
  • if a plugin does not handle acd it better be fixed. But that BufEnter workaround shouldn't be neccessary anymore – Christian Brabandt Jul 28 '16 at 19:06
  • 1
    autochdir was exactly what I was looking for. It doesn't seem to be conflicting at all with my modest plugin selection. – Scribblemacher Jul 29 '16 at 11:27

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.