我经常使用 Vim 并通过快捷键更改当前位置。
然后,当我退出 Vim 时,我希望能在 bash shell 中处于我所在文件的目录。
我该如何实现这个功能?
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
}
vim
中使用cd
/lcd
,所以也没有地方可以cd
到。我只是想解决一个有趣的挑战。 :-) - phd针对未来读者,本文内容参考/借鉴自@phd的回答。
vimrc
代码:
augroup auto_cd_at_edit
autocmd!
autocmd BufEnter * if expand('%p:h') !~ getcwd() | silent! lcd %:p:h | endif
augroup END
" Pointing rm to `~/` gives me the chills! :-)
" Change the *path_name, file_name according to your own desire.
function! Vim_Cd_At_Exit()
let l:file_name = 'cwd'
let l:sub_pathname = 'vim_auto_cd'
let l:path_name = getenv('TMPDIR') . '/' . l:sub_pathname
call mkdir(l:path_name, 'p')
call writefile(['cd -- ' . shellescape(getcwd())], l:path_name . '/' . l:file_name)
endfunction
augroup Auto_Cd_After_Leave
autocmd!
autocmd VimLeave * call Vim_Cd_At_Exit()
augroup END
编写~/.bashrc
的代码
##: if `declare -p TMPDIR` has a value, you can skip this part
##: If not make sure your system has `/dev/shm` by default
##: otherwise use another directory.
export TMPDIR=${TMPDIR:-/dev/shm}
vim() {
builtin local IFS rc path tmp_file
tmp_file="$TMPDIR/vim_auto_cd/cwd"
builtin command vim "$@"
rc=$?
if [[ -e "$tmp_file" && -f "$tmp_file" ]]; then
IFS= builtin read -r path < "$tmp_file"
[[ -n "$path" && "${path#cd -- }" != "'$PWD'" ]] && {
builtin source "$tmp_file" || builtin return
builtin printf '%s\n' "$path"
##: Uncomment the line below to delete the "$tmp_file"
#builtin command rm "$tmp_file"
}
fi
builtin return "$rc"
}
上面帖子中的资源: