├── autoload └── plug.vim └── init.vim /autoload/plug.vim: -------------------------------------------------------------------------------- 1 | " vim-plug: Vim plugin manager 2 | " ============================ 3 | " 4 | " Download plug.vim and put it in ~/.vim/autoload 5 | " 6 | " curl -fLo ~/.vim/autoload/plug.vim --create-dirs \ 7 | " https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim 8 | " 9 | " Edit your .vimrc 10 | " 11 | " call plug#begin('~/.vim/plugged') 12 | " 13 | " " Make sure you use single quotes 14 | " 15 | " " Shorthand notation; fetches https://github.com/junegunn/vim-easy-align 16 | " Plug 'junegunn/vim-easy-align' 17 | " 18 | " " Any valid git URL is allowed 19 | " Plug 'https://github.com/junegunn/vim-github-dashboard.git' 20 | " 21 | " " Multiple Plug commands can be written in a single line using | separators 22 | " Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets' 23 | " 24 | " " On-demand loading 25 | " Plug 'preservim/nerdtree', { 'on': 'NERDTreeToggle' } 26 | " Plug 'tpope/vim-fireplace', { 'for': 'clojure' } 27 | " 28 | " " Using a non-default branch 29 | " Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' } 30 | " 31 | " " Using a tagged release; wildcard allowed (requires git 1.9.2 or above) 32 | " Plug 'fatih/vim-go', { 'tag': '*' } 33 | " 34 | " " Plugin options 35 | " Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' } 36 | " 37 | " " Plugin outside ~/.vim/plugged with post-update hook 38 | " Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' } 39 | " 40 | " " Unmanaged plugin (manually installed and updated) 41 | " Plug '~/my-prototype-plugin' 42 | " 43 | " " Initialize plugin system 44 | " call plug#end() 45 | " 46 | " Then reload .vimrc and :PlugInstall to install plugins. 47 | " 48 | " Plug options: 49 | " 50 | "| Option | Description | 51 | "| ----------------------- | ------------------------------------------------ | 52 | "| `branch`/`tag`/`commit` | Branch/tag/commit of the repository to use | 53 | "| `rtp` | Subdirectory that contains Vim plugin | 54 | "| `dir` | Custom directory for the plugin | 55 | "| `as` | Use different name for the plugin | 56 | "| `do` | Post-update hook (string or funcref) | 57 | "| `on` | On-demand loading: Commands or ``-mappings | 58 | "| `for` | On-demand loading: File types | 59 | "| `frozen` | Do not update unless explicitly specified | 60 | " 61 | " More information: https://github.com/junegunn/vim-plug 62 | " 63 | " 64 | " Copyright (c) 2017 Junegunn Choi 65 | " 66 | " MIT License 67 | " 68 | " Permission is hereby granted, free of charge, to any person obtaining 69 | " a copy of this software and associated documentation files (the 70 | " "Software"), to deal in the Software without restriction, including 71 | " without limitation the rights to use, copy, modify, merge, publish, 72 | " distribute, sublicense, and/or sell copies of the Software, and to 73 | " permit persons to whom the Software is furnished to do so, subject to 74 | " the following conditions: 75 | " 76 | " The above copyright notice and this permission notice shall be 77 | " included in all copies or substantial portions of the Software. 78 | " 79 | " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 80 | " EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 81 | " MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 82 | " NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 83 | " LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 84 | " OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 85 | " WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 86 | 87 | if exists('g:loaded_plug') 88 | finish 89 | endif 90 | let g:loaded_plug = 1 91 | 92 | let s:cpo_save = &cpo 93 | set cpo&vim 94 | 95 | let s:plug_src = 'https://github.com/junegunn/vim-plug.git' 96 | let s:plug_tab = get(s:, 'plug_tab', -1) 97 | let s:plug_buf = get(s:, 'plug_buf', -1) 98 | let s:mac_gui = has('gui_macvim') && has('gui_running') 99 | let s:is_win = has('win32') 100 | let s:nvim = has('nvim-0.2') || (has('nvim') && exists('*jobwait') && !s:is_win) 101 | let s:vim8 = has('patch-8.0.0039') && exists('*job_start') 102 | if s:is_win && &shellslash 103 | set noshellslash 104 | let s:me = resolve(expand(':p')) 105 | set shellslash 106 | else 107 | let s:me = resolve(expand(':p')) 108 | endif 109 | let s:base_spec = { 'branch': '', 'frozen': 0 } 110 | let s:TYPE = { 111 | \ 'string': type(''), 112 | \ 'list': type([]), 113 | \ 'dict': type({}), 114 | \ 'funcref': type(function('call')) 115 | \ } 116 | let s:loaded = get(s:, 'loaded', {}) 117 | let s:triggers = get(s:, 'triggers', {}) 118 | 119 | function! s:is_powershell(shell) 120 | return a:shell =~# 'powershell\(\.exe\)\?$' || a:shell =~# 'pwsh\(\.exe\)\?$' 121 | endfunction 122 | 123 | function! s:isabsolute(dir) abort 124 | return a:dir =~# '^/' || (has('win32') && a:dir =~? '^\%(\\\|[A-Z]:\)') 125 | endfunction 126 | 127 | function! s:git_dir(dir) abort 128 | let gitdir = s:trim(a:dir) . '/.git' 129 | if isdirectory(gitdir) 130 | return gitdir 131 | endif 132 | if !filereadable(gitdir) 133 | return '' 134 | endif 135 | let gitdir = matchstr(get(readfile(gitdir), 0, ''), '^gitdir: \zs.*') 136 | if len(gitdir) && !s:isabsolute(gitdir) 137 | let gitdir = a:dir . '/' . gitdir 138 | endif 139 | return isdirectory(gitdir) ? gitdir : '' 140 | endfunction 141 | 142 | function! s:git_origin_url(dir) abort 143 | let gitdir = s:git_dir(a:dir) 144 | let config = gitdir . '/config' 145 | if empty(gitdir) || !filereadable(config) 146 | return '' 147 | endif 148 | return matchstr(join(readfile(config)), '\[remote "origin"\].\{-}url\s*=\s*\zs\S*\ze') 149 | endfunction 150 | 151 | function! s:git_revision(dir) abort 152 | let gitdir = s:git_dir(a:dir) 153 | let head = gitdir . '/HEAD' 154 | if empty(gitdir) || !filereadable(head) 155 | return '' 156 | endif 157 | 158 | let line = get(readfile(head), 0, '') 159 | let ref = matchstr(line, '^ref: \zs.*') 160 | if empty(ref) 161 | return line 162 | endif 163 | 164 | if filereadable(gitdir . '/' . ref) 165 | return get(readfile(gitdir . '/' . ref), 0, '') 166 | endif 167 | 168 | if filereadable(gitdir . '/packed-refs') 169 | for line in readfile(gitdir . '/packed-refs') 170 | if line =~# ' ' . ref 171 | return matchstr(line, '^[0-9a-f]*') 172 | endif 173 | endfor 174 | endif 175 | 176 | return '' 177 | endfunction 178 | 179 | function! s:git_local_branch(dir) abort 180 | let gitdir = s:git_dir(a:dir) 181 | let head = gitdir . '/HEAD' 182 | if empty(gitdir) || !filereadable(head) 183 | return '' 184 | endif 185 | let branch = matchstr(get(readfile(head), 0, ''), '^ref: refs/heads/\zs.*') 186 | return len(branch) ? branch : 'HEAD' 187 | endfunction 188 | 189 | function! s:git_origin_branch(spec) 190 | if len(a:spec.branch) 191 | return a:spec.branch 192 | endif 193 | 194 | " The file may not be present if this is a local repository 195 | let gitdir = s:git_dir(a:spec.dir) 196 | let origin_head = gitdir.'/refs/remotes/origin/HEAD' 197 | if len(gitdir) && filereadable(origin_head) 198 | return matchstr(get(readfile(origin_head), 0, ''), 199 | \ '^ref: refs/remotes/origin/\zs.*') 200 | endif 201 | 202 | " The command may not return the name of a branch in detached HEAD state 203 | let result = s:lines(s:system('git symbolic-ref --short HEAD', a:spec.dir)) 204 | return v:shell_error ? '' : result[-1] 205 | endfunction 206 | 207 | if s:is_win 208 | function! s:plug_call(fn, ...) 209 | let shellslash = &shellslash 210 | try 211 | set noshellslash 212 | return call(a:fn, a:000) 213 | finally 214 | let &shellslash = shellslash 215 | endtry 216 | endfunction 217 | else 218 | function! s:plug_call(fn, ...) 219 | return call(a:fn, a:000) 220 | endfunction 221 | endif 222 | 223 | function! s:plug_getcwd() 224 | return s:plug_call('getcwd') 225 | endfunction 226 | 227 | function! s:plug_fnamemodify(fname, mods) 228 | return s:plug_call('fnamemodify', a:fname, a:mods) 229 | endfunction 230 | 231 | function! s:plug_expand(fmt) 232 | return s:plug_call('expand', a:fmt, 1) 233 | endfunction 234 | 235 | function! s:plug_tempname() 236 | return s:plug_call('tempname') 237 | endfunction 238 | 239 | function! plug#begin(...) 240 | if a:0 > 0 241 | let home = s:path(s:plug_fnamemodify(s:plug_expand(a:1), ':p')) 242 | elseif exists('g:plug_home') 243 | let home = s:path(g:plug_home) 244 | elseif has('nvim') 245 | let home = stdpath('data') . '/plugged' 246 | elseif !empty(&rtp) 247 | let home = s:path(split(&rtp, ',')[0]) . '/plugged' 248 | else 249 | return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.') 250 | endif 251 | if s:plug_fnamemodify(home, ':t') ==# 'plugin' && s:plug_fnamemodify(home, ':h') ==# s:first_rtp 252 | return s:err('Invalid plug home. '.home.' is a standard Vim runtime path and is not allowed.') 253 | endif 254 | 255 | let g:plug_home = home 256 | let g:plugs = {} 257 | let g:plugs_order = [] 258 | let s:triggers = {} 259 | 260 | call s:define_commands() 261 | return 1 262 | endfunction 263 | 264 | function! s:define_commands() 265 | command! -nargs=+ -bar Plug call plug#() 266 | if !executable('git') 267 | return s:err('`git` executable not found. Most commands will not be available. To suppress this message, prepend `silent!` to `call plug#begin(...)`.') 268 | endif 269 | if has('win32') 270 | \ && &shellslash 271 | \ && (&shell =~# 'cmd\(\.exe\)\?$' || s:is_powershell(&shell)) 272 | return s:err('vim-plug does not support shell, ' . &shell . ', when shellslash is set.') 273 | endif 274 | if !has('nvim') 275 | \ && (has('win32') || has('win32unix')) 276 | \ && !has('multi_byte') 277 | return s:err('Vim needs +multi_byte feature on Windows to run shell commands. Enable +iconv for best results.') 278 | endif 279 | command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install(0, []) 280 | command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update(0, []) 281 | command! -nargs=0 -bar -bang PlugClean call s:clean(0) 282 | command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:esc(s:me) | endif 283 | command! -nargs=0 -bar PlugStatus call s:status() 284 | command! -nargs=0 -bar PlugDiff call s:diff() 285 | command! -nargs=? -bar -bang -complete=file PlugSnapshot call s:snapshot(0, ) 286 | endfunction 287 | 288 | function! s:to_a(v) 289 | return type(a:v) == s:TYPE.list ? a:v : [a:v] 290 | endfunction 291 | 292 | function! s:to_s(v) 293 | return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n" 294 | endfunction 295 | 296 | function! s:glob(from, pattern) 297 | return s:lines(globpath(a:from, a:pattern)) 298 | endfunction 299 | 300 | function! s:source(from, ...) 301 | let found = 0 302 | for pattern in a:000 303 | for vim in s:glob(a:from, pattern) 304 | execute 'source' s:esc(vim) 305 | let found = 1 306 | endfor 307 | endfor 308 | return found 309 | endfunction 310 | 311 | function! s:assoc(dict, key, val) 312 | let a:dict[a:key] = add(get(a:dict, a:key, []), a:val) 313 | endfunction 314 | 315 | function! s:ask(message, ...) 316 | call inputsave() 317 | echohl WarningMsg 318 | let answer = input(a:message.(a:0 ? ' (y/N/a) ' : ' (y/N) ')) 319 | echohl None 320 | call inputrestore() 321 | echo "\r" 322 | return (a:0 && answer =~? '^a') ? 2 : (answer =~? '^y') ? 1 : 0 323 | endfunction 324 | 325 | function! s:ask_no_interrupt(...) 326 | try 327 | return call('s:ask', a:000) 328 | catch 329 | return 0 330 | endtry 331 | endfunction 332 | 333 | function! s:lazy(plug, opt) 334 | return has_key(a:plug, a:opt) && 335 | \ (empty(s:to_a(a:plug[a:opt])) || 336 | \ !isdirectory(a:plug.dir) || 337 | \ len(s:glob(s:rtp(a:plug), 'plugin')) || 338 | \ len(s:glob(s:rtp(a:plug), 'after/plugin'))) 339 | endfunction 340 | 341 | function! plug#end() 342 | if !exists('g:plugs') 343 | return s:err('plug#end() called without calling plug#begin() first') 344 | endif 345 | 346 | if exists('#PlugLOD') 347 | augroup PlugLOD 348 | autocmd! 349 | augroup END 350 | augroup! PlugLOD 351 | endif 352 | let lod = { 'ft': {}, 'map': {}, 'cmd': {} } 353 | 354 | if get(g:, 'did_load_filetypes', 0) 355 | filetype off 356 | endif 357 | for name in g:plugs_order 358 | if !has_key(g:plugs, name) 359 | continue 360 | endif 361 | let plug = g:plugs[name] 362 | if get(s:loaded, name, 0) || !s:lazy(plug, 'on') && !s:lazy(plug, 'for') 363 | let s:loaded[name] = 1 364 | continue 365 | endif 366 | 367 | if has_key(plug, 'on') 368 | let s:triggers[name] = { 'map': [], 'cmd': [] } 369 | for cmd in s:to_a(plug.on) 370 | if cmd =~? '^.\+' 371 | if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i')) 372 | call s:assoc(lod.map, cmd, name) 373 | endif 374 | call add(s:triggers[name].map, cmd) 375 | elseif cmd =~# '^[A-Z]' 376 | let cmd = substitute(cmd, '!*$', '', '') 377 | if exists(':'.cmd) != 2 378 | call s:assoc(lod.cmd, cmd, name) 379 | endif 380 | call add(s:triggers[name].cmd, cmd) 381 | else 382 | call s:err('Invalid `on` option: '.cmd. 383 | \ '. Should start with an uppercase letter or ``.') 384 | endif 385 | endfor 386 | endif 387 | 388 | if has_key(plug, 'for') 389 | let types = s:to_a(plug.for) 390 | if !empty(types) 391 | augroup filetypedetect 392 | call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim') 393 | if has('nvim-0.5.0') 394 | call s:source(s:rtp(plug), 'ftdetect/**/*.lua', 'after/ftdetect/**/*.lua') 395 | endif 396 | augroup END 397 | endif 398 | for type in types 399 | call s:assoc(lod.ft, type, name) 400 | endfor 401 | endif 402 | endfor 403 | 404 | for [cmd, names] in items(lod.cmd) 405 | execute printf( 406 | \ 'command! -nargs=* -range -bang -complete=file %s call s:lod_cmd(%s, "", , , , %s)', 407 | \ cmd, string(cmd), string(names)) 408 | endfor 409 | 410 | for [map, names] in items(lod.map) 411 | for [mode, map_prefix, key_prefix] in 412 | \ [['i', '', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']] 413 | execute printf( 414 | \ '%snoremap %s %s:call lod_map(%s, %s, %s, "%s")', 415 | \ mode, map, map_prefix, string(map), string(names), mode != 'i', key_prefix) 416 | endfor 417 | endfor 418 | 419 | for [ft, names] in items(lod.ft) 420 | augroup PlugLOD 421 | execute printf('autocmd FileType %s call lod_ft(%s, %s)', 422 | \ ft, string(ft), string(names)) 423 | augroup END 424 | endfor 425 | 426 | call s:reorg_rtp() 427 | filetype plugin indent on 428 | if has('vim_starting') 429 | if has('syntax') && !exists('g:syntax_on') 430 | syntax enable 431 | end 432 | else 433 | call s:reload_plugins() 434 | endif 435 | endfunction 436 | 437 | function! s:loaded_names() 438 | return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)') 439 | endfunction 440 | 441 | function! s:load_plugin(spec) 442 | call s:source(s:rtp(a:spec), 'plugin/**/*.vim', 'after/plugin/**/*.vim') 443 | if has('nvim-0.5.0') 444 | call s:source(s:rtp(a:spec), 'plugin/**/*.lua', 'after/plugin/**/*.lua') 445 | endif 446 | endfunction 447 | 448 | function! s:reload_plugins() 449 | for name in s:loaded_names() 450 | call s:load_plugin(g:plugs[name]) 451 | endfor 452 | endfunction 453 | 454 | function! s:trim(str) 455 | return substitute(a:str, '[\/]\+$', '', '') 456 | endfunction 457 | 458 | function! s:version_requirement(val, min) 459 | for idx in range(0, len(a:min) - 1) 460 | let v = get(a:val, idx, 0) 461 | if v < a:min[idx] | return 0 462 | elseif v > a:min[idx] | return 1 463 | endif 464 | endfor 465 | return 1 466 | endfunction 467 | 468 | function! s:git_version_requirement(...) 469 | if !exists('s:git_version') 470 | let s:git_version = map(split(split(s:system(['git', '--version']))[2], '\.'), 'str2nr(v:val)') 471 | endif 472 | return s:version_requirement(s:git_version, a:000) 473 | endfunction 474 | 475 | function! s:progress_opt(base) 476 | return a:base && !s:is_win && 477 | \ s:git_version_requirement(1, 7, 1) ? '--progress' : '' 478 | endfunction 479 | 480 | function! s:rtp(spec) 481 | return s:path(a:spec.dir . get(a:spec, 'rtp', '')) 482 | endfunction 483 | 484 | if s:is_win 485 | function! s:path(path) 486 | return s:trim(substitute(a:path, '/', '\', 'g')) 487 | endfunction 488 | 489 | function! s:dirpath(path) 490 | return s:path(a:path) . '\' 491 | endfunction 492 | 493 | function! s:is_local_plug(repo) 494 | return a:repo =~? '^[a-z]:\|^[%~]' 495 | endfunction 496 | 497 | " Copied from fzf 498 | function! s:wrap_cmds(cmds) 499 | let cmds = [ 500 | \ '@echo off', 501 | \ 'setlocal enabledelayedexpansion'] 502 | \ + (type(a:cmds) == type([]) ? a:cmds : [a:cmds]) 503 | \ + ['endlocal'] 504 | if has('iconv') 505 | if !exists('s:codepage') 506 | let s:codepage = libcallnr('kernel32.dll', 'GetACP', 0) 507 | endif 508 | return map(cmds, printf('iconv(v:val."\r", "%s", "cp%d")', &encoding, s:codepage)) 509 | endif 510 | return map(cmds, 'v:val."\r"') 511 | endfunction 512 | 513 | function! s:batchfile(cmd) 514 | let batchfile = s:plug_tempname().'.bat' 515 | call writefile(s:wrap_cmds(a:cmd), batchfile) 516 | let cmd = plug#shellescape(batchfile, {'shell': &shell, 'script': 0}) 517 | if s:is_powershell(&shell) 518 | let cmd = '& ' . cmd 519 | endif 520 | return [batchfile, cmd] 521 | endfunction 522 | else 523 | function! s:path(path) 524 | return s:trim(a:path) 525 | endfunction 526 | 527 | function! s:dirpath(path) 528 | return substitute(a:path, '[/\\]*$', '/', '') 529 | endfunction 530 | 531 | function! s:is_local_plug(repo) 532 | return a:repo[0] =~ '[/$~]' 533 | endfunction 534 | endif 535 | 536 | function! s:err(msg) 537 | echohl ErrorMsg 538 | echom '[vim-plug] '.a:msg 539 | echohl None 540 | endfunction 541 | 542 | function! s:warn(cmd, msg) 543 | echohl WarningMsg 544 | execute a:cmd 'a:msg' 545 | echohl None 546 | endfunction 547 | 548 | function! s:esc(path) 549 | return escape(a:path, ' ') 550 | endfunction 551 | 552 | function! s:escrtp(path) 553 | return escape(a:path, ' ,') 554 | endfunction 555 | 556 | function! s:remove_rtp() 557 | for name in s:loaded_names() 558 | let rtp = s:rtp(g:plugs[name]) 559 | execute 'set rtp-='.s:escrtp(rtp) 560 | let after = globpath(rtp, 'after') 561 | if isdirectory(after) 562 | execute 'set rtp-='.s:escrtp(after) 563 | endif 564 | endfor 565 | endfunction 566 | 567 | function! s:reorg_rtp() 568 | if !empty(s:first_rtp) 569 | execute 'set rtp-='.s:first_rtp 570 | execute 'set rtp-='.s:last_rtp 571 | endif 572 | 573 | " &rtp is modified from outside 574 | if exists('s:prtp') && s:prtp !=# &rtp 575 | call s:remove_rtp() 576 | unlet! s:middle 577 | endif 578 | 579 | let s:middle = get(s:, 'middle', &rtp) 580 | let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])') 581 | let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), '!empty(v:val)') 582 | let rtp = join(map(rtps, 'escape(v:val, ",")'), ',') 583 | \ . ','.s:middle.',' 584 | \ . join(map(afters, 'escape(v:val, ",")'), ',') 585 | let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g') 586 | let s:prtp = &rtp 587 | 588 | if !empty(s:first_rtp) 589 | execute 'set rtp^='.s:first_rtp 590 | execute 'set rtp+='.s:last_rtp 591 | endif 592 | endfunction 593 | 594 | function! s:doautocmd(...) 595 | if exists('#'.join(a:000, '#')) 596 | execute 'doautocmd' ((v:version > 703 || has('patch442')) ? '' : '') join(a:000) 597 | endif 598 | endfunction 599 | 600 | function! s:dobufread(names) 601 | for name in a:names 602 | let path = s:rtp(g:plugs[name]) 603 | for dir in ['ftdetect', 'ftplugin', 'after/ftdetect', 'after/ftplugin'] 604 | if len(finddir(dir, path)) 605 | if exists('#BufRead') 606 | doautocmd BufRead 607 | endif 608 | return 609 | endif 610 | endfor 611 | endfor 612 | endfunction 613 | 614 | function! plug#load(...) 615 | if a:0 == 0 616 | return s:err('Argument missing: plugin name(s) required') 617 | endif 618 | if !exists('g:plugs') 619 | return s:err('plug#begin was not called') 620 | endif 621 | let names = a:0 == 1 && type(a:1) == s:TYPE.list ? a:1 : a:000 622 | let unknowns = filter(copy(names), '!has_key(g:plugs, v:val)') 623 | if !empty(unknowns) 624 | let s = len(unknowns) > 1 ? 's' : '' 625 | return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', '))) 626 | end 627 | let unloaded = filter(copy(names), '!get(s:loaded, v:val, 0)') 628 | if !empty(unloaded) 629 | for name in unloaded 630 | call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) 631 | endfor 632 | call s:dobufread(unloaded) 633 | return 1 634 | end 635 | return 0 636 | endfunction 637 | 638 | function! s:remove_triggers(name) 639 | if !has_key(s:triggers, a:name) 640 | return 641 | endif 642 | for cmd in s:triggers[a:name].cmd 643 | execute 'silent! delc' cmd 644 | endfor 645 | for map in s:triggers[a:name].map 646 | execute 'silent! unmap' map 647 | execute 'silent! iunmap' map 648 | endfor 649 | call remove(s:triggers, a:name) 650 | endfunction 651 | 652 | function! s:lod(names, types, ...) 653 | for name in a:names 654 | call s:remove_triggers(name) 655 | let s:loaded[name] = 1 656 | endfor 657 | call s:reorg_rtp() 658 | 659 | for name in a:names 660 | let rtp = s:rtp(g:plugs[name]) 661 | for dir in a:types 662 | call s:source(rtp, dir.'/**/*.vim') 663 | if has('nvim-0.5.0') " see neovim#14686 664 | call s:source(rtp, dir.'/**/*.lua') 665 | endif 666 | endfor 667 | if a:0 668 | if !s:source(rtp, a:1) && !empty(s:glob(rtp, a:2)) 669 | execute 'runtime' a:1 670 | endif 671 | call s:source(rtp, a:2) 672 | endif 673 | call s:doautocmd('User', name) 674 | endfor 675 | endfunction 676 | 677 | function! s:lod_ft(pat, names) 678 | let syn = 'syntax/'.a:pat.'.vim' 679 | call s:lod(a:names, ['plugin', 'after/plugin'], syn, 'after/'.syn) 680 | execute 'autocmd! PlugLOD FileType' a:pat 681 | call s:doautocmd('filetypeplugin', 'FileType') 682 | call s:doautocmd('filetypeindent', 'FileType') 683 | endfunction 684 | 685 | function! s:lod_cmd(cmd, bang, l1, l2, args, names) 686 | call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) 687 | call s:dobufread(a:names) 688 | execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args) 689 | endfunction 690 | 691 | function! s:lod_map(map, names, with_prefix, prefix) 692 | call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) 693 | call s:dobufread(a:names) 694 | let extra = '' 695 | while 1 696 | let c = getchar(0) 697 | if c == 0 698 | break 699 | endif 700 | let extra .= nr2char(c) 701 | endwhile 702 | 703 | if a:with_prefix 704 | let prefix = v:count ? v:count : '' 705 | let prefix .= '"'.v:register.a:prefix 706 | if mode(1) == 'no' 707 | if v:operator == 'c' 708 | let prefix = "\" . prefix 709 | endif 710 | let prefix .= v:operator 711 | endif 712 | call feedkeys(prefix, 'n') 713 | endif 714 | call feedkeys(substitute(a:map, '^', "\", '') . extra) 715 | endfunction 716 | 717 | function! plug#(repo, ...) 718 | if a:0 > 1 719 | return s:err('Invalid number of arguments (1..2)') 720 | endif 721 | 722 | try 723 | let repo = s:trim(a:repo) 724 | let opts = a:0 == 1 ? s:parse_options(a:1) : s:base_spec 725 | let name = get(opts, 'as', s:plug_fnamemodify(repo, ':t:s?\.git$??')) 726 | let spec = extend(s:infer_properties(name, repo), opts) 727 | if !has_key(g:plugs, name) 728 | call add(g:plugs_order, name) 729 | endif 730 | let g:plugs[name] = spec 731 | let s:loaded[name] = get(s:loaded, name, 0) 732 | catch 733 | return s:err(repo . ' ' . v:exception) 734 | endtry 735 | endfunction 736 | 737 | function! s:parse_options(arg) 738 | let opts = copy(s:base_spec) 739 | let type = type(a:arg) 740 | let opt_errfmt = 'Invalid argument for "%s" option of :Plug (expected: %s)' 741 | if type == s:TYPE.string 742 | if empty(a:arg) 743 | throw printf(opt_errfmt, 'tag', 'string') 744 | endif 745 | let opts.tag = a:arg 746 | elseif type == s:TYPE.dict 747 | for opt in ['branch', 'tag', 'commit', 'rtp', 'dir', 'as'] 748 | if has_key(a:arg, opt) 749 | \ && (type(a:arg[opt]) != s:TYPE.string || empty(a:arg[opt])) 750 | throw printf(opt_errfmt, opt, 'string') 751 | endif 752 | endfor 753 | for opt in ['on', 'for'] 754 | if has_key(a:arg, opt) 755 | \ && type(a:arg[opt]) != s:TYPE.list 756 | \ && (type(a:arg[opt]) != s:TYPE.string || empty(a:arg[opt])) 757 | throw printf(opt_errfmt, opt, 'string or list') 758 | endif 759 | endfor 760 | if has_key(a:arg, 'do') 761 | \ && type(a:arg.do) != s:TYPE.funcref 762 | \ && (type(a:arg.do) != s:TYPE.string || empty(a:arg.do)) 763 | throw printf(opt_errfmt, 'do', 'string or funcref') 764 | endif 765 | call extend(opts, a:arg) 766 | if has_key(opts, 'dir') 767 | let opts.dir = s:dirpath(s:plug_expand(opts.dir)) 768 | endif 769 | else 770 | throw 'Invalid argument type (expected: string or dictionary)' 771 | endif 772 | return opts 773 | endfunction 774 | 775 | function! s:infer_properties(name, repo) 776 | let repo = a:repo 777 | if s:is_local_plug(repo) 778 | return { 'dir': s:dirpath(s:plug_expand(repo)) } 779 | else 780 | if repo =~ ':' 781 | let uri = repo 782 | else 783 | if repo !~ '/' 784 | throw printf('Invalid argument: %s (implicit `vim-scripts'' expansion is deprecated)', repo) 785 | endif 786 | let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git') 787 | let uri = printf(fmt, repo) 788 | endif 789 | return { 'dir': s:dirpath(g:plug_home.'/'.a:name), 'uri': uri } 790 | endif 791 | endfunction 792 | 793 | function! s:install(force, names) 794 | call s:update_impl(0, a:force, a:names) 795 | endfunction 796 | 797 | function! s:update(force, names) 798 | call s:update_impl(1, a:force, a:names) 799 | endfunction 800 | 801 | function! plug#helptags() 802 | if !exists('g:plugs') 803 | return s:err('plug#begin was not called') 804 | endif 805 | for spec in values(g:plugs) 806 | let docd = join([s:rtp(spec), 'doc'], '/') 807 | if isdirectory(docd) 808 | silent! execute 'helptags' s:esc(docd) 809 | endif 810 | endfor 811 | return 1 812 | endfunction 813 | 814 | function! s:syntax() 815 | syntax clear 816 | syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber 817 | syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX 818 | syn match plugNumber /[0-9]\+[0-9.]*/ contained 819 | syn match plugBracket /[[\]]/ contained 820 | syn match plugX /x/ contained 821 | syn match plugDash /^-\{1}\ / 822 | syn match plugPlus /^+/ 823 | syn match plugStar /^*/ 824 | syn match plugMessage /\(^- \)\@<=.*/ 825 | syn match plugName /\(^- \)\@<=[^ ]*:/ 826 | syn match plugSha /\%(: \)\@<=[0-9a-f]\{4,}$/ 827 | syn match plugTag /(tag: [^)]\+)/ 828 | syn match plugInstall /\(^+ \)\@<=[^:]*/ 829 | syn match plugUpdate /\(^* \)\@<=[^:]*/ 830 | syn match plugCommit /^ \X*[0-9a-f]\{7,9} .*/ contains=plugRelDate,plugEdge,plugTag 831 | syn match plugEdge /^ \X\+$/ 832 | syn match plugEdge /^ \X*/ contained nextgroup=plugSha 833 | syn match plugSha /[0-9a-f]\{7,9}/ contained 834 | syn match plugRelDate /([^)]*)$/ contained 835 | syn match plugNotLoaded /(not loaded)$/ 836 | syn match plugError /^x.*/ 837 | syn region plugDeleted start=/^\~ .*/ end=/^\ze\S/ 838 | syn match plugH2 /^.*:\n-\+$/ 839 | syn match plugH2 /^-\{2,}/ 840 | syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean 841 | hi def link plug1 Title 842 | hi def link plug2 Repeat 843 | hi def link plugH2 Type 844 | hi def link plugX Exception 845 | hi def link plugBracket Structure 846 | hi def link plugNumber Number 847 | 848 | hi def link plugDash Special 849 | hi def link plugPlus Constant 850 | hi def link plugStar Boolean 851 | 852 | hi def link plugMessage Function 853 | hi def link plugName Label 854 | hi def link plugInstall Function 855 | hi def link plugUpdate Type 856 | 857 | hi def link plugError Error 858 | hi def link plugDeleted Ignore 859 | hi def link plugRelDate Comment 860 | hi def link plugEdge PreProc 861 | hi def link plugSha Identifier 862 | hi def link plugTag Constant 863 | 864 | hi def link plugNotLoaded Comment 865 | endfunction 866 | 867 | function! s:lpad(str, len) 868 | return a:str . repeat(' ', a:len - len(a:str)) 869 | endfunction 870 | 871 | function! s:lines(msg) 872 | return split(a:msg, "[\r\n]") 873 | endfunction 874 | 875 | function! s:lastline(msg) 876 | return get(s:lines(a:msg), -1, '') 877 | endfunction 878 | 879 | function! s:new_window() 880 | execute get(g:, 'plug_window', '-tabnew') 881 | endfunction 882 | 883 | function! s:plug_window_exists() 884 | let buflist = tabpagebuflist(s:plug_tab) 885 | return !empty(buflist) && index(buflist, s:plug_buf) >= 0 886 | endfunction 887 | 888 | function! s:switch_in() 889 | if !s:plug_window_exists() 890 | return 0 891 | endif 892 | 893 | if winbufnr(0) != s:plug_buf 894 | let s:pos = [tabpagenr(), winnr(), winsaveview()] 895 | execute 'normal!' s:plug_tab.'gt' 896 | let winnr = bufwinnr(s:plug_buf) 897 | execute winnr.'wincmd w' 898 | call add(s:pos, winsaveview()) 899 | else 900 | let s:pos = [winsaveview()] 901 | endif 902 | 903 | setlocal modifiable 904 | return 1 905 | endfunction 906 | 907 | function! s:switch_out(...) 908 | call winrestview(s:pos[-1]) 909 | setlocal nomodifiable 910 | if a:0 > 0 911 | execute a:1 912 | endif 913 | 914 | if len(s:pos) > 1 915 | execute 'normal!' s:pos[0].'gt' 916 | execute s:pos[1] 'wincmd w' 917 | call winrestview(s:pos[2]) 918 | endif 919 | endfunction 920 | 921 | function! s:finish_bindings() 922 | nnoremap R :call retry() 923 | nnoremap D :PlugDiff 924 | nnoremap S :PlugStatus 925 | nnoremap U :call status_update() 926 | xnoremap U :call status_update() 927 | nnoremap ]] :silent! call section('') 928 | nnoremap [[ :silent! call section('b') 929 | endfunction 930 | 931 | function! s:prepare(...) 932 | if empty(s:plug_getcwd()) 933 | throw 'Invalid current working directory. Cannot proceed.' 934 | endif 935 | 936 | for evar in ['$GIT_DIR', '$GIT_WORK_TREE'] 937 | if exists(evar) 938 | throw evar.' detected. Cannot proceed.' 939 | endif 940 | endfor 941 | 942 | call s:job_abort() 943 | if s:switch_in() 944 | if b:plug_preview == 1 945 | pc 946 | endif 947 | enew 948 | else 949 | call s:new_window() 950 | endif 951 | 952 | nnoremap q :call close_pane() 953 | if a:0 == 0 954 | call s:finish_bindings() 955 | endif 956 | let b:plug_preview = -1 957 | let s:plug_tab = tabpagenr() 958 | let s:plug_buf = winbufnr(0) 959 | call s:assign_name() 960 | 961 | for k in ['', 'L', 'o', 'X', 'd', 'dd'] 962 | execute 'silent! unmap ' k 963 | endfor 964 | setlocal buftype=nofile bufhidden=wipe nobuflisted nolist noswapfile nowrap cursorline modifiable nospell 965 | if exists('+colorcolumn') 966 | setlocal colorcolumn= 967 | endif 968 | setf vim-plug 969 | if exists('g:syntax_on') 970 | call s:syntax() 971 | endif 972 | endfunction 973 | 974 | function! s:close_pane() 975 | if b:plug_preview == 1 976 | pc 977 | let b:plug_preview = -1 978 | else 979 | bd 980 | endif 981 | endfunction 982 | 983 | function! s:assign_name() 984 | " Assign buffer name 985 | let prefix = '[Plugins]' 986 | let name = prefix 987 | let idx = 2 988 | while bufexists(name) 989 | let name = printf('%s (%s)', prefix, idx) 990 | let idx = idx + 1 991 | endwhile 992 | silent! execute 'f' fnameescape(name) 993 | endfunction 994 | 995 | function! s:chsh(swap) 996 | let prev = [&shell, &shellcmdflag, &shellredir] 997 | if !s:is_win 998 | set shell=sh 999 | endif 1000 | if a:swap 1001 | if s:is_powershell(&shell) 1002 | let &shellredir = '2>&1 | Out-File -Encoding UTF8 %s' 1003 | elseif &shell =~# 'sh' || &shell =~# 'cmd\(\.exe\)\?$' 1004 | set shellredir=>%s\ 2>&1 1005 | endif 1006 | endif 1007 | return prev 1008 | endfunction 1009 | 1010 | function! s:bang(cmd, ...) 1011 | let batchfile = '' 1012 | try 1013 | let [sh, shellcmdflag, shrd] = s:chsh(a:0) 1014 | " FIXME: Escaping is incomplete. We could use shellescape with eval, 1015 | " but it won't work on Windows. 1016 | let cmd = a:0 ? s:with_cd(a:cmd, a:1) : a:cmd 1017 | if s:is_win 1018 | let [batchfile, cmd] = s:batchfile(cmd) 1019 | endif 1020 | let g:_plug_bang = (s:is_win && has('gui_running') ? 'silent ' : '').'!'.escape(cmd, '#!%') 1021 | execute "normal! :execute g:_plug_bang\\" 1022 | finally 1023 | unlet g:_plug_bang 1024 | let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] 1025 | if s:is_win && filereadable(batchfile) 1026 | call delete(batchfile) 1027 | endif 1028 | endtry 1029 | return v:shell_error ? 'Exit status: ' . v:shell_error : '' 1030 | endfunction 1031 | 1032 | function! s:regress_bar() 1033 | let bar = substitute(getline(2)[1:-2], '.*\zs=', 'x', '') 1034 | call s:progress_bar(2, bar, len(bar)) 1035 | endfunction 1036 | 1037 | function! s:is_updated(dir) 1038 | return !empty(s:system_chomp(['git', 'log', '--pretty=format:%h', 'HEAD...HEAD@{1}'], a:dir)) 1039 | endfunction 1040 | 1041 | function! s:do(pull, force, todo) 1042 | if has('nvim') 1043 | " Reset &rtp to invalidate Neovim cache of loaded Lua modules 1044 | " See https://github.com/junegunn/vim-plug/pull/1157#issuecomment-1809226110 1045 | let &rtp = &rtp 1046 | endif 1047 | for [name, spec] in items(a:todo) 1048 | if !isdirectory(spec.dir) 1049 | continue 1050 | endif 1051 | let installed = has_key(s:update.new, name) 1052 | let updated = installed ? 0 : 1053 | \ (a:pull && index(s:update.errors, name) < 0 && s:is_updated(spec.dir)) 1054 | if a:force || installed || updated 1055 | execute 'cd' s:esc(spec.dir) 1056 | call append(3, '- Post-update hook for '. name .' ... ') 1057 | let error = '' 1058 | let type = type(spec.do) 1059 | if type == s:TYPE.string 1060 | if spec.do[0] == ':' 1061 | if !get(s:loaded, name, 0) 1062 | let s:loaded[name] = 1 1063 | call s:reorg_rtp() 1064 | endif 1065 | call s:load_plugin(spec) 1066 | try 1067 | execute spec.do[1:] 1068 | catch 1069 | let error = v:exception 1070 | endtry 1071 | if !s:plug_window_exists() 1072 | cd - 1073 | throw 'Warning: vim-plug was terminated by the post-update hook of '.name 1074 | endif 1075 | else 1076 | let error = s:bang(spec.do) 1077 | endif 1078 | elseif type == s:TYPE.funcref 1079 | try 1080 | call s:load_plugin(spec) 1081 | let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged') 1082 | call spec.do({ 'name': name, 'status': status, 'force': a:force }) 1083 | catch 1084 | let error = v:exception 1085 | endtry 1086 | else 1087 | let error = 'Invalid hook type' 1088 | endif 1089 | call s:switch_in() 1090 | call setline(4, empty(error) ? (getline(4) . 'OK') 1091 | \ : ('x' . getline(4)[1:] . error)) 1092 | if !empty(error) 1093 | call add(s:update.errors, name) 1094 | call s:regress_bar() 1095 | endif 1096 | cd - 1097 | endif 1098 | endfor 1099 | endfunction 1100 | 1101 | function! s:hash_match(a, b) 1102 | return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0 1103 | endfunction 1104 | 1105 | function! s:checkout(spec) 1106 | let sha = a:spec.commit 1107 | let output = s:git_revision(a:spec.dir) 1108 | let error = 0 1109 | if !empty(output) && !s:hash_match(sha, s:lines(output)[0]) 1110 | let credential_helper = s:git_version_requirement(2) ? '-c credential.helper= ' : '' 1111 | let output = s:system( 1112 | \ 'git '.credential_helper.'fetch --depth 999999 && git checkout '.plug#shellescape(sha).' --', a:spec.dir) 1113 | let error = v:shell_error 1114 | endif 1115 | return [output, error] 1116 | endfunction 1117 | 1118 | function! s:finish(pull) 1119 | let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen')) 1120 | if new_frozen 1121 | let s = new_frozen > 1 ? 's' : '' 1122 | call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s)) 1123 | endif 1124 | call append(3, '- Finishing ... ') | 4 1125 | redraw 1126 | call plug#helptags() 1127 | call plug#end() 1128 | call setline(4, getline(4) . 'Done!') 1129 | redraw 1130 | let msgs = [] 1131 | if !empty(s:update.errors) 1132 | call add(msgs, "Press 'R' to retry.") 1133 | endif 1134 | if a:pull && len(s:update.new) < len(filter(getline(5, '$'), 1135 | \ "v:val =~ '^- ' && v:val !~# 'Already up.to.date'")) 1136 | call add(msgs, "Press 'D' to see the updated changes.") 1137 | endif 1138 | echo join(msgs, ' ') 1139 | call s:finish_bindings() 1140 | endfunction 1141 | 1142 | function! s:retry() 1143 | if empty(s:update.errors) 1144 | return 1145 | endif 1146 | echo 1147 | call s:update_impl(s:update.pull, s:update.force, 1148 | \ extend(copy(s:update.errors), [s:update.threads])) 1149 | endfunction 1150 | 1151 | function! s:is_managed(name) 1152 | return has_key(g:plugs[a:name], 'uri') 1153 | endfunction 1154 | 1155 | function! s:names(...) 1156 | return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)')) 1157 | endfunction 1158 | 1159 | function! s:check_ruby() 1160 | silent! ruby require 'thread'; VIM::command("let g:plug_ruby = '#{RUBY_VERSION}'") 1161 | if !exists('g:plug_ruby') 1162 | redraw! 1163 | return s:warn('echom', 'Warning: Ruby interface is broken') 1164 | endif 1165 | let ruby_version = split(g:plug_ruby, '\.') 1166 | unlet g:plug_ruby 1167 | return s:version_requirement(ruby_version, [1, 8, 7]) 1168 | endfunction 1169 | 1170 | function! s:update_impl(pull, force, args) abort 1171 | let sync = index(a:args, '--sync') >= 0 || has('vim_starting') 1172 | let args = filter(copy(a:args), 'v:val != "--sync"') 1173 | let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ? 1174 | \ remove(args, -1) : get(g:, 'plug_threads', 16) 1175 | 1176 | let managed = filter(deepcopy(g:plugs), 's:is_managed(v:key)') 1177 | let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') : 1178 | \ filter(managed, 'index(args, v:key) >= 0') 1179 | 1180 | if empty(todo) 1181 | return s:warn('echo', 'No plugin to '. (a:pull ? 'update' : 'install')) 1182 | endif 1183 | 1184 | if !s:is_win && s:git_version_requirement(2, 3) 1185 | let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : '' 1186 | let $GIT_TERMINAL_PROMPT = 0 1187 | for plug in values(todo) 1188 | let plug.uri = substitute(plug.uri, 1189 | \ '^https://git::@github\.com', 'https://github.com', '') 1190 | endfor 1191 | endif 1192 | 1193 | if !isdirectory(g:plug_home) 1194 | try 1195 | call mkdir(g:plug_home, 'p') 1196 | catch 1197 | return s:err(printf('Invalid plug directory: %s. '. 1198 | \ 'Try to call plug#begin with a valid directory', g:plug_home)) 1199 | endtry 1200 | endif 1201 | 1202 | if has('nvim') && !exists('*jobwait') && threads > 1 1203 | call s:warn('echom', '[vim-plug] Update Neovim for parallel installer') 1204 | endif 1205 | 1206 | let use_job = s:nvim || s:vim8 1207 | let python = (has('python') || has('python3')) && !use_job 1208 | let ruby = has('ruby') && !use_job && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running')) && threads > 1 && s:check_ruby() 1209 | 1210 | let s:update = { 1211 | \ 'start': reltime(), 1212 | \ 'all': todo, 1213 | \ 'todo': copy(todo), 1214 | \ 'errors': [], 1215 | \ 'pull': a:pull, 1216 | \ 'force': a:force, 1217 | \ 'new': {}, 1218 | \ 'threads': (python || ruby || use_job) ? min([len(todo), threads]) : 1, 1219 | \ 'bar': '', 1220 | \ 'fin': 0 1221 | \ } 1222 | 1223 | call s:prepare(1) 1224 | call append(0, ['', '']) 1225 | normal! 2G 1226 | silent! redraw 1227 | 1228 | " Set remote name, overriding a possible user git config's clone.defaultRemoteName 1229 | let s:clone_opt = ['--origin', 'origin'] 1230 | if get(g:, 'plug_shallow', 1) 1231 | call extend(s:clone_opt, ['--depth', '1']) 1232 | if s:git_version_requirement(1, 7, 10) 1233 | call add(s:clone_opt, '--no-single-branch') 1234 | endif 1235 | endif 1236 | 1237 | if has('win32unix') || has('wsl') 1238 | call extend(s:clone_opt, ['-c', 'core.eol=lf', '-c', 'core.autocrlf=input']) 1239 | endif 1240 | 1241 | let s:submodule_opt = s:git_version_requirement(2, 8) ? ' --jobs='.threads : '' 1242 | 1243 | " Python version requirement (>= 2.7) 1244 | if python && !has('python3') && !ruby && !use_job && s:update.threads > 1 1245 | redir => pyv 1246 | silent python import platform; print platform.python_version() 1247 | redir END 1248 | let python = s:version_requirement( 1249 | \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6]) 1250 | endif 1251 | 1252 | if (python || ruby) && s:update.threads > 1 1253 | try 1254 | let imd = &imd 1255 | if s:mac_gui 1256 | set noimd 1257 | endif 1258 | if ruby 1259 | call s:update_ruby() 1260 | else 1261 | call s:update_python() 1262 | endif 1263 | catch 1264 | let lines = getline(4, '$') 1265 | let printed = {} 1266 | silent! 4,$d _ 1267 | for line in lines 1268 | let name = s:extract_name(line, '.', '') 1269 | if empty(name) || !has_key(printed, name) 1270 | call append('$', line) 1271 | if !empty(name) 1272 | let printed[name] = 1 1273 | if line[0] == 'x' && index(s:update.errors, name) < 0 1274 | call add(s:update.errors, name) 1275 | end 1276 | endif 1277 | endif 1278 | endfor 1279 | finally 1280 | let &imd = imd 1281 | call s:update_finish() 1282 | endtry 1283 | else 1284 | call s:update_vim() 1285 | while use_job && sync 1286 | sleep 100m 1287 | if s:update.fin 1288 | break 1289 | endif 1290 | endwhile 1291 | endif 1292 | endfunction 1293 | 1294 | function! s:log4(name, msg) 1295 | call setline(4, printf('- %s (%s)', a:msg, a:name)) 1296 | redraw 1297 | endfunction 1298 | 1299 | function! s:update_finish() 1300 | if exists('s:git_terminal_prompt') 1301 | let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt 1302 | endif 1303 | if s:switch_in() 1304 | call append(3, '- Updating ...') | 4 1305 | for [name, spec] in items(filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && (s:update.force || s:update.pull || has_key(s:update.new, v:key))')) 1306 | let [pos, _] = s:logpos(name) 1307 | if !pos 1308 | continue 1309 | endif 1310 | let out = '' 1311 | let error = 0 1312 | if has_key(spec, 'commit') 1313 | call s:log4(name, 'Checking out '.spec.commit) 1314 | let [out, error] = s:checkout(spec) 1315 | elseif has_key(spec, 'tag') 1316 | let tag = spec.tag 1317 | if tag =~ '\*' 1318 | let tags = s:lines(s:system('git tag --list '.plug#shellescape(tag).' --sort -version:refname 2>&1', spec.dir)) 1319 | if !v:shell_error && !empty(tags) 1320 | let tag = tags[0] 1321 | call s:log4(name, printf('Latest tag for %s -> %s', spec.tag, tag)) 1322 | call append(3, '') 1323 | endif 1324 | endif 1325 | call s:log4(name, 'Checking out '.tag) 1326 | let out = s:system('git checkout -q '.plug#shellescape(tag).' -- 2>&1', spec.dir) 1327 | let error = v:shell_error 1328 | endif 1329 | if !error && filereadable(spec.dir.'/.gitmodules') && 1330 | \ (s:update.force || has_key(s:update.new, name) || s:is_updated(spec.dir)) 1331 | call s:log4(name, 'Updating submodules. This may take a while.') 1332 | let out .= s:bang('git submodule update --init --recursive'.s:submodule_opt.' 2>&1', spec.dir) 1333 | let error = v:shell_error 1334 | endif 1335 | let msg = s:format_message(v:shell_error ? 'x': '-', name, out) 1336 | if error 1337 | call add(s:update.errors, name) 1338 | call s:regress_bar() 1339 | silent execute pos 'd _' 1340 | call append(4, msg) | 4 1341 | elseif !empty(out) 1342 | call setline(pos, msg[0]) 1343 | endif 1344 | redraw 1345 | endfor 1346 | silent 4 d _ 1347 | try 1348 | call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && has_key(v:val, "do")')) 1349 | catch 1350 | call s:warn('echom', v:exception) 1351 | call s:warn('echo', '') 1352 | return 1353 | endtry 1354 | call s:finish(s:update.pull) 1355 | call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.') 1356 | call s:switch_out('normal! gg') 1357 | endif 1358 | endfunction 1359 | 1360 | function! s:job_abort() 1361 | if (!s:nvim && !s:vim8) || !exists('s:jobs') 1362 | return 1363 | endif 1364 | 1365 | for [name, j] in items(s:jobs) 1366 | if s:nvim 1367 | silent! call jobstop(j.jobid) 1368 | elseif s:vim8 1369 | silent! call job_stop(j.jobid) 1370 | endif 1371 | if j.new 1372 | call s:rm_rf(g:plugs[name].dir) 1373 | endif 1374 | endfor 1375 | let s:jobs = {} 1376 | endfunction 1377 | 1378 | function! s:last_non_empty_line(lines) 1379 | let len = len(a:lines) 1380 | for idx in range(len) 1381 | let line = a:lines[len-idx-1] 1382 | if !empty(line) 1383 | return line 1384 | endif 1385 | endfor 1386 | return '' 1387 | endfunction 1388 | 1389 | function! s:job_out_cb(self, data) abort 1390 | let self = a:self 1391 | let data = remove(self.lines, -1) . a:data 1392 | let lines = map(split(data, "\n", 1), 'split(v:val, "\r", 1)[-1]') 1393 | call extend(self.lines, lines) 1394 | " To reduce the number of buffer updates 1395 | let self.tick = get(self, 'tick', -1) + 1 1396 | if !self.running || self.tick % len(s:jobs) == 0 1397 | let bullet = self.running ? (self.new ? '+' : '*') : (self.error ? 'x' : '-') 1398 | let result = self.error ? join(self.lines, "\n") : s:last_non_empty_line(self.lines) 1399 | if len(result) 1400 | call s:log(bullet, self.name, result) 1401 | endif 1402 | endif 1403 | endfunction 1404 | 1405 | function! s:job_exit_cb(self, data) abort 1406 | let a:self.running = 0 1407 | let a:self.error = a:data != 0 1408 | call s:reap(a:self.name) 1409 | call s:tick() 1410 | endfunction 1411 | 1412 | function! s:job_cb(fn, job, ch, data) 1413 | if !s:plug_window_exists() " plug window closed 1414 | return s:job_abort() 1415 | endif 1416 | call call(a:fn, [a:job, a:data]) 1417 | endfunction 1418 | 1419 | function! s:nvim_cb(job_id, data, event) dict abort 1420 | return (a:event == 'stdout' || a:event == 'stderr') ? 1421 | \ s:job_cb('s:job_out_cb', self, 0, join(a:data, "\n")) : 1422 | \ s:job_cb('s:job_exit_cb', self, 0, a:data) 1423 | endfunction 1424 | 1425 | function! s:spawn(name, spec, queue, opts) 1426 | let job = { 'name': a:name, 'spec': a:spec, 'running': 1, 'error': 0, 'lines': [''], 1427 | \ 'new': get(a:opts, 'new', 0), 'queue': copy(a:queue) } 1428 | let Item = remove(job.queue, 0) 1429 | let argv = type(Item) == s:TYPE.funcref ? call(Item, [a:spec]) : Item 1430 | let s:jobs[a:name] = job 1431 | 1432 | if s:nvim 1433 | if has_key(a:opts, 'dir') 1434 | let job.cwd = a:opts.dir 1435 | endif 1436 | call extend(job, { 1437 | \ 'on_stdout': function('s:nvim_cb'), 1438 | \ 'on_stderr': function('s:nvim_cb'), 1439 | \ 'on_exit': function('s:nvim_cb'), 1440 | \ }) 1441 | let jid = s:plug_call('jobstart', argv, job) 1442 | if jid > 0 1443 | let job.jobid = jid 1444 | else 1445 | let job.running = 0 1446 | let job.error = 1 1447 | let job.lines = [jid < 0 ? argv[0].' is not executable' : 1448 | \ 'Invalid arguments (or job table is full)'] 1449 | endif 1450 | elseif s:vim8 1451 | let cmd = join(map(copy(argv), 'plug#shellescape(v:val, {"script": 0})')) 1452 | if has_key(a:opts, 'dir') 1453 | let cmd = s:with_cd(cmd, a:opts.dir, 0) 1454 | endif 1455 | let argv = s:is_win ? ['cmd', '/s', '/c', '"'.cmd.'"'] : ['sh', '-c', cmd] 1456 | let jid = job_start(s:is_win ? join(argv, ' ') : argv, { 1457 | \ 'out_cb': function('s:job_cb', ['s:job_out_cb', job]), 1458 | \ 'err_cb': function('s:job_cb', ['s:job_out_cb', job]), 1459 | \ 'exit_cb': function('s:job_cb', ['s:job_exit_cb', job]), 1460 | \ 'err_mode': 'raw', 1461 | \ 'out_mode': 'raw' 1462 | \}) 1463 | if job_status(jid) == 'run' 1464 | let job.jobid = jid 1465 | else 1466 | let job.running = 0 1467 | let job.error = 1 1468 | let job.lines = ['Failed to start job'] 1469 | endif 1470 | else 1471 | let job.lines = s:lines(call('s:system', has_key(a:opts, 'dir') ? [argv, a:opts.dir] : [argv])) 1472 | let job.error = v:shell_error != 0 1473 | let job.running = 0 1474 | endif 1475 | endfunction 1476 | 1477 | function! s:reap(name) 1478 | let job = remove(s:jobs, a:name) 1479 | if job.error 1480 | call add(s:update.errors, a:name) 1481 | elseif get(job, 'new', 0) 1482 | let s:update.new[a:name] = 1 1483 | endif 1484 | 1485 | let more = len(get(job, 'queue', [])) 1486 | let bullet = job.error ? 'x' : more ? (job.new ? '+' : '*') : '-' 1487 | let result = job.error ? join(job.lines, "\n") : s:last_non_empty_line(job.lines) 1488 | if len(result) 1489 | call s:log(bullet, a:name, result) 1490 | endif 1491 | 1492 | if !job.error && more 1493 | let job.spec.queue = job.queue 1494 | let s:update.todo[a:name] = job.spec 1495 | else 1496 | let s:update.bar .= job.error ? 'x' : '=' 1497 | call s:bar() 1498 | endif 1499 | endfunction 1500 | 1501 | function! s:bar() 1502 | if s:switch_in() 1503 | let total = len(s:update.all) 1504 | call setline(1, (s:update.pull ? 'Updating' : 'Installing'). 1505 | \ ' plugins ('.len(s:update.bar).'/'.total.')') 1506 | call s:progress_bar(2, s:update.bar, total) 1507 | call s:switch_out() 1508 | endif 1509 | endfunction 1510 | 1511 | function! s:logpos(name) 1512 | let max = line('$') 1513 | for i in range(4, max > 4 ? max : 4) 1514 | if getline(i) =~# '^[-+x*] '.a:name.':' 1515 | for j in range(i + 1, max > 5 ? max : 5) 1516 | if getline(j) !~ '^ ' 1517 | return [i, j - 1] 1518 | endif 1519 | endfor 1520 | return [i, i] 1521 | endif 1522 | endfor 1523 | return [0, 0] 1524 | endfunction 1525 | 1526 | function! s:log(bullet, name, lines) 1527 | if s:switch_in() 1528 | let [b, e] = s:logpos(a:name) 1529 | if b > 0 1530 | silent execute printf('%d,%d d _', b, e) 1531 | if b > winheight('.') 1532 | let b = 4 1533 | endif 1534 | else 1535 | let b = 4 1536 | endif 1537 | " FIXME For some reason, nomodifiable is set after :d in vim8 1538 | setlocal modifiable 1539 | call append(b - 1, s:format_message(a:bullet, a:name, a:lines)) 1540 | call s:switch_out() 1541 | endif 1542 | endfunction 1543 | 1544 | function! s:update_vim() 1545 | let s:jobs = {} 1546 | 1547 | call s:bar() 1548 | call s:tick() 1549 | endfunction 1550 | 1551 | function! s:checkout_command(spec) 1552 | let a:spec.branch = s:git_origin_branch(a:spec) 1553 | return ['git', 'checkout', '-q', a:spec.branch, '--'] 1554 | endfunction 1555 | 1556 | function! s:merge_command(spec) 1557 | let a:spec.branch = s:git_origin_branch(a:spec) 1558 | return ['git', 'merge', '--ff-only', 'origin/'.a:spec.branch] 1559 | endfunction 1560 | 1561 | function! s:tick() 1562 | let pull = s:update.pull 1563 | let prog = s:progress_opt(s:nvim || s:vim8) 1564 | while 1 " Without TCO, Vim stack is bound to explode 1565 | if empty(s:update.todo) 1566 | if empty(s:jobs) && !s:update.fin 1567 | call s:update_finish() 1568 | let s:update.fin = 1 1569 | endif 1570 | return 1571 | endif 1572 | 1573 | let name = keys(s:update.todo)[0] 1574 | let spec = remove(s:update.todo, name) 1575 | let queue = get(spec, 'queue', []) 1576 | let new = empty(globpath(spec.dir, '.git', 1)) 1577 | 1578 | if empty(queue) 1579 | call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...') 1580 | redraw 1581 | endif 1582 | 1583 | let has_tag = has_key(spec, 'tag') 1584 | if len(queue) 1585 | call s:spawn(name, spec, queue, { 'dir': spec.dir }) 1586 | elseif !new 1587 | let [error, _] = s:git_validate(spec, 0) 1588 | if empty(error) 1589 | if pull 1590 | let cmd = s:git_version_requirement(2) ? ['git', '-c', 'credential.helper=', 'fetch'] : ['git', 'fetch'] 1591 | if has_tag && !empty(globpath(spec.dir, '.git/shallow')) 1592 | call extend(cmd, ['--depth', '99999999']) 1593 | endif 1594 | if !empty(prog) 1595 | call add(cmd, prog) 1596 | endif 1597 | let queue = [cmd, split('git remote set-head origin -a')] 1598 | if !has_tag && !has_key(spec, 'commit') 1599 | call extend(queue, [function('s:checkout_command'), function('s:merge_command')]) 1600 | endif 1601 | call s:spawn(name, spec, queue, { 'dir': spec.dir }) 1602 | else 1603 | let s:jobs[name] = { 'running': 0, 'lines': ['Already installed'], 'error': 0 } 1604 | endif 1605 | else 1606 | let s:jobs[name] = { 'running': 0, 'lines': s:lines(error), 'error': 1 } 1607 | endif 1608 | else 1609 | let cmd = ['git', 'clone'] 1610 | if !has_tag 1611 | call extend(cmd, s:clone_opt) 1612 | endif 1613 | if !empty(prog) 1614 | call add(cmd, prog) 1615 | endif 1616 | call s:spawn(name, spec, [extend(cmd, [spec.uri, s:trim(spec.dir)]), function('s:checkout_command'), function('s:merge_command')], { 'new': 1 }) 1617 | endif 1618 | 1619 | if !s:jobs[name].running 1620 | call s:reap(name) 1621 | endif 1622 | if len(s:jobs) >= s:update.threads 1623 | break 1624 | endif 1625 | endwhile 1626 | endfunction 1627 | 1628 | function! s:update_python() 1629 | let py_exe = has('python') ? 'python' : 'python3' 1630 | execute py_exe "<< EOF" 1631 | import datetime 1632 | import functools 1633 | import os 1634 | try: 1635 | import queue 1636 | except ImportError: 1637 | import Queue as queue 1638 | import random 1639 | import re 1640 | import shutil 1641 | import signal 1642 | import subprocess 1643 | import tempfile 1644 | import threading as thr 1645 | import time 1646 | import traceback 1647 | import vim 1648 | 1649 | G_NVIM = vim.eval("has('nvim')") == '1' 1650 | G_PULL = vim.eval('s:update.pull') == '1' 1651 | G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1 1652 | G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)')) 1653 | G_CLONE_OPT = ' '.join(vim.eval('s:clone_opt')) 1654 | G_PROGRESS = vim.eval('s:progress_opt(1)') 1655 | G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads')) 1656 | G_STOP = thr.Event() 1657 | G_IS_WIN = vim.eval('s:is_win') == '1' 1658 | 1659 | class PlugError(Exception): 1660 | def __init__(self, msg): 1661 | self.msg = msg 1662 | class CmdTimedOut(PlugError): 1663 | pass 1664 | class CmdFailed(PlugError): 1665 | pass 1666 | class InvalidURI(PlugError): 1667 | pass 1668 | class Action(object): 1669 | INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-'] 1670 | 1671 | class Buffer(object): 1672 | def __init__(self, lock, num_plugs, is_pull): 1673 | self.bar = '' 1674 | self.event = 'Updating' if is_pull else 'Installing' 1675 | self.lock = lock 1676 | self.maxy = int(vim.eval('winheight(".")')) 1677 | self.num_plugs = num_plugs 1678 | 1679 | def __where(self, name): 1680 | """ Find first line with name in current buffer. Return line num. """ 1681 | found, lnum = False, 0 1682 | matcher = re.compile('^[-+x*] {0}:'.format(name)) 1683 | for line in vim.current.buffer: 1684 | if matcher.search(line) is not None: 1685 | found = True 1686 | break 1687 | lnum += 1 1688 | 1689 | if not found: 1690 | lnum = -1 1691 | return lnum 1692 | 1693 | def header(self): 1694 | curbuf = vim.current.buffer 1695 | curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs) 1696 | 1697 | num_spaces = self.num_plugs - len(self.bar) 1698 | curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ') 1699 | 1700 | with self.lock: 1701 | vim.command('normal! 2G') 1702 | vim.command('redraw') 1703 | 1704 | def write(self, action, name, lines): 1705 | first, rest = lines[0], lines[1:] 1706 | msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)] 1707 | msg.extend([' ' + line for line in rest]) 1708 | 1709 | try: 1710 | if action == Action.ERROR: 1711 | self.bar += 'x' 1712 | vim.command("call add(s:update.errors, '{0}')".format(name)) 1713 | elif action == Action.DONE: 1714 | self.bar += '=' 1715 | 1716 | curbuf = vim.current.buffer 1717 | lnum = self.__where(name) 1718 | if lnum != -1: # Found matching line num 1719 | del curbuf[lnum] 1720 | if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]): 1721 | lnum = 3 1722 | else: 1723 | lnum = 3 1724 | curbuf.append(msg, lnum) 1725 | 1726 | self.header() 1727 | except vim.error: 1728 | pass 1729 | 1730 | class Command(object): 1731 | CD = 'cd /d' if G_IS_WIN else 'cd' 1732 | 1733 | def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None): 1734 | self.cmd = cmd 1735 | if cmd_dir: 1736 | self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd) 1737 | self.timeout = timeout 1738 | self.callback = cb if cb else (lambda msg: None) 1739 | self.clean = clean if clean else (lambda: None) 1740 | self.proc = None 1741 | 1742 | @property 1743 | def alive(self): 1744 | """ Returns true only if command still running. """ 1745 | return self.proc and self.proc.poll() is None 1746 | 1747 | def execute(self, ntries=3): 1748 | """ Execute the command with ntries if CmdTimedOut. 1749 | Returns the output of the command if no Exception. 1750 | """ 1751 | attempt, finished, limit = 0, False, self.timeout 1752 | 1753 | while not finished: 1754 | try: 1755 | attempt += 1 1756 | result = self.try_command() 1757 | finished = True 1758 | return result 1759 | except CmdTimedOut: 1760 | if attempt != ntries: 1761 | self.notify_retry() 1762 | self.timeout += limit 1763 | else: 1764 | raise 1765 | 1766 | def notify_retry(self): 1767 | """ Retry required for command, notify user. """ 1768 | for count in range(3, 0, -1): 1769 | if G_STOP.is_set(): 1770 | raise KeyboardInterrupt 1771 | msg = 'Timeout. Will retry in {0} second{1} ...'.format( 1772 | count, 's' if count != 1 else '') 1773 | self.callback([msg]) 1774 | time.sleep(1) 1775 | self.callback(['Retrying ...']) 1776 | 1777 | def try_command(self): 1778 | """ Execute a cmd & poll for callback. Returns list of output. 1779 | Raises CmdFailed -> return code for Popen isn't 0 1780 | Raises CmdTimedOut -> command exceeded timeout without new output 1781 | """ 1782 | first_line = True 1783 | 1784 | try: 1785 | tfile = tempfile.NamedTemporaryFile(mode='w+b') 1786 | preexec_fn = not G_IS_WIN and os.setsid or None 1787 | self.proc = subprocess.Popen(self.cmd, stdout=tfile, 1788 | stderr=subprocess.STDOUT, 1789 | stdin=subprocess.PIPE, shell=True, 1790 | preexec_fn=preexec_fn) 1791 | thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,)) 1792 | thrd.start() 1793 | 1794 | thread_not_started = True 1795 | while thread_not_started: 1796 | try: 1797 | thrd.join(0.1) 1798 | thread_not_started = False 1799 | except RuntimeError: 1800 | pass 1801 | 1802 | while self.alive: 1803 | if G_STOP.is_set(): 1804 | raise KeyboardInterrupt 1805 | 1806 | if first_line or random.random() < G_LOG_PROB: 1807 | first_line = False 1808 | line = '' if G_IS_WIN else nonblock_read(tfile.name) 1809 | if line: 1810 | self.callback([line]) 1811 | 1812 | time_diff = time.time() - os.path.getmtime(tfile.name) 1813 | if time_diff > self.timeout: 1814 | raise CmdTimedOut(['Timeout!']) 1815 | 1816 | thrd.join(0.5) 1817 | 1818 | tfile.seek(0) 1819 | result = [line.decode('utf-8', 'replace').rstrip() for line in tfile] 1820 | 1821 | if self.proc.returncode != 0: 1822 | raise CmdFailed([''] + result) 1823 | 1824 | return result 1825 | except: 1826 | self.terminate() 1827 | raise 1828 | 1829 | def terminate(self): 1830 | """ Terminate process and cleanup. """ 1831 | if self.alive: 1832 | if G_IS_WIN: 1833 | os.kill(self.proc.pid, signal.SIGINT) 1834 | else: 1835 | os.killpg(self.proc.pid, signal.SIGTERM) 1836 | self.clean() 1837 | 1838 | class Plugin(object): 1839 | def __init__(self, name, args, buf_q, lock): 1840 | self.name = name 1841 | self.args = args 1842 | self.buf_q = buf_q 1843 | self.lock = lock 1844 | self.tag = args.get('tag', 0) 1845 | 1846 | def manage(self): 1847 | try: 1848 | if os.path.exists(self.args['dir']): 1849 | self.update() 1850 | else: 1851 | self.install() 1852 | with self.lock: 1853 | thread_vim_command("let s:update.new['{0}'] = 1".format(self.name)) 1854 | except PlugError as exc: 1855 | self.write(Action.ERROR, self.name, exc.msg) 1856 | except KeyboardInterrupt: 1857 | G_STOP.set() 1858 | self.write(Action.ERROR, self.name, ['Interrupted!']) 1859 | except: 1860 | # Any exception except those above print stack trace 1861 | msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip()) 1862 | self.write(Action.ERROR, self.name, msg.split('\n')) 1863 | raise 1864 | 1865 | def install(self): 1866 | target = self.args['dir'] 1867 | if target[-1] == '\\': 1868 | target = target[0:-1] 1869 | 1870 | def clean(target): 1871 | def _clean(): 1872 | try: 1873 | shutil.rmtree(target) 1874 | except OSError: 1875 | pass 1876 | return _clean 1877 | 1878 | self.write(Action.INSTALL, self.name, ['Installing ...']) 1879 | callback = functools.partial(self.write, Action.INSTALL, self.name) 1880 | cmd = 'git clone {0} {1} {2} {3} 2>&1'.format( 1881 | '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'], 1882 | esc(target)) 1883 | com = Command(cmd, None, G_TIMEOUT, callback, clean(target)) 1884 | result = com.execute(G_RETRIES) 1885 | self.write(Action.DONE, self.name, result[-1:]) 1886 | 1887 | def repo_uri(self): 1888 | cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url' 1889 | command = Command(cmd, self.args['dir'], G_TIMEOUT,) 1890 | result = command.execute(G_RETRIES) 1891 | return result[-1] 1892 | 1893 | def update(self): 1894 | actual_uri = self.repo_uri() 1895 | expect_uri = self.args['uri'] 1896 | regex = re.compile(r'^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$') 1897 | ma = regex.match(actual_uri) 1898 | mb = regex.match(expect_uri) 1899 | if ma is None or mb is None or ma.groups() != mb.groups(): 1900 | msg = ['', 1901 | 'Invalid URI: {0}'.format(actual_uri), 1902 | 'Expected {0}'.format(expect_uri), 1903 | 'PlugClean required.'] 1904 | raise InvalidURI(msg) 1905 | 1906 | if G_PULL: 1907 | self.write(Action.UPDATE, self.name, ['Updating ...']) 1908 | callback = functools.partial(self.write, Action.UPDATE, self.name) 1909 | fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else '' 1910 | cmd = 'git fetch {0} {1} 2>&1'.format(fetch_opt, G_PROGRESS) 1911 | com = Command(cmd, self.args['dir'], G_TIMEOUT, callback) 1912 | result = com.execute(G_RETRIES) 1913 | self.write(Action.DONE, self.name, result[-1:]) 1914 | else: 1915 | self.write(Action.DONE, self.name, ['Already installed']) 1916 | 1917 | def write(self, action, name, msg): 1918 | self.buf_q.put((action, name, msg)) 1919 | 1920 | class PlugThread(thr.Thread): 1921 | def __init__(self, tname, args): 1922 | super(PlugThread, self).__init__() 1923 | self.tname = tname 1924 | self.args = args 1925 | 1926 | def run(self): 1927 | thr.current_thread().name = self.tname 1928 | buf_q, work_q, lock = self.args 1929 | 1930 | try: 1931 | while not G_STOP.is_set(): 1932 | name, args = work_q.get_nowait() 1933 | plug = Plugin(name, args, buf_q, lock) 1934 | plug.manage() 1935 | work_q.task_done() 1936 | except queue.Empty: 1937 | pass 1938 | 1939 | class RefreshThread(thr.Thread): 1940 | def __init__(self, lock): 1941 | super(RefreshThread, self).__init__() 1942 | self.lock = lock 1943 | self.running = True 1944 | 1945 | def run(self): 1946 | while self.running: 1947 | with self.lock: 1948 | thread_vim_command('noautocmd normal! a') 1949 | time.sleep(0.33) 1950 | 1951 | def stop(self): 1952 | self.running = False 1953 | 1954 | if G_NVIM: 1955 | def thread_vim_command(cmd): 1956 | vim.session.threadsafe_call(lambda: vim.command(cmd)) 1957 | else: 1958 | def thread_vim_command(cmd): 1959 | vim.command(cmd) 1960 | 1961 | def esc(name): 1962 | return '"' + name.replace('"', '\"') + '"' 1963 | 1964 | def nonblock_read(fname): 1965 | """ Read a file with nonblock flag. Return the last line. """ 1966 | fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK) 1967 | buf = os.read(fread, 100000).decode('utf-8', 'replace') 1968 | os.close(fread) 1969 | 1970 | line = buf.rstrip('\r\n') 1971 | left = max(line.rfind('\r'), line.rfind('\n')) 1972 | if left != -1: 1973 | left += 1 1974 | line = line[left:] 1975 | 1976 | return line 1977 | 1978 | def main(): 1979 | thr.current_thread().name = 'main' 1980 | nthreads = int(vim.eval('s:update.threads')) 1981 | plugs = vim.eval('s:update.todo') 1982 | mac_gui = vim.eval('s:mac_gui') == '1' 1983 | 1984 | lock = thr.Lock() 1985 | buf = Buffer(lock, len(plugs), G_PULL) 1986 | buf_q, work_q = queue.Queue(), queue.Queue() 1987 | for work in plugs.items(): 1988 | work_q.put(work) 1989 | 1990 | start_cnt = thr.active_count() 1991 | for num in range(nthreads): 1992 | tname = 'PlugT-{0:02}'.format(num) 1993 | thread = PlugThread(tname, (buf_q, work_q, lock)) 1994 | thread.start() 1995 | if mac_gui: 1996 | rthread = RefreshThread(lock) 1997 | rthread.start() 1998 | 1999 | while not buf_q.empty() or thr.active_count() != start_cnt: 2000 | try: 2001 | action, name, msg = buf_q.get(True, 0.25) 2002 | buf.write(action, name, ['OK'] if not msg else msg) 2003 | buf_q.task_done() 2004 | except queue.Empty: 2005 | pass 2006 | except KeyboardInterrupt: 2007 | G_STOP.set() 2008 | 2009 | if mac_gui: 2010 | rthread.stop() 2011 | rthread.join() 2012 | 2013 | main() 2014 | EOF 2015 | endfunction 2016 | 2017 | function! s:update_ruby() 2018 | ruby << EOF 2019 | module PlugStream 2020 | SEP = ["\r", "\n", nil] 2021 | def get_line 2022 | buffer = '' 2023 | loop do 2024 | char = readchar rescue return 2025 | if SEP.include? char.chr 2026 | buffer << $/ 2027 | break 2028 | else 2029 | buffer << char 2030 | end 2031 | end 2032 | buffer 2033 | end 2034 | end unless defined?(PlugStream) 2035 | 2036 | def esc arg 2037 | %["#{arg.gsub('"', '\"')}"] 2038 | end 2039 | 2040 | def killall pid 2041 | pids = [pid] 2042 | if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM 2043 | pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil } 2044 | else 2045 | unless `which pgrep 2> /dev/null`.empty? 2046 | children = pids 2047 | until children.empty? 2048 | children = children.map { |pid| 2049 | `pgrep -P #{pid}`.lines.map { |l| l.chomp } 2050 | }.flatten 2051 | pids += children 2052 | end 2053 | end 2054 | pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil } 2055 | end 2056 | end 2057 | 2058 | def compare_git_uri a, b 2059 | regex = %r{^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$} 2060 | regex.match(a).to_a.drop(1) == regex.match(b).to_a.drop(1) 2061 | end 2062 | 2063 | require 'thread' 2064 | require 'fileutils' 2065 | require 'timeout' 2066 | running = true 2067 | iswin = VIM::evaluate('s:is_win').to_i == 1 2068 | pull = VIM::evaluate('s:update.pull').to_i == 1 2069 | base = VIM::evaluate('g:plug_home') 2070 | all = VIM::evaluate('s:update.todo') 2071 | limit = VIM::evaluate('get(g:, "plug_timeout", 60)') 2072 | tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1 2073 | nthr = VIM::evaluate('s:update.threads').to_i 2074 | maxy = VIM::evaluate('winheight(".")').to_i 2075 | vim7 = VIM::evaluate('v:version').to_i <= 703 && RUBY_PLATFORM =~ /darwin/ 2076 | cd = iswin ? 'cd /d' : 'cd' 2077 | tot = VIM::evaluate('len(s:update.todo)') || 0 2078 | bar = '' 2079 | skip = 'Already installed' 2080 | mtx = Mutex.new 2081 | take1 = proc { mtx.synchronize { running && all.shift } } 2082 | logh = proc { 2083 | cnt = bar.length 2084 | $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})" 2085 | $curbuf[2] = '[' + bar.ljust(tot) + ']' 2086 | VIM::command('normal! 2G') 2087 | VIM::command('redraw') 2088 | } 2089 | where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } } 2090 | log = proc { |name, result, type| 2091 | mtx.synchronize do 2092 | ing = ![true, false].include?(type) 2093 | bar += type ? '=' : 'x' unless ing 2094 | b = case type 2095 | when :install then '+' when :update then '*' 2096 | when true, nil then '-' else 2097 | VIM::command("call add(s:update.errors, '#{name}')") 2098 | 'x' 2099 | end 2100 | result = 2101 | if type || type.nil? 2102 | ["#{b} #{name}: #{result.lines.to_a.last || 'OK'}"] 2103 | elsif result =~ /^Interrupted|^Timeout/ 2104 | ["#{b} #{name}: #{result}"] 2105 | else 2106 | ["#{b} #{name}"] + result.lines.map { |l| " " << l } 2107 | end 2108 | if lnum = where.call(name) 2109 | $curbuf.delete lnum 2110 | lnum = 4 if ing && lnum > maxy 2111 | end 2112 | result.each_with_index do |line, offset| 2113 | $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp) 2114 | end 2115 | logh.call 2116 | end 2117 | } 2118 | bt = proc { |cmd, name, type, cleanup| 2119 | tried = timeout = 0 2120 | begin 2121 | tried += 1 2122 | timeout += limit 2123 | fd = nil 2124 | data = '' 2125 | if iswin 2126 | Timeout::timeout(timeout) do 2127 | tmp = VIM::evaluate('tempname()') 2128 | system("(#{cmd}) > #{tmp}") 2129 | data = File.read(tmp).chomp 2130 | File.unlink tmp rescue nil 2131 | end 2132 | else 2133 | fd = IO.popen(cmd).extend(PlugStream) 2134 | first_line = true 2135 | log_prob = 1.0 / nthr 2136 | while line = Timeout::timeout(timeout) { fd.get_line } 2137 | data << line 2138 | log.call name, line.chomp, type if name && (first_line || rand < log_prob) 2139 | first_line = false 2140 | end 2141 | fd.close 2142 | end 2143 | [$? == 0, data.chomp] 2144 | rescue Timeout::Error, Interrupt => e 2145 | if fd && !fd.closed? 2146 | killall fd.pid 2147 | fd.close 2148 | end 2149 | cleanup.call if cleanup 2150 | if e.is_a?(Timeout::Error) && tried < tries 2151 | 3.downto(1) do |countdown| 2152 | s = countdown > 1 ? 's' : '' 2153 | log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type 2154 | sleep 1 2155 | end 2156 | log.call name, 'Retrying ...', type 2157 | retry 2158 | end 2159 | [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"] 2160 | end 2161 | } 2162 | main = Thread.current 2163 | threads = [] 2164 | watcher = Thread.new { 2165 | if vim7 2166 | while VIM::evaluate('getchar(1)') 2167 | sleep 0.1 2168 | end 2169 | else 2170 | require 'io/console' # >= Ruby 1.9 2171 | nil until IO.console.getch == 3.chr 2172 | end 2173 | mtx.synchronize do 2174 | running = false 2175 | threads.each { |t| t.raise Interrupt } unless vim7 2176 | end 2177 | threads.each { |t| t.join rescue nil } 2178 | main.kill 2179 | } 2180 | refresh = Thread.new { 2181 | while true 2182 | mtx.synchronize do 2183 | break unless running 2184 | VIM::command('noautocmd normal! a') 2185 | end 2186 | sleep 0.2 2187 | end 2188 | } if VIM::evaluate('s:mac_gui') == 1 2189 | 2190 | clone_opt = VIM::evaluate('s:clone_opt').join(' ') 2191 | progress = VIM::evaluate('s:progress_opt(1)') 2192 | nthr.times do 2193 | mtx.synchronize do 2194 | threads << Thread.new { 2195 | while pair = take1.call 2196 | name = pair.first 2197 | dir, uri, tag = pair.last.values_at *%w[dir uri tag] 2198 | exists = File.directory? dir 2199 | ok, result = 2200 | if exists 2201 | chdir = "#{cd} #{iswin ? dir : esc(dir)}" 2202 | ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url", nil, nil, nil 2203 | current_uri = data.lines.to_a.last 2204 | if !ret 2205 | if data =~ /^Interrupted|^Timeout/ 2206 | [false, data] 2207 | else 2208 | [false, [data.chomp, "PlugClean required."].join($/)] 2209 | end 2210 | elsif !compare_git_uri(current_uri, uri) 2211 | [false, ["Invalid URI: #{current_uri}", 2212 | "Expected: #{uri}", 2213 | "PlugClean required."].join($/)] 2214 | else 2215 | if pull 2216 | log.call name, 'Updating ...', :update 2217 | fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : '' 2218 | bt.call "#{chdir} && git fetch #{fetch_opt} #{progress} 2>&1", name, :update, nil 2219 | else 2220 | [true, skip] 2221 | end 2222 | end 2223 | else 2224 | d = esc dir.sub(%r{[\\/]+$}, '') 2225 | log.call name, 'Installing ...', :install 2226 | bt.call "git clone #{clone_opt unless tag} #{progress} #{uri} #{d} 2>&1", name, :install, proc { 2227 | FileUtils.rm_rf dir 2228 | } 2229 | end 2230 | mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok 2231 | log.call name, result, ok 2232 | end 2233 | } if running 2234 | end 2235 | end 2236 | threads.each { |t| t.join rescue nil } 2237 | logh.call 2238 | refresh.kill if refresh 2239 | watcher.kill 2240 | EOF 2241 | endfunction 2242 | 2243 | function! s:shellesc_cmd(arg, script) 2244 | let escaped = substitute('"'.a:arg.'"', '[&|<>()@^!"]', '^&', 'g') 2245 | return substitute(escaped, '%', (a:script ? '%' : '^') . '&', 'g') 2246 | endfunction 2247 | 2248 | function! s:shellesc_ps1(arg) 2249 | return "'".substitute(escape(a:arg, '\"'), "'", "''", 'g')."'" 2250 | endfunction 2251 | 2252 | function! s:shellesc_sh(arg) 2253 | return "'".substitute(a:arg, "'", "'\\\\''", 'g')."'" 2254 | endfunction 2255 | 2256 | " Escape the shell argument based on the shell. 2257 | " Vim and Neovim's shellescape() are insufficient. 2258 | " 1. shellslash determines whether to use single/double quotes. 2259 | " Double-quote escaping is fragile for cmd.exe. 2260 | " 2. It does not work for powershell. 2261 | " 3. It does not work for *sh shells if the command is executed 2262 | " via cmd.exe (ie. cmd.exe /c sh -c command command_args) 2263 | " 4. It does not support batchfile syntax. 2264 | " 2265 | " Accepts an optional dictionary with the following keys: 2266 | " - shell: same as Vim/Neovim 'shell' option. 2267 | " If unset, fallback to 'cmd.exe' on Windows or 'sh'. 2268 | " - script: If truthy and shell is cmd.exe, escape for batchfile syntax. 2269 | function! plug#shellescape(arg, ...) 2270 | if a:arg =~# '^[A-Za-z0-9_/:.-]\+$' 2271 | return a:arg 2272 | endif 2273 | let opts = a:0 > 0 && type(a:1) == s:TYPE.dict ? a:1 : {} 2274 | let shell = get(opts, 'shell', s:is_win ? 'cmd.exe' : 'sh') 2275 | let script = get(opts, 'script', 1) 2276 | if shell =~# 'cmd\(\.exe\)\?$' 2277 | return s:shellesc_cmd(a:arg, script) 2278 | elseif s:is_powershell(shell) 2279 | return s:shellesc_ps1(a:arg) 2280 | endif 2281 | return s:shellesc_sh(a:arg) 2282 | endfunction 2283 | 2284 | function! s:glob_dir(path) 2285 | return map(filter(s:glob(a:path, '**'), 'isdirectory(v:val)'), 's:dirpath(v:val)') 2286 | endfunction 2287 | 2288 | function! s:progress_bar(line, bar, total) 2289 | call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']') 2290 | endfunction 2291 | 2292 | function! s:compare_git_uri(a, b) 2293 | " See `git help clone' 2294 | " https:// [user@] github.com[:port] / junegunn/vim-plug [.git] 2295 | " [git@] github.com[:port] : junegunn/vim-plug [.git] 2296 | " file:// / junegunn/vim-plug [/] 2297 | " / junegunn/vim-plug [/] 2298 | let pat = '^\%(\w\+://\)\='.'\%([^@/]*@\)\='.'\([^:/]*\%(:[0-9]*\)\=\)'.'[:/]'.'\(.\{-}\)'.'\%(\.git\)\=/\?$' 2299 | let ma = matchlist(a:a, pat) 2300 | let mb = matchlist(a:b, pat) 2301 | return ma[1:2] ==# mb[1:2] 2302 | endfunction 2303 | 2304 | function! s:format_message(bullet, name, message) 2305 | if a:bullet != 'x' 2306 | return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))] 2307 | else 2308 | let lines = map(s:lines(a:message), '" ".v:val') 2309 | return extend([printf('x %s:', a:name)], lines) 2310 | endif 2311 | endfunction 2312 | 2313 | function! s:with_cd(cmd, dir, ...) 2314 | let script = a:0 > 0 ? a:1 : 1 2315 | return printf('cd%s %s && %s', s:is_win ? ' /d' : '', plug#shellescape(a:dir, {'script': script}), a:cmd) 2316 | endfunction 2317 | 2318 | function! s:system(cmd, ...) 2319 | let batchfile = '' 2320 | try 2321 | let [sh, shellcmdflag, shrd] = s:chsh(1) 2322 | if type(a:cmd) == s:TYPE.list 2323 | " Neovim's system() supports list argument to bypass the shell 2324 | " but it cannot set the working directory for the command. 2325 | " Assume that the command does not rely on the shell. 2326 | if has('nvim') && a:0 == 0 2327 | return system(a:cmd) 2328 | endif 2329 | let cmd = join(map(copy(a:cmd), 'plug#shellescape(v:val, {"shell": &shell, "script": 0})')) 2330 | if s:is_powershell(&shell) 2331 | let cmd = '& ' . cmd 2332 | endif 2333 | else 2334 | let cmd = a:cmd 2335 | endif 2336 | if a:0 > 0 2337 | let cmd = s:with_cd(cmd, a:1, type(a:cmd) != s:TYPE.list) 2338 | endif 2339 | if s:is_win && type(a:cmd) != s:TYPE.list 2340 | let [batchfile, cmd] = s:batchfile(cmd) 2341 | endif 2342 | return system(cmd) 2343 | finally 2344 | let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] 2345 | if s:is_win && filereadable(batchfile) 2346 | call delete(batchfile) 2347 | endif 2348 | endtry 2349 | endfunction 2350 | 2351 | function! s:system_chomp(...) 2352 | let ret = call('s:system', a:000) 2353 | return v:shell_error ? '' : substitute(ret, '\n$', '', '') 2354 | endfunction 2355 | 2356 | function! s:git_validate(spec, check_branch) 2357 | let err = '' 2358 | if isdirectory(a:spec.dir) 2359 | let result = [s:git_local_branch(a:spec.dir), s:git_origin_url(a:spec.dir)] 2360 | let remote = result[-1] 2361 | if empty(remote) 2362 | let err = join([remote, 'PlugClean required.'], "\n") 2363 | elseif !s:compare_git_uri(remote, a:spec.uri) 2364 | let err = join(['Invalid URI: '.remote, 2365 | \ 'Expected: '.a:spec.uri, 2366 | \ 'PlugClean required.'], "\n") 2367 | elseif a:check_branch && has_key(a:spec, 'commit') 2368 | let sha = s:git_revision(a:spec.dir) 2369 | if empty(sha) 2370 | let err = join(add(result, 'PlugClean required.'), "\n") 2371 | elseif !s:hash_match(sha, a:spec.commit) 2372 | let err = join([printf('Invalid HEAD (expected: %s, actual: %s)', 2373 | \ a:spec.commit[:6], sha[:6]), 2374 | \ 'PlugUpdate required.'], "\n") 2375 | endif 2376 | elseif a:check_branch 2377 | let current_branch = result[0] 2378 | " Check tag 2379 | let origin_branch = s:git_origin_branch(a:spec) 2380 | if has_key(a:spec, 'tag') 2381 | let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir) 2382 | if a:spec.tag !=# tag && a:spec.tag !~ '\*' 2383 | let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.', 2384 | \ (empty(tag) ? 'N/A' : tag), a:spec.tag) 2385 | endif 2386 | " Check branch 2387 | elseif origin_branch !=# current_branch 2388 | let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.', 2389 | \ current_branch, origin_branch) 2390 | endif 2391 | if empty(err) 2392 | let ahead_behind = split(s:lastline(s:system([ 2393 | \ 'git', 'rev-list', '--count', '--left-right', 2394 | \ printf('HEAD...origin/%s', origin_branch) 2395 | \ ], a:spec.dir)), '\t') 2396 | if v:shell_error || len(ahead_behind) != 2 2397 | let err = "Failed to compare with the origin. The default branch might have changed.\nPlugClean required." 2398 | else 2399 | let [ahead, behind] = ahead_behind 2400 | if ahead && behind 2401 | " Only mention PlugClean if diverged, otherwise it's likely to be 2402 | " pushable (and probably not that messed up). 2403 | let err = printf( 2404 | \ "Diverged from origin/%s (%d commit(s) ahead and %d commit(s) behind!\n" 2405 | \ .'Backup local changes and run PlugClean and PlugUpdate to reinstall it.', origin_branch, ahead, behind) 2406 | elseif ahead 2407 | let err = printf("Ahead of origin/%s by %d commit(s).\n" 2408 | \ .'Cannot update until local changes are pushed.', 2409 | \ origin_branch, ahead) 2410 | endif 2411 | endif 2412 | endif 2413 | endif 2414 | else 2415 | let err = 'Not found' 2416 | endif 2417 | return [err, err =~# 'PlugClean'] 2418 | endfunction 2419 | 2420 | function! s:rm_rf(dir) 2421 | if isdirectory(a:dir) 2422 | return s:system(s:is_win 2423 | \ ? 'rmdir /S /Q '.plug#shellescape(a:dir) 2424 | \ : ['rm', '-rf', a:dir]) 2425 | endif 2426 | endfunction 2427 | 2428 | function! s:clean(force) 2429 | call s:prepare() 2430 | call append(0, 'Searching for invalid plugins in '.g:plug_home) 2431 | call append(1, '') 2432 | 2433 | " List of valid directories 2434 | let dirs = [] 2435 | let errs = {} 2436 | let [cnt, total] = [0, len(g:plugs)] 2437 | for [name, spec] in items(g:plugs) 2438 | if !s:is_managed(name) || get(spec, 'frozen', 0) 2439 | call add(dirs, spec.dir) 2440 | else 2441 | let [err, clean] = s:git_validate(spec, 1) 2442 | if clean 2443 | let errs[spec.dir] = s:lines(err)[0] 2444 | else 2445 | call add(dirs, spec.dir) 2446 | endif 2447 | endif 2448 | let cnt += 1 2449 | call s:progress_bar(2, repeat('=', cnt), total) 2450 | normal! 2G 2451 | redraw 2452 | endfor 2453 | 2454 | let allowed = {} 2455 | for dir in dirs 2456 | let allowed[s:dirpath(s:plug_fnamemodify(dir, ':h:h'))] = 1 2457 | let allowed[dir] = 1 2458 | for child in s:glob_dir(dir) 2459 | let allowed[child] = 1 2460 | endfor 2461 | endfor 2462 | 2463 | let todo = [] 2464 | let found = sort(s:glob_dir(g:plug_home)) 2465 | while !empty(found) 2466 | let f = remove(found, 0) 2467 | if !has_key(allowed, f) && isdirectory(f) 2468 | call add(todo, f) 2469 | call append(line('$'), '- ' . f) 2470 | if has_key(errs, f) 2471 | call append(line('$'), ' ' . errs[f]) 2472 | endif 2473 | let found = filter(found, 'stridx(v:val, f) != 0') 2474 | end 2475 | endwhile 2476 | 2477 | 4 2478 | redraw 2479 | if empty(todo) 2480 | call append(line('$'), 'Already clean.') 2481 | else 2482 | let s:clean_count = 0 2483 | call append(3, ['Directories to delete:', '']) 2484 | redraw! 2485 | if a:force || s:ask_no_interrupt('Delete all directories?') 2486 | call s:delete([6, line('$')], 1) 2487 | else 2488 | call setline(4, 'Cancelled.') 2489 | nnoremap d :set opfunc=delete_opg@ 2490 | nmap dd d_ 2491 | xnoremap d :call delete_op(visualmode(), 1) 2492 | echo 'Delete the lines (d{motion}) to delete the corresponding directories' 2493 | endif 2494 | endif 2495 | 4 2496 | setlocal nomodifiable 2497 | endfunction 2498 | 2499 | function! s:delete_op(type, ...) 2500 | call s:delete(a:0 ? [line("'<"), line("'>")] : [line("'["), line("']")], 0) 2501 | endfunction 2502 | 2503 | function! s:delete(range, force) 2504 | let [l1, l2] = a:range 2505 | let force = a:force 2506 | let err_count = 0 2507 | while l1 <= l2 2508 | let line = getline(l1) 2509 | if line =~ '^- ' && isdirectory(line[2:]) 2510 | execute l1 2511 | redraw! 2512 | let answer = force ? 1 : s:ask('Delete '.line[2:].'?', 1) 2513 | let force = force || answer > 1 2514 | if answer 2515 | let err = s:rm_rf(line[2:]) 2516 | setlocal modifiable 2517 | if empty(err) 2518 | call setline(l1, '~'.line[1:]) 2519 | let s:clean_count += 1 2520 | else 2521 | delete _ 2522 | call append(l1 - 1, s:format_message('x', line[1:], err)) 2523 | let l2 += len(s:lines(err)) 2524 | let err_count += 1 2525 | endif 2526 | let msg = printf('Removed %d directories.', s:clean_count) 2527 | if err_count > 0 2528 | let msg .= printf(' Failed to remove %d directories.', err_count) 2529 | endif 2530 | call setline(4, msg) 2531 | setlocal nomodifiable 2532 | endif 2533 | endif 2534 | let l1 += 1 2535 | endwhile 2536 | endfunction 2537 | 2538 | function! s:upgrade() 2539 | echo 'Downloading the latest version of vim-plug' 2540 | redraw 2541 | let tmp = s:plug_tempname() 2542 | let new = tmp . '/plug.vim' 2543 | 2544 | try 2545 | let out = s:system(['git', 'clone', '--depth', '1', s:plug_src, tmp]) 2546 | if v:shell_error 2547 | return s:err('Error upgrading vim-plug: '. out) 2548 | endif 2549 | 2550 | if readfile(s:me) ==# readfile(new) 2551 | echo 'vim-plug is already up-to-date' 2552 | return 0 2553 | else 2554 | call rename(s:me, s:me . '.old') 2555 | call rename(new, s:me) 2556 | unlet g:loaded_plug 2557 | echo 'vim-plug has been upgraded' 2558 | return 1 2559 | endif 2560 | finally 2561 | silent! call s:rm_rf(tmp) 2562 | endtry 2563 | endfunction 2564 | 2565 | function! s:upgrade_specs() 2566 | for spec in values(g:plugs) 2567 | let spec.frozen = get(spec, 'frozen', 0) 2568 | endfor 2569 | endfunction 2570 | 2571 | function! s:status() 2572 | call s:prepare() 2573 | call append(0, 'Checking plugins') 2574 | call append(1, '') 2575 | 2576 | let ecnt = 0 2577 | let unloaded = 0 2578 | let [cnt, total] = [0, len(g:plugs)] 2579 | for [name, spec] in items(g:plugs) 2580 | let is_dir = isdirectory(spec.dir) 2581 | if has_key(spec, 'uri') 2582 | if is_dir 2583 | let [err, _] = s:git_validate(spec, 1) 2584 | let [valid, msg] = [empty(err), empty(err) ? 'OK' : err] 2585 | else 2586 | let [valid, msg] = [0, 'Not found. Try PlugInstall.'] 2587 | endif 2588 | else 2589 | if is_dir 2590 | let [valid, msg] = [1, 'OK'] 2591 | else 2592 | let [valid, msg] = [0, 'Not found.'] 2593 | endif 2594 | endif 2595 | let cnt += 1 2596 | let ecnt += !valid 2597 | " `s:loaded` entry can be missing if PlugUpgraded 2598 | if is_dir && get(s:loaded, name, -1) == 0 2599 | let unloaded = 1 2600 | let msg .= ' (not loaded)' 2601 | endif 2602 | call s:progress_bar(2, repeat('=', cnt), total) 2603 | call append(3, s:format_message(valid ? '-' : 'x', name, msg)) 2604 | normal! 2G 2605 | redraw 2606 | endfor 2607 | call setline(1, 'Finished. '.ecnt.' error(s).') 2608 | normal! gg 2609 | setlocal nomodifiable 2610 | if unloaded 2611 | echo "Press 'L' on each line to load plugin, or 'U' to update" 2612 | nnoremap L :call status_load(line('.')) 2613 | xnoremap L :call status_load(line('.')) 2614 | end 2615 | endfunction 2616 | 2617 | function! s:extract_name(str, prefix, suffix) 2618 | return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$') 2619 | endfunction 2620 | 2621 | function! s:status_load(lnum) 2622 | let line = getline(a:lnum) 2623 | let name = s:extract_name(line, '-', '(not loaded)') 2624 | if !empty(name) 2625 | call plug#load(name) 2626 | setlocal modifiable 2627 | call setline(a:lnum, substitute(line, ' (not loaded)$', '', '')) 2628 | setlocal nomodifiable 2629 | endif 2630 | endfunction 2631 | 2632 | function! s:status_update() range 2633 | let lines = getline(a:firstline, a:lastline) 2634 | let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)') 2635 | if !empty(names) 2636 | echo 2637 | execute 'PlugUpdate' join(names) 2638 | endif 2639 | endfunction 2640 | 2641 | function! s:is_preview_window_open() 2642 | silent! wincmd P 2643 | if &previewwindow 2644 | wincmd p 2645 | return 1 2646 | endif 2647 | endfunction 2648 | 2649 | function! s:find_name(lnum) 2650 | for lnum in reverse(range(1, a:lnum)) 2651 | let line = getline(lnum) 2652 | if empty(line) 2653 | return '' 2654 | endif 2655 | let name = s:extract_name(line, '-', '') 2656 | if !empty(name) 2657 | return name 2658 | endif 2659 | endfor 2660 | return '' 2661 | endfunction 2662 | 2663 | function! s:preview_commit() 2664 | if b:plug_preview < 0 2665 | let b:plug_preview = !s:is_preview_window_open() 2666 | endif 2667 | 2668 | let sha = matchstr(getline('.'), '^ \X*\zs[0-9a-f]\{7,9}') 2669 | if empty(sha) 2670 | let name = matchstr(getline('.'), '^- \zs[^:]*\ze:$') 2671 | if empty(name) 2672 | return 2673 | endif 2674 | let title = 'HEAD@{1}..' 2675 | let command = 'git diff --no-color HEAD@{1}' 2676 | else 2677 | let title = sha 2678 | let command = 'git show --no-color --pretty=medium '.sha 2679 | let name = s:find_name(line('.')) 2680 | endif 2681 | 2682 | if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir) 2683 | return 2684 | endif 2685 | 2686 | if !s:is_preview_window_open() 2687 | execute get(g:, 'plug_pwindow', 'vertical rightbelow new') 2688 | execute 'e' title 2689 | else 2690 | execute 'pedit' title 2691 | wincmd P 2692 | endif 2693 | setlocal previewwindow filetype=git buftype=nofile bufhidden=wipe nobuflisted modifiable 2694 | let batchfile = '' 2695 | try 2696 | let [sh, shellcmdflag, shrd] = s:chsh(1) 2697 | let cmd = 'cd '.plug#shellescape(g:plugs[name].dir).' && '.command 2698 | if s:is_win 2699 | let [batchfile, cmd] = s:batchfile(cmd) 2700 | endif 2701 | execute 'silent %!' cmd 2702 | finally 2703 | let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] 2704 | if s:is_win && filereadable(batchfile) 2705 | call delete(batchfile) 2706 | endif 2707 | endtry 2708 | setlocal nomodifiable 2709 | nnoremap q :q 2710 | wincmd p 2711 | endfunction 2712 | 2713 | function! s:section(flags) 2714 | call search('\(^[x-] \)\@<=[^:]\+:', a:flags) 2715 | endfunction 2716 | 2717 | function! s:format_git_log(line) 2718 | let indent = ' ' 2719 | let tokens = split(a:line, nr2char(1)) 2720 | if len(tokens) != 5 2721 | return indent.substitute(a:line, '\s*$', '', '') 2722 | endif 2723 | let [graph, sha, refs, subject, date] = tokens 2724 | let tag = matchstr(refs, 'tag: [^,)]\+') 2725 | let tag = empty(tag) ? ' ' : ' ('.tag.') ' 2726 | return printf('%s%s%s%s%s (%s)', indent, graph, sha, tag, subject, date) 2727 | endfunction 2728 | 2729 | function! s:append_ul(lnum, text) 2730 | call append(a:lnum, ['', a:text, repeat('-', len(a:text))]) 2731 | endfunction 2732 | 2733 | function! s:diff() 2734 | call s:prepare() 2735 | call append(0, ['Collecting changes ...', '']) 2736 | let cnts = [0, 0] 2737 | let bar = '' 2738 | let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)') 2739 | call s:progress_bar(2, bar, len(total)) 2740 | for origin in [1, 0] 2741 | let plugs = reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))')))) 2742 | if empty(plugs) 2743 | continue 2744 | endif 2745 | call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:') 2746 | for [k, v] in plugs 2747 | let branch = s:git_origin_branch(v) 2748 | if len(branch) 2749 | let range = origin ? '..origin/'.branch : 'HEAD@{1}..' 2750 | let cmd = ['git', 'log', '--graph', '--color=never'] 2751 | if s:git_version_requirement(2, 10, 0) 2752 | call add(cmd, '--no-show-signature') 2753 | endif 2754 | call extend(cmd, ['--pretty=format:%x01%h%x01%d%x01%s%x01%cr', range]) 2755 | if has_key(v, 'rtp') 2756 | call extend(cmd, ['--', v.rtp]) 2757 | endif 2758 | let diff = s:system_chomp(cmd, v.dir) 2759 | if !empty(diff) 2760 | let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : '' 2761 | call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)'))) 2762 | let cnts[origin] += 1 2763 | endif 2764 | endif 2765 | let bar .= '=' 2766 | call s:progress_bar(2, bar, len(total)) 2767 | normal! 2G 2768 | redraw 2769 | endfor 2770 | if !cnts[origin] 2771 | call append(5, ['', 'N/A']) 2772 | endif 2773 | endfor 2774 | call setline(1, printf('%d plugin(s) updated.', cnts[0]) 2775 | \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : '')) 2776 | 2777 | if cnts[0] || cnts[1] 2778 | nnoremap (plug-preview) :silent! call preview_commit() 2779 | if empty(maparg("\", 'n')) 2780 | nmap (plug-preview) 2781 | endif 2782 | if empty(maparg('o', 'n')) 2783 | nmap o (plug-preview) 2784 | endif 2785 | endif 2786 | if cnts[0] 2787 | nnoremap X :call revert() 2788 | echo "Press 'X' on each block to revert the update" 2789 | endif 2790 | normal! gg 2791 | setlocal nomodifiable 2792 | endfunction 2793 | 2794 | function! s:revert() 2795 | if search('^Pending updates', 'bnW') 2796 | return 2797 | endif 2798 | 2799 | let name = s:find_name(line('.')) 2800 | if empty(name) || !has_key(g:plugs, name) || 2801 | \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y' 2802 | return 2803 | endif 2804 | 2805 | call s:system('git reset --hard HEAD@{1} && git checkout '.plug#shellescape(g:plugs[name].branch).' --', g:plugs[name].dir) 2806 | setlocal modifiable 2807 | normal! "_dap 2808 | setlocal nomodifiable 2809 | echo 'Reverted' 2810 | endfunction 2811 | 2812 | function! s:snapshot(force, ...) abort 2813 | call s:prepare() 2814 | setf vim 2815 | call append(0, ['" Generated by vim-plug', 2816 | \ '" '.strftime("%c"), 2817 | \ '" :source this file in vim to restore the snapshot', 2818 | \ '" or execute: vim -S snapshot.vim', 2819 | \ '', '', 'PlugUpdate!']) 2820 | 1 2821 | let anchor = line('$') - 3 2822 | let names = sort(keys(filter(copy(g:plugs), 2823 | \'has_key(v:val, "uri") && isdirectory(v:val.dir)'))) 2824 | for name in reverse(names) 2825 | let sha = has_key(g:plugs[name], 'commit') ? g:plugs[name].commit : s:git_revision(g:plugs[name].dir) 2826 | if !empty(sha) 2827 | call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha)) 2828 | redraw 2829 | endif 2830 | endfor 2831 | 2832 | if a:0 > 0 2833 | let fn = s:plug_expand(a:1) 2834 | if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?')) 2835 | return 2836 | endif 2837 | call writefile(getline(1, '$'), fn) 2838 | echo 'Saved as '.a:1 2839 | silent execute 'e' s:esc(fn) 2840 | setf vim 2841 | endif 2842 | endfunction 2843 | 2844 | function! s:split_rtp() 2845 | return split(&rtp, '\\\@ 1 && line("'\"") <= line("$") | 103 | \ exe "normal! g`\"" | 104 | \ endif 105 | 106 | au VimEnter * RainbowParenthesesActivate 107 | " Round disabled for CMakeLists.txt support... 108 | "au Syntax * RainbowParenthesesLoadRound 109 | au Syntax * RainbowParenthesesLoadSquare 110 | au Syntax * RainbowParenthesesLoadBraces 111 | " au Syntax * RainbowParenthesesLoadChevrons 112 | 113 | set backup 114 | 115 | 116 | --------------------------------------------------------------------------------