You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2804 lines
81 KiB

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