Vim,在当前文件位置退出



我运行Vim,并一直通过快捷方式更改我的当前位置。

然后,当我退出Vim时,我希望在bash shell中的文件目录中。

我该怎么做?

在多进程操作系统中,子进程不能更改父进程中的任何内容。但是父流程可以合作,因此子流程可以要求父流程为子流程做一些事情。在您退出的情况下,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
}

对于未来的读者,改编自@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 '%sn' "$path"
##: Uncomment the line below to delete the "$tmp_file"
#builtin command rm "$tmp_file"
}
fi
builtin return "$rc"
}

  • 在某些系统上,vivim/etc/alternatives/kbd>,bashshell函数名仅为vim,因此避免此功能的一种快速方法是使用<kbd]vi>。或者使用命令vim调用/执行它,请参阅:help命令

以上帖子中的资源:

  • https://vim.fandom.com/wiki/Set_working_directory_to_the_current_file
  • 将工作目录更改为当前打开的文件
  • cd为什么不更改目录/
  • 我正试图编写一个将更改目录(或设置变量(的脚本,但在脚本完成后,我又回到了开始的位置(或者我的变量没有设置(

最新更新