5

I notice when I launch Vim, the ^X^F completion works in the current directory I launch Vim in, not where the current file is.

For example, if I use vim /path/to/foo/file.txt instead of vim file.txt, it will not complete in /path/to/foo/, only in the working directory if that makes sense.

So I was wondering if I can change that. I tried to use :!cd /path/to/foo in Vim, and that did not work, it still completes where I launch vim, not where the file is.

How do I make ^X^F work better for me? Is there some other command I might be missing?

It works fine if I cd to it first before launching Vim, but is there a proper way to change the current directory within Vim itself, maybe?

2 Answers 2

5

The command to change the Vim current working directory is:

:cd path/to/file

For the current filename folder you can also use:

:cd %:h

Remark: There are also variants (lcd and tcd that changes the Vim working directory only for the current buffer or for all the buffers that share the same tab respectively)

Some automatically change the Vim working directory to either:

  • the current file folder (:set autochdir)
  • the project root folder (e.g: via the vim-rooter plugin)

You could be interested by the vim-relatively-complete plugin that provides file completion relative to the file path instead of the current working directory folder by changing temporarily the Vim local working directory (lcd) while looking for file completion.

1
  • 1
    Ah, it's always the internal commands I forget to check first. Side note but I should do a more advanced Vim tutorial because it seems like searching for things in the help file that I want needs a help file in itself. Haha.
    – mrjpaxton
    Dec 16, 2023 at 9:15
3
:!cd /path/to/foo

doesn't do what you want because :! executes the external command cd in a subshell. Changing directory outside of Vim, either in a subshell or in its parent shell has no effect whatsoever on Vim's internal state. See :help :!.

What you need is the internal command :cd:

:cd /path/to/foo

See :help :cd.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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