4

.vimrc文件中,如果文件是从特定目录加载的,是否可以仅执行 autocmd?

在 MacVim 中,我的代码中有一行代码.vimrc自动 cds 到包含我正在编辑的文件的目录 - 但是当我访问 :Gedit 创建的 git 文件时会导致错误(vim package fugitive)。

自动命令是:

autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')

错误是:

Error detected while processing BufEnter Auto commands for "*":

:echo expand("%")很明显,Fugitive 创建了以 开头的路径,fugitive:///所以我试图弄清楚如何测试文件路径的前 12 个字符是否 ==fugitive:///

4

3 回答 3

2

嗯,我想我理解错了。您正在更改 shell 中的目录,而不是在 Vim 中,不是吗?在这种情况下, autochdir 是不够的。

:Gedit创建一个具有时髦名称的临时文件:

:e vimrc
:Gedit ~2
:echo expand("%")
fugitive:///home/romainl/.vim/.git//8aece3dc3c19522c33c997bc82a2487e3bdf013b/vimrc
:echo expand("%:p:h")
fugitive:///home/romainl/.vim/.git//8aece3dc3c19522c33c997bc82a2487e3bdf013b/

您的外壳无法cd进入该“目录”,因为它不是有效路径。

但是,我set autochdir告诉 vimcd自动到包含当前文件的目录。多亏了这一点,我可以看到临时文件位于:

:pwd
/tmp/vGiSmH2

:pwd我可以使用cd那里的输出。

于 2012-08-25T09:23:36.177 回答
1

这可以使用strpart函数来实现。

我最终解决了以下问题:

if strpart(expand("%:p:h"), 0, 15) == "/Users/myputer/"
   autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')
endif

如果cd它以/Users/myputer/

于 2012-09-16T02:58:08.557 回答
1

这个问题有一张

autocm BufEnter * if expand('%:p') !~ '://' | :lchdir %:p:h | endif

这很好用。

于 2015-05-27T02:32:03.480 回答