Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim, exit at current files location

Tags:

bash

vim

cwd

I run Vim and change my current location all the time via shortcuts.

Then when I exit Vim, I want to be in the directory of the file I was in, in the bash shell.

How do I go about doing that?

like image 318
john-jones Avatar asked Sep 07 '26 13:09

john-jones


1 Answers

In multiprocess operating systems a subprocess cannot change anything in the parent process. But the parent process can cooperate so a subprocess can ask the parent process to do something for the subprocess. In your case on exit vim should return the last working directory and the shell should cd to it. I managed to implement cooperation this way:

In ~/.vimrc:

call mkdir(expand('~/tmp/vim'), 'p') " create a directory $HOME/tmp/vim
autocmd VimLeave * call writefile([getcwd()], expand('~/tmp/vim/cwd')) " on exit write the CWD to the file

In ~/.bashrc:

vim() {
    command vim "$@"
    rc=$?
    cd "`cat \"$HOME/tmp/vim/cwd\"`" && rm "$HOME/tmp/vim/cwd" &&
    return $rc
}
like image 133
phd Avatar answered Sep 11 '26 16:09

phd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!