title: Which autocmd event to use to set the current directory to the directory of the file in the current window?
body: <p>The article at <a href="http://vim.wikia.com/wiki/Set_working_directory_to_the_current_file" rel="nofollow noreferrer">http://vim.wikia.com/wiki/Set_working_directory_to_the_current_file</a> offers two suggestions.</p>
  
  <ul>
  <li><p>One that sets the <code>autochdir</code> option.</p>
  
  <pre><code>set autochdir
  </code></pre></li>
  <li><p>Another that uses <code>autocmd</code> on <code>BufEnter</code> event.</p>
  
  <pre><code>autocmd BufEnter * silent! lcd %:p:h
  </code></pre></li>
  </ul>
  
  <p>This question is about <code>autocmd</code> only.</p>
  
  <p>On StackOverflow, there are other posts where the answers suggest using <code>autocmd BufEnter</code> to solve this problem.</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/q/2288756/303363">How to set working/current directory in Vim?</a></li>
  <li><a href="https://stackoverflow.com/q/3847796/303363">Change working directory to currently opened file</a></li>
  </ul>
  
  <p>But <code>lcd</code> is local to a window. The current directory for every window remains intact unless we explicitly change it. So I am curious why <code>autocmd BufEnter</code> is being suggested here. It feels excessive to me because <code>autocmd BufEnter</code> executes <code>lcd</code> every time I switch between windows, say with <code>Ctrl-w w</code>, even when the buffer in window I am switching to hasn't changed.</p>
  
  <p>I think, it is sufficient to execute <code>lcd</code> whenever a buffer in a window changes, thus <code>autocmd BufwinEnter</code> is sufficient.</p>
  
  <p>What can go wrong if <code>autocmd BufWinEnter</code> is used instead?</p>
  
  <p>For example, let us consider the following alternate solution.</p>
  
  <pre><code>autocmd BufWinEnter * lcd %:p:h
  </code></pre>
  
  <p>Can you describe a scenario where the <code>autocmd BufEnter</code> command would do the right thing but <code>autocmd BufWinEnter</code> command would not?</p>