【问题标题】:Vim, exit at current files locationVim,退出当前文件位置
【发布时间】:2022-11-02 09:33:42
【问题描述】:

我总是通过快捷方式运行 Vim 并更改当前位置。

然后当我退出 Vim 时,我想进入我所在文件的目录,在 bash shell 中。

我该怎么做呢?

【问题讨论】:

  • 大多数情况下你不能:子进程(vim)不能修改父进程(你启动vim的shell)的工作目录。
  • 但是我可以让 Vim 在退出时返回一个字符串,这是 bash 将自己移动到的密码吗?
  • vi.stackexchange.com/a/22949 一个很好的例子来说明正在发生的事情。

标签: bash vim cwd


【解决方案1】:

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

【讨论】:

  • 我更进一步,将函数命名为 vim_cd_at_exit。然后,如果我想 vim,加上 cd 到我退出的地方,我会执行“${EDITOR}_cd_at_exit”。但如果我不想这样,我就像以前一样运行 vim。
  • @john-jones 由你决定。我根本不在vim 中使用cd/lcd,所以cd 无处可去。我只是想解决一个有趣的挑战。 :-)
  • 从中学到一些东西。投票赞成!
【解决方案2】:

对于未来的读者,改编/源自@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 -- '  .  shellescape(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"
}

  • 在某些系统上vim要点说/etc/alternatives重击shell函数名只是vim,因此避免此功能的快速方法就是使用.要么调用/执行它命令 vim, 看:帮助命令

来自上述帖子的资源:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 2013-08-02
    • 1970-01-01
    • 2016-01-27
    • 2013-11-02
    • 2010-11-15
    相关资源
    最近更新 更多