简体   繁体   English

"如何在 .vimrc 中获取文件"

[英]How to source files in .vimrc

I am trying a simple means of sourcing a file based on the filetype of the new opened file.我正在尝试一种基于新打开文件的文件类型来获取文件的简单方法。 For example, I want to source python.vimrc when a new file is *.py.例如,当一个新文件是 *.py 时,我想 source python.vimrc。 This code (in .vimrc)此代码(在 .vimrc 中)

function LoadFileTypeDefaults()
  let vimrcfile = &filetype . '.vimrc' 
  if filereadable(vimrcfile)
    echo vimrcfile
    source vimrcfile
  endif
endfunction

gives the following error when I do vi new.py当我执行vi new.py时出现以下错误

python.vimrc蟒蛇.vimrc

Error detected while processing function LoadFileTypeDefault:处理函数 LoadFileTypeDefault 时检测到错误:

line 4:第 4 行:

E484: Can't open file vimrcfile E484: 无法打开文件 vimrcfile

My python.vimrc is in my runpath.我的 python.vimrc 在我的运行路径中。 Moreover, if I replace此外,如果我更换

source vimrcfile

with

source python.vimrc 

everything works as required.一切都按要求工作。

What am I missing?我错过了什么?

The source command expects a file name, not an expression. source命令需要文件名,而不是表达式。 You gave it vimrcfile so it's looking for the file called vimrcfile . 您给了它vimrcfile所以它正在寻找名为vimrcfile的文件。 Use execute to string together a command from one or more expressions. 使用execute将来自一个或多个表达式的命令串在一起。

exe 'source' vimrcfile

(If you pass multiple arguments they will be joined with spaces before executing.) (如果传递多个参数,它们将在执行前与空格连接。)


What you probably really want is to just add 您可能真正想要的只是添加

autocmd Filetype python set expandtab " etc

in your .vimrc . 在您的.vimrc


Or if you really have a lot of settings, put them in ~/.vim/after/ftplugin/python.vim . 或者,如果您确实有很多设置,请将它们放在~/.vim/after/ftplugin/python.vim

Shouldn't it be execute "source " . vimrcfile 它不应该execute "source " . vimrcfile execute "source " . vimrcfile ? execute "source " . vimrcfile

Vim has a system for dealing with this kind of thing, called filetype plugins, or ftplugins. Vim有一个用于处理这种情况的系统,称为文件类型插件或ftplugins。

In your ~/.vim (or whatever is standard on your OS), go to the ftplugins directory (create if it doesn't exist) and create a python directory under that. ~/.vim (或操作系统中的标准配置)中,转到ftplugins目录(如果不存在则创建),并在该目录下创建python目录。 Any .vim file under that directory will automatically be sourced when a .py file is loaded. 加载.py文件时,该目录下的任何.vim文件都会自动获得。

Note that you need to have filetype plugin on . 请注意,您需要在上安装filetype plugin on

Alternatively you can do this with autocommands, though it is a bit cumbersome: 另外,您也可以使用自动命令来执行此操作,尽管这有点麻烦:

autocmd BufNewFile,BufRead *.py source python.vimrc

Put that in your normal vimrc, and it'll do what you want. 将其放入您的常规vimrc中,它将完成您想要的操作。

作为 vim 命令:

:so ~/.vimrc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM