Search code examples
vimterminalchdir

In Vim, how can I prevent chdir to buffer directory from running when I switch to terminal pane?


In my .vimrc, I have:

autocmd BufEnter * :lchdir %:p:h

which changes the current directory to the directory for the file being edited in that window.

With the terminal feature enabled, however, I get the following messages:

Error detected while processing BufEnter Autocommands for "*":
E344: Can't find directory "C:\Users\sinan\!C:\WINDOWS\system32" in cdpath
E472: Command failed

which then have to be dismissed by pressing enter. This makes it annoying to switch back & forth between a document window and terminal.

Here's a screenshot:

In Vim, switching to terminal causes chdir error

I understand why I get the error. I am trying to figure out how I need to change the autocmd line above so it doesn't run for terminal panes. That is, instead of *, I need to specify not a terminal.

How do I do that?


Solution

  • You can check 'buftype' to see if it is a terminal buffer.

    augroup AutoChdir
      autocmd!
      autocmd BufEnter * if &buftype !=# 'terminal' | lchdir %:p:h | endif
    augroup END
    

    NOTE: I have not tested this. Use as is.

    See :h 'buftype' for more information