How do I make Vim automatically change the working directory to the file I'm editing?
Answer
:set autochdir
Explanation
The autochdir option tells Vim to automatically change the current working directory to the directory of the file in the active window whenever you switch buffers or open a file. This means commands like :e, :r, and shell expansions that rely on cwd always resolve relative to the file you're looking at.
How it works
- When
autochdiris set, Vim fires aBufEnterhook that runs:lcd(local change directory) to the file's containing directory whenever focus enters a window - It uses a window-local directory change, so other windows are unaffected
- Relative paths in
:e filename,:r file, andgfwill resolve from the current file's location rather than the directory where Vim was launched
Example
You launch Vim from /home/user/ and open /home/user/projects/app/main.go. Without autochdir, :e utils.go tries to open /home/user/utils.go. With it:
:set autochdir
:e utils.go
Now Vim opens /home/user/projects/app/utils.go — the file next to main.go.
Tips
- Add
set autochdirto yourvimrcto make it permanent - If you use
autochdirglobally but need a project root for certain commands (grep, make), consider:tcd(tab-local directory) or project-root plugins as a complement - To check the current working directory at any time, run
:pwd - Use
:set noautochdirto turn it off temporarily