我正在尝试将我的vimrc
拆分为多个文件 - init.vim
,keybindings.vim
,ui.vim
等 - 但我无法让Vim相对于init.vim
源文件(它相对于我启动Vim的位置源。
这是我在init.vim
顶部得到的:
source keybindings.vim
source ui.vim
如果我从与这些文件相同的目录中运行vim
,它工作正常;如果我从任何其他目录运行它,则会出现以下错误:
Error detected while processing /path/to/vimrc:
line 1:
E484: Can't open file keybindings.vim
line 2:
E484: Can't open file ui.vim
Press ENTER or type command to continue
编辑:值得注意的是,我使用的是NixOS,所以我不知道绝对路径是什么,也不知道如果我发现它们是否会是恒定的。
我认为您可以使用
runtime keybindings.vim
Source 需要完整路径,但是您可以使用这样的东西来简化它:
let path = expand('%:p:h')
exec 'source' path . '/keybindings.vim'
你可以看看我的 这里 - https://github.com/dhruvasagar/dotfiles/blob/master/vim/vimrc 参考。
如果顺序不重要,你可以把你的脚本放到~/.vim/plugin/
,它们会在~/.vimrc
之后被获取。您可以检查:scriptnames
输出以查看何时获取的内容。
您可以通过插件文件名在一定程度上影响排序。例如,我有一个配置 Vim 插件的~/.vim/plugin/00plugin-configuration.vim
;00...
确保首先采购。
为了获得更精细的控制,我会将脚本放入~/.vim/
。Vim 会在那里忽略它们,但它们可以很容易地通过 :runtime
来解决,它在所有运行时路径中查找,并且~/.vim/
通常包含在'runtimepath'
中:
# .vimrc
runtime init.vim
runtime keybindings.vim
...
相关帮助页面::help .vimrc
和:help load-plugins
。
我在 Neovim 遇到了完全相同的问题。我将我的大init.vim
文件拆分为几个小的 vim 脚本,我想在 init.vim
中获取它们。这是我根据@Dhruva Sagar的链接最终得到的:
let g:nvim_config_root = stdpath('config')
let g:config_file_list = ['variables.vim',
'options.vim',
'autocommands.vim',
'mappings.vim',
'plugins.vim',
'ui.vim'
]
for f in g:config_file_list
execute 'source ' . g:nvim_config_root . '/' . f
endfor
基于Dhruva的答案,你可以创建一个函数来帮助解决这个问题
function! SourceLocal(relativePath)
let root = expand('%:p:h')
let fullPath = root . '/'. a:relativePath
exec 'source ' . fullPath
endfunction
然后你像使用它一样使用它
call SourceLocal ("yourScript.vim")
<</div>
div class="one_answers"> 由于没有一个解决方案可以真正替代全局工作的source
(在任何脚本上,甚至来自vimrc
),我最终得到了这个解决方案并决定在这里分享,它可以用作具有相对支持的source
的替代品,就像
Rsource /home/me/.vim/your/file/path
Rsource $HOME/.vim/your/file/path
Rsource your/file/path
Rsource ../your/file/path
要使用它,必须在您的vimrc
或由其提供的任何文件上定义它,然后才能使用 Rsource
:
if !exists('g:RelativeSource')
function! g:RelativeSource(file)
let file = expand(a:file)
" if file is a root path, just source it
if stridx(file, '/') == 0
exec 'source ' . file
return
endif
let sfile = expand('<sfile>:p:h')
" If this is called outside this script, it will contains this script
" name, this function name, a script_marker then the executing script name
" In this case we extract just the last part, the script name which called
" the this function
let script_marker = '..script '
let path_index = strridx(sfile, script_marker)
if path_index == -1
let path_index = 0
else
let path_index += len(script_marker)
endif
let path = strpart(sfile,path_index)
let absolute_path = resolve(path . '/'. file)
exec 'source ' . absolute_path
endfunction
command! -nargs=1 Rsource :call g:RelativeSource(<q-args>)
endif
这可以安全地用于任何脚本或插件。
这些都是很棒的解决方案,这就是我最终使用的。
let home = expand('~')
exec 'source' home . '/.config/nvim/prettierConfig.vim'