I edit file /home/me/projects/myproj/src/util.c And want to start terminal at /home/me/projects/myproj/src. Vim version > 8 so I can run :terminal but it always starts at folder in which I've opened vim. Which is /home/me/projects/myproj. How can I do this?

2 Answers 2


I am grateful to @statox for useful hints, but as I don't wont to change current dir each time I come to following:

map <F6> :let $VIM_DIR=expand('%:p:h')<CR>:terminal<CR>cd $VIM_DIR<CR>
  • I don't quite get why this doesn't work for me; typing :echo $VIM_DIR outputs the correct directory, but the command fails :(
    – Krish
    Mar 12, 2021 at 20:33
  • 1
    @Krish How to debug a mapping might help.
    – statox
    Apr 16, 2021 at 13:53
  • @Krish try :terminal<CR>Acd $VIM_DIR<CR> in Neovim atleast, terminal opens up in normal mode, so you get into insert mode first (a/i/A/I) to type in the rest of the command Jan 20 at 3:22

See :h :cd and :h :lcd.

:cd changes the current directory for all the windows while :lcd changes the current directory for the current window.

You can change the current directory to the directory containing the current file with:

:cd %:p:h

And you can use set autochdir in your .vimrc to change the current working directory whenever you open a file, switch buffers, delete a buffer or open/close a window. It will change to the directory containing the file which was opened or selected. (see :h 'autochdir')

Also note that the doc mentions that autochdir may break some plugin and this wikia page suggests the following autocommand to replace this setting:

autocmd BufEnter * silent! lcd %:p:h
  • 1
    Note that when a local directory is in use for the current window, it's best to avoid :cd. When exists('*haslocaldir') && haslocaldir() is true, always use :lcd. Otherwise, we have the choice. Dec 13, 2017 at 13:29
  • 1
    Put it all together: split | lcd %:h | terminal ++curwin. May want to wrap this up into a command. e.g. command! -nargs=* Terminal split | lcd %:h | terminal ++curwin <args> Dec 13, 2017 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.