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

How do I change the working directory to the folder containing the current file without affecting other windows?

Answer

:lcd %:p:h

Explanation

:lcd %:p:h sets the working directory for the current window to the directory of the file you're editing, using Vim's path expansion modifiers. Unlike :cd, which changes the global working directory for the entire Vim session, :lcd applies only to the current window — other splits keep their own directories.

How it works

  • :lcd — local change directory (window-scoped, does not affect other windows)
  • % — the current file's path
  • :p — expand to full absolute path
  • :h — take the head (directory part), stripping the filename

So %:p:h expands to the absolute path of the directory containing the current file, even if you opened the file from a different directory.

Example

If you're editing /home/user/projects/myapp/src/main.go and you run:

:lcd %:p:h

The current window's directory becomes /home/user/projects/myapp/src/. Running :!ls or using file completion now starts from that directory.

Tips

  • Use :pwd to confirm the current working directory after running the command
  • To affect all windows in the current tab, use :tcd %:p:h instead of :lcd
  • To change the global directory for the session, use :cd %:p:h
  • Add it to your vimrc with an autocmd to do it automatically per-buffer: autocmd BufEnter * silent! lcd %:p:h
  • Compare with :set autochdir (global setting that does the same thing but applies globally and may conflict with plugins)

Next

How do I inspect all syntax highlight groups stacked under the cursor to debug colorscheme or syntax issues?