The article at http://vim.wikia.com/wiki/Set_working_directory_to_the_current_file offers two suggestions.
One that sets the
autochdiroption.set autochdirAnother that uses
autocmdonBufEnterevent.autocmd BufEnter * silent! lcd %:p:h
This question is about autocmd only.
On StackOverflow, there are other posts where the answers suggest using autocmd BufEnter to solve this problem.
But lcd is local to a window. The current directory for every window remains intact unless we explicitly change it. So I am curious why autocmd BufEnter is being suggested here. It feels excessive to me because autocmd BufEnter executes lcd every time I switch between windows, say with Ctrl-w w, even when the buffer in window I am switching to hasn't changed.
I think, it is sufficient to execute lcd whenever a buffer in a window changes, thus autocmd BufwinEnter is sufficient.
What can go wrong if autocmd BufWinEnter is used instead?
For example, let us consider the following alternate solution.
autocmd BufWinEnter * lcd %:p:h
Can you describe a scenario where the autocmd BufEnter command would do the right thing but autocmd BufWinEnter command would not?