graph TD
A[vimrc 中 plug#begin()] --> B[Plug 命令收集插件规格]
B --> C[s:plugs 字典与声明顺序]
C --> D[plug#
end() 统一调度]
D -->|"未安装"| E[并行 git clone]
D -->|"已安装"| F[注入 runtimepath]
E --> F
F --> G{"是否按需加载"}
G -->|"否"| H[立即 source 插件]
G -->|"是"| I[注册 autocmd 钩子]
I --> J[命令/文件类型/映射触发]
J --> K[plug#load 延迟 source]
设计上最值得说道的是并行更新的实现方式。Vim script 本身没有线程,vim-plug 的做法是“生成脚本 + 交给 shell”:把每个插件的 git fetch / git reset 拼成 shell 命令,用 & 丢到后台、末尾 wait 汇总,再把输出回读进 Vim 的 buffer 渲染。这是典型的“借宿主操作系统做并发”,代价是 Windows 平台退化为串行(没有可靠的 job control),这也是它在 Windows 上更新偏慢的根因。
按需加载的分支同样基于这种思路:它不去改 Vim 的加载器,而是用 Vim 自身的 autocmd 做“代理”。on 对应 CmdUndefined——你敲了一个尚未定义的命令,钩子先 plug#load 再让命令继续执行;for 对应 BufRead / BufNewFile 的模式匹配;映射则借助 <Plug> 与映射事件。这种设计优雅在于完全复用 Vim 的事件系统,缺点是启发式的:一旦你的插件在加载前就被别的插件调用,钩子根本等不到触发时机,于是出现“明明装了却报找不到函数”的经典问题。
版本锁定(commit / tag / branch)也是直接在 git checkout 层面做,没有版本求解,没有依赖图。这既是它的简单之源,也是它的能力边界。
适合的场景:团队内 Vim 与 Neovim 混用、需要一份配置两端跑;服务器或容器环境不希望引入额外运行时;对启动时间敏感、愿意用按需加载做优化的大型配置。
落地时的几个坑值得提前规避。第一,版本锁定要配合 CI,:PlugSnapshot 产出的快照应提交进仓库,否则“锁了 commit 但没记录”等于没锁。第二,按需加载要克制,只对启动体积大、调用频率低的插件开启,并对 on 的命令名做显式校验,避免钩子等待不到。第三,并行更新在 Windows 上不可依赖,若团队有 Windows 成员,应把更新流程放到 CI 或 WSL 中执行。第四,PlugClean 会删除未被声明的插件目录,在共享配置的机器上执行前务必确认。
iwr -useb https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim |`
ni "$(@($env:XDG_DATA_HOME, $env:LOCALAPPDATA)[$null -eq $env:XDG_DATA_HOME])/nvim-data/site/autoload/plug.vim" -Force
Usage
Add a vim-plug section to your ~/.vimrc (or ~/.config/nvim/init.vim for Neovim)
Begin the section with call plug#begin()
List the plugins with Plug commands
End the section with call plug#end()
For example,
call plug#begin()
" List your plugins here
Plug 'tpope/vim-sensible'
call plug#end()
Reload the file or restart Vim, then you can,
:PlugInstall to install the plugins
:PlugUpdate to install or update the plugins
:PlugDiff to review the changes from the last update
:PlugClean to remove plugins no longer in the list
[!NOTE]
That’s basically all you need to know to get started. The rest of the
document is for advanced users who want to know more about the features and
options.
[!TIP]
plug#end() automatically executes filetype plugin indent on and syntax enable. We believe this is a good default for most users, but if you don’t
want this behavior, you can revert the settings after the call.
call plug#end()
filetype indent off " Disable file-type-specific indentation
syntax off " Disable syntax highlighting
Getting Help
See tutorial page to learn more about the basics of vim-plug
See tips and FAQ pages for common problems and questions
Examples
The following examples demonstrate the additional features of vim-plug.
Vim script example
call plug#begin()
" The default plugin directory will be as follows:
" - Vim (Linux/macOS): '~/.vim/plugged'
" - Vim (Windows): '~/vimfiles/plugged'
" - Neovim (Linux/macOS/Windows): stdpath('data') . '/plugged'
" You can specify a custom plugin directory by passing it as the argument
" - e.g. `call plug#begin('~/.vim/plugged')`
" - Avoid using standard Vim directory names like 'plugin'
" Make sure you use single quotes
" Shorthand notation for GitHub; translates to https://github.com/junegunn/seoul256.vim.git
Plug 'junegunn/seoul256.vim'
" Any valid git URL is allowed
Plug 'https://github.com/junegunn/vim-easy-align.git'
" Using a tagged release; wildcard allowed (requires git 1.9.2 or above)
Plug 'fatih/vim-go', { 'tag': '*' }
" Using a non-default branch
Plug 'neoclide/coc.nvim', { 'branch': 'release' }
" Use 'dir' option to install plugin in a non-default directory
Plug 'junegunn/fzf', { 'dir': '~/.fzf' }
" Post-update hook: run a shell command after installing or updating the plugin
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
" Post-update hook can be a lambda expression
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
" If the vim plugin is in a subdirectory, use 'rtp' option to specify its path
Plug 'nsf/gocode', { 'rtp': 'vim' }
" On-demand loading: loaded when the specified command is executed
Plug 'preservim/nerdtree', { 'on': 'NERDTreeToggle' }
" On-demand loading: loaded when a file with a specific file type is opened
Plug 'tpope/vim-fireplace', { 'for': 'clojure' }
" Unmanaged plugin (manually installed and updated)
Plug '~/my-prototype-plugin'
" Call plug#end to update &runtimepath and initialize the plugin system.
" - It automatically executes `filetype plugin indent on` and `syntax enable`
call plug#end()
" You can revert the settings after the call like so:
" filetype indent off " Disable file-type-specific indentation
" syntax off " Disable syntax highlighting
" Color schemes should be loaded after plug#end().
" We prepend it with 'silent!' to ignore errors when it's not yet installed.
silent! colorscheme seoul256
Lua example for Neovim
In Neovim, you can write your configuration in a Lua script file named
init.lua. The following code is the Lua script equivalent to the Vim script
example above.
local vim = vim
local Plug = vim.fn['plug#']
vim.call('plug#begin')
-- Shorthand notation for GitHub; translates to https://github.com/junegunn/seoul256.vim.git
Plug('junegunn/seoul256.vim')
-- Any valid git URL is allowed
Plug('https://github.com/junegunn/vim-easy-align.git')
-- Using a tagged release; wildcard allowed (requires git 1.9.2 or above)
Plug('fatih/vim-go', { ['tag'] = '*' })
-- Using a non-default branch
Plug('neoclide/coc.nvim', { ['branch'] = 'release' })
-- Use 'dir' option to install plugin in a non-default directory
Plug('junegunn/fzf', { ['dir'] = '~/.fzf' })
-- Post-update hook: run a shell command after installing or updating the plugin
Plug('junegunn/fzf', { ['dir'] = '~/.fzf', ['do'] = './install --all' })
-- Post-update hook can be a lambda expression
Plug('junegunn/fzf', { ['do'] = function()
vim.fn['fzf#install']()
end })
-- If the vim plugin is in a subdirectory, use 'rtp' option to specify its path
Plug('nsf/gocode', { ['rtp'] = 'vim' })
-- On-demand loading: loaded when the specified command is executed
Plug('preservim/nerdtree', { ['on'] = 'NERDTreeToggle' })
-- On-demand loading: loaded when a file with a specific file type is opened
Plug('tpope/vim-fireplace', { ['for'] = 'clojure' })
-- Unmanaged plugin (manually installed and updated)
Plug('~/my-prototype-plugin')
vim.call('plug#end')
-- Color schemes should be loaded after plug#end().
-- We prepend it with 'silent!' to ignore errors when it's not yet installed.
vim.cmd('silent! colorscheme seoul256')
Commands
Command
Description
PlugInstall [name ...] [#threads]
Install plugins
PlugUpdate [name ...] [#threads]
Install or update plugins
PlugClean[!]
Remove unlisted plugins (bang version will clean without prompt)
PlugUpgrade
Upgrade vim-plug itself
PlugStatus
Check the status of plugins
PlugDiff
Examine changes from the previous update and the pending changes
PlugSnapshot[!] [output path]
Generate script for restoring the current snapshot of the plugins
Plug options
Option
Description
branch/tag/commit
Branch/tag/commit of the repository to use
rtp
Subdirectory that contains Vim plugin
dir
Custom directory for the plugin
as
Use different name for the plugin
do
Post-update hook (string or funcref)
on
On-demand loading: Commands or <Plug>-mappings
for
On-demand loading: File types
frozen
Do not remove and do not update unless explicitly specified
Global options
Flag
Default
Description
g:plug_threads
16
Default number of threads to use
g:plug_timeout
60
Time limit of each task in seconds (Ruby & Python)
g:plug_retries
2
Number of retries in case of timeout (Ruby & Python)
g:plug_shallow
1
Use shallow clone
g:plug_window
-tabnew
Command to open plug window
g:plug_pwindow
vertical rightbelow new
Command to open preview window in PlugDiff
g:plug_url_format
https://git::@github.com/%s.git
printf format to build repo URL (Only applies to the subsequent Plug commands)
Keybindings
D - PlugDiff
S - PlugStatus
R - Retry failed update or installation tasks
U - Update plugins in the selected range
q - Abort the running tasks or close the window
:PlugStatus
L - Load plugin
:PlugDiff
X - Revert the update
Post-update hooks
There are some plugins that require extra steps after installation or update.
In that case, use the do option to describe the task to be performed.
If you need more control, you can pass a reference to a Vim function that
takes a dictionary argument.
function! BuildYCM(info)
" info is a dictionary with 3 fields
" - name: name of the plugin
" - status: 'installed', 'updated', or 'unchanged'
" - force: set on PlugInstall! or PlugUpdate!
if a:info.status == 'installed' || a:info.force
!./install.py
endif
endfunction
Plug 'ycm-core/YouCompleteMe', { 'do': function('BuildYCM') }
A post-update hook is executed inside the directory of the plugin and only run
when the repository has changed, but you can force it to run unconditionally
with the bang-versions of the commands: PlugInstall! and PlugUpdate!.
[!TIP]
Make sure to escape BARs and double-quotes when you write the do option
inline as they are mistakenly recognized as command separator or the start of
the trailing comment.
Plug 'junegunn/fzf', { 'do': 'yes \| ./install' }
But you can avoid the escaping if you extract the inline specification using a
variable (or any Vim script expression) as follows:
The installer takes the following steps when installing/updating a plugin:
git clone or git fetch from its origin
Check out branch, tag, or commit and optionally git merge remote branch
If the plugin was updated (or installed for the first time)
Update submodules
Execute post-update hooks
The commands with the ! suffix ensure that all steps are run unconditionally.
On-demand loading of plugins
" NERD tree will be loaded on the first invocation of NERDTreeToggle command
Plug 'preservim/nerdtree', { 'on': 'NERDTreeToggle' }
" Multiple commands
Plug 'junegunn/vim-github-dashboard', { 'on': ['GHDashboard', 'GHActivity'] }
" Loaded when clojure file is opened
Plug 'tpope/vim-fireplace', { 'for': 'clojure' }
" Multiple file types
Plug 'kovisoft/paredit', { 'for': ['clojure', 'scheme'] }
" On-demand loading on both conditions
Plug 'junegunn/vader.vim', { 'on': 'Vader', 'for': 'vader' }
" Code to execute when the plugin is lazily loaded on demand
Plug 'junegunn/goyo.vim', { 'for': 'markdown' }
autocmd! User goyo.vim echom 'Goyo is now loaded!'
Note 注意
Should I set up on-demand loading?
You probably don’t need to.
A properly implemented Vim plugin should already load lazily without any
help from a plugin manager (:help autoload). So there are few cases where
these options actually make much sense. Making a plugin load faster is
the responsibility of the plugin developer, not the user. If you find
a plugin that takes too long to load, consider opening an issue on the
plugin’s issue tracker.
Let me give you a perspective. The time it takes to load a plugin is usually
less than 2 or 3ms on modern computers. So unless you use a very large
number of plugins, you are unlikely to save more than 50ms. If you have
spent an hour carefully setting up the options to shave off 50ms, you
will have to start Vim 72,000 times just to break even. You should ask
yourself if that’s a good investment of your time.
Make sure that you’re tackling the right problem by breaking down the
startup time of Vim using --startuptime.
vim --startuptime /tmp/log
On-demand loading should only be used as a last resort. It is basically
a hacky workaround and is not always guaranteed to work.
[!TIP]
You can pass an empty list to on or for option to disable the loading
of the plugin. You can manually load the plugin using plug#load(NAMES...)
function.
评论