Mastodon hachyterm.io

Navigating files with Vim is cumbersome. The default settings and the inbuilt file browser netrw are not convenient.

I use vim-picker to navigate in a project.

vim-picker is a fuzzy file picker for NeoVim and Vim:

vim-picker gif

To use vim-picker you need a program that can traverse your project with a fuzzy text selector.

vim-picker will search the current working directory. That’s the folder in which you’ve opened Vim.

The Problem

You need to open Vim in the project root directory (most often the Git project root), so that you can use fuzzy file and text searching.

But if you want to use file auto-completion relative to the opened file, the system fails you. Now you’ll get auto-completion relative to the project root.

The Requirements

Vim should use the project root folder as working directory. For me, that’s almost always a Git project.

When I insert text into a file, I want to switch the current working directory to the folder of the file. That way, auto-completion of file names work (via CTRL+X CTRL+F).

The Solution

I found this solution on superuser.com, but adjusted it to my needs.
The original resource uses autochdir, which doesn’t play well with fuzzy searching. I use lcd instead. The command sets the current directory for the Vim window.

Add this to your Vim/NeoVim configuration:

augroup working_directory
  autocmd!
  " set current directory on insert mode
  autocmd InsertEnter * let save_cwd = getcwd() | silent! lcd %:p:h
  " switch back to previous directory when leaving insert mode
  autocmd InsertLeave * silent execute 'lcd' fnameescape(save_cwd)
augroup END

If you prefer to set the project root to the Git folder, take a look at the blog post Sane Vim Working Directories by Jonathan Lehman.

Further Reading