我總是通過快捷方式運行 Vim 并更改當前位置。
然后當我退出 Vim 時,我想進入我所在檔案的目錄,在 bash shell 中。
我該怎么做呢?
uj5u.com熱心網友回復:
在多行程作業系統中,子行程不能更改父行程中的任何內容。但是父行程可以合作,因此子行程可以要求父行程為子行程做一些事情。在您的情況下,退出時vim應該回傳最后一個作業目錄,shell 應該cd回傳它。我設法以這種方式實施合作:
在~/.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
在~/.bashrc:
vim() {
command vim "$@"
rc=$?
cd "`cat \"$HOME/tmp/vim/cwd\"`" && rm "$HOME/tmp/vim/cwd" &&
return $rc
}
uj5u.com熱心網友回復:
對于未來的讀者,改編/源自@phd 的回答。
代碼.vimrc
augroup auto_cd_at_edit
autocmd!
autocmd BufEnter * silent! lcd %:p:h
augroup END
" Pointing rm to `~/` gives me the chills! :-)
" Change the path/directory according to your own desire.
function! Vim_Cd_At_Exit()
call mkdir('/dev/shm/vim_auto_cd'), 'p')
call writefile(['cd ' . getcwd()], '/dev/shm/vim_auto_cd/cwd')
endfunction
augroup Auto_Cd_After_Leave
autocmd!
autocmd VimLeave * call Vim_Cd_At_Exit()
augroup END
代碼~/.bashrc
vim() {
builtin local rc tmp_file
tmp_file=/dev/shm/vim_auto_cd/cwd
builtin command vim "$@"
rc=$?
if [[ -e "$tmp_file" && -f "$tmp_file" ]]; then
builtin source "$tmp_file"
fi
##: uncomment the code below to remove the temp file
#rm "$temp_file"
builtin return "$rc"
}
- 在某些系統上vi,vim要說/etc/alternatives的和功能名稱只是vim,所以一個快速的方法來避免這個功能就是使用vi。或者使用 呼叫/執行它command vim,請參閱:help command
也可以看看:
- https://vim.fandom.com/wiki/Set_working_directory_to_the_current_file
- 將作業目錄更改為當前打開的檔案
- 為什么-does-cd-not-change-the-directory/
- 我正在嘗試撰寫一個將更改目錄(或設定變數)的腳本,但是在腳本完成后,我又回到了我開始的地方(或者我的變數沒有設定)!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/524813.html
標籤:重击vimcwd
