How do I automatically change Vim's working directory to the project root when opening a file?
Answer
vim-rooter (auto :lcd to project root)
Explanation
vim-rooter (by Andrew Radev) automatically changes Vim's working directory to the root of the project whenever you open a file. It identifies the project root by looking for root markers like .git, Makefile, package.json, or any pattern you configure.
How it works
- You open any file inside a project
- vim-rooter walks up the directory tree looking for configured root markers
- If found, it runs
:lcd(or:tcd) to change the working directory to that root - File operations,
:find,:grep, and plugins now operate from the project root
Install with: Plug 'airblade/vim-rooter'
Configuration
" Define what counts as a project root
let g:rooter_patterns = ['.git', 'Makefile', 'package.json', 'pyproject.toml', 'Cargo.toml']
" Change to root of the file's project (default)
let g:rooter_cd_cmd = 'lcd'
" Or use tab-local directory
let g:rooter_cd_cmd = 'tcd'
" Only change when opening certain files
let g:rooter_targets = '/,*.py,*.js'
" Disable automatic changing (only manual trigger)
let g:rooter_manual_only = 1
Manual trigger
:Rooter — manually trigger root detection for the current file
Tips
- Without vim-rooter,
:grep,:find, FZF, etc. search relative to wherever you launched Vim — not the project root - Combine with
:tcdscope for multi-project workflows (each tab has its own project root) - vim-rooter pairs well with FZF or Telescope — they automatically search from the current working directory
- Alternative: vim-projectroot or configure your plugin manager to set root automatically on startup