vimtricks.wiki Concise Vim tricks, one at a time.

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 autochdir is set, Vim fires a BufEnter hook 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, and gf will 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 autochdir to your vimrc to make it permanent
  • If you use autochdir globally 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 noautochdir to turn it off temporarily

Next

How do I complete identifiers using ctags from within insert mode?