plug.vim 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. " vim-plug: Vim plugin manager
  2. " ============================
  3. "
  4. " Download plug.vim and put it in ~/.vim/autoload
  5. "
  6. " mkdir -p ~/.vim/autoload
  7. " curl -fLo ~/.vim/autoload/plug.vim \
  8. " https://raw.github.com/junegunn/vim-plug/master/plug.vim
  9. "
  10. " Edit your .vimrc
  11. "
  12. " call plug#begin('~/.vim/plugged')
  13. "
  14. " " Make sure you use single quotes
  15. " Plug 'junegunn/seoul256.vim'
  16. " Plug 'junegunn/vim-easy-align'
  17. "
  18. " " On-demand loading
  19. " Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
  20. " Plug 'tpope/vim-fireplace', { 'for': 'clojure' }
  21. "
  22. " " Using git URL
  23. " Plug 'https://github.com/junegunn/vim-github-dashboard.git'
  24. "
  25. " " Plugin options
  26. " Plug 'nsf/gocode', { 'tag': 'go.weekly.2012-03-13', 'rtp': 'vim' }
  27. "
  28. " " Plugin outside ~/.vim/plugged with post-update hook
  29. " Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': 'yes \| ./install' }
  30. "
  31. " " Unmanaged plugin (manually installed and updated)
  32. " Plug '~/my-prototype-plugin'
  33. "
  34. " call plug#end()
  35. "
  36. " Then reload .vimrc and :PlugInstall to install plugins.
  37. " Visit https://github.com/junegunn/vim-plug for more information.
  38. "
  39. "
  40. " Copyright (c) 2014 Junegunn Choi
  41. "
  42. " MIT License
  43. "
  44. " Permission is hereby granted, free of charge, to any person obtaining
  45. " a copy of this software and associated documentation files (the
  46. " "Software"), to deal in the Software without restriction, including
  47. " without limitation the rights to use, copy, modify, merge, publish,
  48. " distribute, sublicense, and/or sell copies of the Software, and to
  49. " permit persons to whom the Software is furnished to do so, subject to
  50. " the following conditions:
  51. "
  52. " The above copyright notice and this permission notice shall be
  53. " included in all copies or substantial portions of the Software.
  54. "
  55. " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  56. " EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  57. " MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  58. " NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  59. " LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  60. " OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  61. " WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  62. if exists('g:loaded_plug')
  63. finish
  64. endif
  65. let g:loaded_plug = 1
  66. let s:cpo_save = &cpo
  67. set cpo&vim
  68. let s:plug_source = 'https://raw.github.com/junegunn/vim-plug/master/plug.vim'
  69. let s:plug_buf = -1
  70. let s:mac_gui = has('gui_macvim') && has('gui_running')
  71. let s:is_win = has('win32') || has('win64')
  72. let s:me = expand('<sfile>:p')
  73. let s:base_spec = { 'branch': 'master', 'frozen': 0 }
  74. let s:TYPE = {
  75. \ 'string': type(''),
  76. \ 'list': type([]),
  77. \ 'dict': type({}),
  78. \ 'funcref': type(function('call'))
  79. \ }
  80. function! plug#begin(...)
  81. if a:0 > 0
  82. let home = s:path(fnamemodify(a:1, ':p'))
  83. elseif exists('g:plug_home')
  84. let home = s:path(g:plug_home)
  85. elseif !empty(&rtp)
  86. let home = s:path(split(&rtp, ',')[0]) . '/plugged'
  87. else
  88. return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.')
  89. endif
  90. if !isdirectory(home)
  91. try
  92. call mkdir(home, 'p')
  93. catch
  94. return s:err('Invalid plug directory: '. home)
  95. endtry
  96. endif
  97. if !executable('git')
  98. return s:err('`git` executable not found. vim-plug requires git.')
  99. endif
  100. let g:plug_home = home
  101. let g:plugs = {}
  102. " we want to keep track of the order plugins where registered.
  103. let g:plugs_order = []
  104. command! -nargs=+ -bar Plug call s:add(<args>)
  105. command! -nargs=* -complete=customlist,s:names PlugInstall call s:install(<f-args>)
  106. command! -nargs=* -complete=customlist,s:names PlugUpdate call s:update(<f-args>)
  107. command! -nargs=0 -bang PlugClean call s:clean('<bang>' == '!')
  108. command! -nargs=0 PlugUpgrade if s:upgrade() | call s:upgrade_specs() | execute 'source '. s:me | endif
  109. command! -nargs=0 PlugStatus call s:status()
  110. command! -nargs=0 PlugDiff call s:diff()
  111. return 1
  112. endfunction
  113. function! s:to_a(v)
  114. return type(a:v) == s:TYPE.list ? a:v : [a:v]
  115. endfunction
  116. function! plug#end()
  117. if !exists('g:plugs')
  118. return s:err('Call plug#begin() first')
  119. endif
  120. if exists('#PlugLOD')
  121. augroup PlugLOD
  122. autocmd!
  123. augroup END
  124. augroup! PlugLOD
  125. endif
  126. let lod = {}
  127. filetype off
  128. " we want to make sure the plugin directories are added to rtp in the same
  129. " order that they are registered with the Plug command. since the s:add_rtp
  130. " function uses ^= to add plugin directories to the front of the rtp, we
  131. " need to loop through the plugins in reverse
  132. for name in reverse(copy(g:plugs_order))
  133. let plug = g:plugs[name]
  134. if !has_key(plug, 'on') && !has_key(plug, 'for')
  135. call s:add_rtp(s:rtp(plug))
  136. continue
  137. endif
  138. if has_key(plug, 'on')
  139. let commands = s:to_a(plug.on)
  140. for cmd in commands
  141. if cmd =~ '^<Plug>.\+'
  142. if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i'))
  143. for [mode, map_prefix, key_prefix] in
  144. \ [['i', '<C-O>', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']]
  145. execute printf(
  146. \ '%snoremap <silent> %s %s:<C-U>call <SID>lod_map(%s, %s, "%s")<CR>',
  147. \ mode, cmd, map_prefix, string(cmd), string(name), key_prefix)
  148. endfor
  149. endif
  150. elseif !exists(':'.cmd)
  151. execute printf(
  152. \ 'command! -nargs=* -range -bang %s call s:lod_cmd(%s, "<bang>", <line1>, <line2>, <q-args>, %s)',
  153. \ cmd, string(cmd), string(name))
  154. endif
  155. endfor
  156. endif
  157. if has_key(plug, 'for')
  158. for vim in split(globpath(s:rtp(plug), 'ftdetect/**/*.vim'), '\n')
  159. execute 'source '.vim
  160. endfor
  161. for key in s:to_a(plug.for)
  162. if !has_key(lod, key)
  163. let lod[key] = []
  164. endif
  165. call add(lod[key], name)
  166. endfor
  167. endif
  168. endfor
  169. for [key, names] in items(lod)
  170. augroup PlugLOD
  171. execute printf('autocmd FileType %s call <SID>lod_ft(%s, %s)',
  172. \ key, string(key), string(reverse(names)))
  173. augroup END
  174. endfor
  175. call s:reorg_rtp()
  176. filetype plugin indent on
  177. syntax on
  178. endfunction
  179. function! s:trim(str)
  180. return substitute(a:str, '[\/]\+$', '', '')
  181. endfunction
  182. if s:is_win
  183. function! s:rtp(spec)
  184. return s:path(a:spec.dir . get(a:spec, 'rtp', ''))
  185. endfunction
  186. function! s:path(path)
  187. return s:trim(substitute(a:path, '/', '\', 'g'))
  188. endfunction
  189. function! s:dirpath(path)
  190. return s:path(a:path) . '\'
  191. endfunction
  192. function! s:is_local_plug(repo)
  193. return a:repo =~? '^[a-z]:'
  194. endfunction
  195. else
  196. function! s:rtp(spec)
  197. return s:dirpath(a:spec.dir . get(a:spec, 'rtp', ''))
  198. endfunction
  199. function! s:path(path)
  200. return s:trim(a:path)
  201. endfunction
  202. function! s:dirpath(path)
  203. return substitute(a:path, '[/\\]*$', '/', '')
  204. endfunction
  205. function! s:is_local_plug(repo)
  206. return a:repo[0] =~ '[/$~]'
  207. endfunction
  208. endif
  209. function! s:err(msg)
  210. echohl ErrorMsg
  211. echom a:msg
  212. echohl None
  213. return 0
  214. endfunction
  215. function! s:esc(path)
  216. return substitute(a:path, ' ', '\\ ', 'g')
  217. endfunction
  218. function! s:add_rtp(rtp)
  219. execute 'set rtp^='.s:esc(a:rtp)
  220. let after = globpath(a:rtp, 'after')
  221. if isdirectory(after)
  222. execute 'set rtp+='.s:esc(after)
  223. endif
  224. endfunction
  225. function! s:reorg_rtp()
  226. if !empty(s:first_rtp)
  227. execute 'set rtp-='.s:first_rtp
  228. execute 'set rtp^='.s:first_rtp
  229. endif
  230. if s:last_rtp !=# s:first_rtp
  231. execute 'set rtp-='.s:last_rtp
  232. execute 'set rtp+='.s:last_rtp
  233. endif
  234. endfunction
  235. function! s:lod(plug, types)
  236. let rtp = s:rtp(a:plug)
  237. call s:add_rtp(rtp)
  238. for dir in a:types
  239. for vim in split(globpath(rtp, dir.'/**/*.vim'), '\n')
  240. execute 'source '.vim
  241. endfor
  242. endfor
  243. endfunction
  244. function! s:lod_ft(pat, names)
  245. for name in a:names
  246. call s:lod(g:plugs[name], ['plugin', 'after'])
  247. endfor
  248. call s:reorg_rtp()
  249. execute 'autocmd! PlugLOD FileType ' . a:pat
  250. silent! doautocmd filetypeplugin FileType
  251. endfunction
  252. function! s:lod_cmd(cmd, bang, l1, l2, args, name)
  253. execute 'delc '.a:cmd
  254. call s:lod(g:plugs[a:name], ['plugin', 'ftdetect', 'after'])
  255. call s:reorg_rtp()
  256. execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args)
  257. endfunction
  258. function! s:lod_map(map, name, prefix)
  259. execute 'unmap '.a:map
  260. execute 'iunmap '.a:map
  261. call s:lod(g:plugs[a:name], ['plugin', 'ftdetect', 'after'])
  262. call s:reorg_rtp()
  263. let extra = ''
  264. while 1
  265. let c = getchar(0)
  266. if c == 0
  267. break
  268. endif
  269. let extra .= nr2char(c)
  270. endwhile
  271. call feedkeys(a:prefix . substitute(a:map, '^<Plug>', "\<Plug>", '') . extra)
  272. endfunction
  273. function! s:add(repo, ...)
  274. if a:0 > 1
  275. return s:err('Invalid number of arguments (1..2)')
  276. endif
  277. try
  278. let repo = s:trim(a:repo)
  279. let name = fnamemodify(repo, ':t:s?\.git$??')
  280. let spec = extend(s:infer_properties(name, repo),
  281. \ a:0 == 1 ? s:parse_options(a:1) : copy(s:base_spec))
  282. let g:plugs[name] = spec
  283. let g:plugs_order += [name]
  284. catch
  285. return s:err(v:exception)
  286. endtry
  287. endfunction
  288. function! s:parse_options(arg)
  289. let opts = copy(s:base_spec)
  290. let type = type(a:arg)
  291. if type == s:TYPE.string
  292. let opts.branch = a:arg
  293. elseif type == s:TYPE.dict
  294. call extend(opts, a:arg)
  295. if has_key(opts, 'tag')
  296. let opts.branch = remove(opts, 'tag')
  297. endif
  298. if has_key(opts, 'dir')
  299. let opts.dir = s:dirpath(expand(opts.dir))
  300. endif
  301. else
  302. throw 'Invalid argument type (expected: string or dictionary)'
  303. endif
  304. return opts
  305. endfunction
  306. function! s:infer_properties(name, repo)
  307. let repo = a:repo
  308. if s:is_local_plug(repo)
  309. let properties = { 'dir': s:dirpath(expand(repo)) }
  310. else
  311. if repo =~ ':'
  312. let uri = repo
  313. else
  314. if repo !~ '/'
  315. let repo = 'vim-scripts/'. repo
  316. endif
  317. let uri = 'https://git:@github.com/' . repo . '.git'
  318. endif
  319. let dir = s:dirpath( fnamemodify(join([g:plug_home, a:name], '/'), ':p') )
  320. let properties = { 'dir': dir, 'uri': uri }
  321. endif
  322. return properties
  323. endfunction
  324. function! s:install(...)
  325. call s:update_impl(0, a:000)
  326. endfunction
  327. function! s:update(...)
  328. call s:update_impl(1, a:000)
  329. endfunction
  330. function! s:apply()
  331. for spec in values(g:plugs)
  332. let docd = join([spec.dir, 'doc'], '/')
  333. if isdirectory(docd)
  334. silent! execute 'helptags '. join([spec.dir, 'doc'], '/')
  335. endif
  336. endfor
  337. runtime! plugin/*.vim
  338. runtime! after/**/*.vim
  339. silent! source $MYVIMRC
  340. endfunction
  341. function! s:syntax()
  342. syntax clear
  343. syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber
  344. syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX
  345. syn match plugNumber /[0-9]\+[0-9.]*/ contained
  346. syn match plugBracket /[[\]]/ contained
  347. syn match plugX /x/ contained
  348. syn match plugDash /^-/
  349. syn match plugPlus /^+/
  350. syn match plugStar /^*/
  351. syn match plugMessage /\(^- \)\@<=.*/
  352. syn match plugName /\(^- \)\@<=[^ ]*:/
  353. syn match plugInstall /\(^+ \)\@<=[^:]*/
  354. syn match plugUpdate /\(^* \)\@<=[^:]*/
  355. syn match plugCommit /^ [0-9a-z]\{7} .*/ contains=plugRelDate,plugSha
  356. syn match plugSha /\(^ \)\@<=[0-9a-z]\{7}/ contained
  357. syn match plugRelDate /([^)]*)$/ contained
  358. syn match plugError /^x.*/
  359. syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean
  360. hi def link plug1 Title
  361. hi def link plug2 Repeat
  362. hi def link plugX Exception
  363. hi def link plugBracket Structure
  364. hi def link plugNumber Number
  365. hi def link plugDash Special
  366. hi def link plugPlus Constant
  367. hi def link plugStar Boolean
  368. hi def link plugMessage Function
  369. hi def link plugName Label
  370. hi def link plugInstall Function
  371. hi def link plugUpdate Type
  372. hi def link plugError Error
  373. hi def link plugRelDate Comment
  374. hi def link plugSha Identifier
  375. endfunction
  376. function! s:lpad(str, len)
  377. return a:str . repeat(' ', a:len - len(a:str))
  378. endfunction
  379. function! s:lastline(msg)
  380. let lines = split(a:msg, '\n')
  381. return get(lines, -1, '')
  382. endfunction
  383. function! s:prepare()
  384. if bufexists(s:plug_buf)
  385. let winnr = bufwinnr(s:plug_buf)
  386. if winnr < 0
  387. vertical topleft new
  388. execute 'buffer ' . s:plug_buf
  389. else
  390. execute winnr . 'wincmd w'
  391. endif
  392. silent %d _
  393. else
  394. vertical topleft new
  395. nnoremap <silent> <buffer> q :if b:plug_preview==1<bar>pc<bar>endif<bar>q<cr>
  396. nnoremap <silent> <buffer> R :silent! call <SID>retry()<cr>
  397. nnoremap <silent> <buffer> D :PlugDiff<cr>
  398. nnoremap <silent> <buffer> S :PlugStatus<cr>
  399. nnoremap <silent> <buffer> ]] :silent! call <SID>section('')<cr>
  400. nnoremap <silent> <buffer> [[ :silent! call <SID>section('b')<cr>
  401. let b:plug_preview = -1
  402. let s:plug_buf = winbufnr(0)
  403. call s:assign_name()
  404. endif
  405. silent! unmap <buffer> <cr>
  406. setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap cursorline
  407. setf vim-plug
  408. call s:syntax()
  409. endfunction
  410. function! s:assign_name()
  411. " Assign buffer name
  412. let prefix = '[Plugins]'
  413. let name = prefix
  414. let idx = 2
  415. while bufexists(name)
  416. let name = printf('%s (%s)', prefix, idx)
  417. let idx = idx + 1
  418. endwhile
  419. silent! execute 'f '.fnameescape(name)
  420. endfunction
  421. function! s:do(pull, todo)
  422. for [name, spec] in items(a:todo)
  423. if !isdirectory(spec.dir)
  424. continue
  425. endif
  426. execute 'cd '.s:esc(spec.dir)
  427. let installed = has_key(s:prev_update.new, name)
  428. if installed || (a:pull &&
  429. \ !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"')))
  430. call append(3, '- Post-update hook for '. name .' ... ')
  431. let type = type(spec.do)
  432. if type == s:TYPE.string
  433. try
  434. " FIXME: Escaping is incomplete. We could use shellescape with eval,
  435. " but it won't work on Windows.
  436. let g:_plug_do = '!'.escape(spec.do, '#!%')
  437. execute "normal! :execute g:_plug_do\<cr>\<cr>"
  438. finally
  439. let result = v:shell_error ? ('Exit status: '.v:shell_error) : 'Done!'
  440. unlet g:_plug_do
  441. endtry
  442. elseif type == s:TYPE.funcref
  443. try
  444. call spec.do({ 'name': name, 'status': (installed ? 'installed' : 'updated') })
  445. let result = 'Done!'
  446. catch
  447. let result = 'Error: ' . v:exception
  448. endtry
  449. else
  450. let result = 'Error: Invalid type!'
  451. endif
  452. call setline(4, getline(4) . result)
  453. endif
  454. cd -
  455. endfor
  456. endfunction
  457. function! s:finish(pull)
  458. call append(3, '- Finishing ... ')
  459. redraw
  460. call s:apply()
  461. call s:syntax()
  462. call setline(4, getline(4) . 'Done!')
  463. normal! gg
  464. redraw
  465. let msgs = []
  466. if !empty(s:prev_update.errors)
  467. call add(msgs, "Press 'R' to retry.")
  468. endif
  469. if a:pull
  470. call add(msgs, "Press 'D' to see the updated changes.")
  471. endif
  472. echo join(msgs, ' ')
  473. endfunction
  474. function! s:retry()
  475. if empty(s:prev_update.errors)
  476. return
  477. endif
  478. call s:update_impl(s:prev_update.pull,
  479. \ extend(copy(s:prev_update.errors), [s:prev_update.threads]))
  480. endfunction
  481. function! s:is_managed(name)
  482. return has_key(g:plugs[a:name], 'uri')
  483. endfunction
  484. function! s:names(...)
  485. return filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)')
  486. endfunction
  487. function! s:update_impl(pull, args) abort
  488. let st = reltime()
  489. let args = copy(a:args)
  490. let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
  491. \ remove(args, -1) : get(g:, 'plug_threads', 16)
  492. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  493. let todo = empty(args) ? filter(managed, '!v:val.frozen') :
  494. \ filter(managed, 'index(args, v:key) >= 0')
  495. if empty(todo)
  496. echohl WarningMsg
  497. echo 'No plugin to '. (a:pull ? 'update' : 'install') . '.'
  498. echohl None
  499. return
  500. endif
  501. call s:prepare()
  502. call append(0, a:pull ? 'Updating plugins' : 'Installing plugins')
  503. call append(1, '['. s:lpad('', len(todo)) .']')
  504. normal! 2G
  505. redraw
  506. if !isdirectory(g:plug_home)
  507. call mkdir(g:plug_home, 'p')
  508. endif
  509. let s:prev_update = { 'errors': [], 'pull': a:pull, 'new': {}, 'threads': threads }
  510. if has('ruby') && threads > 1
  511. try
  512. let imd = &imd
  513. if s:mac_gui
  514. set noimd
  515. endif
  516. call s:update_parallel(a:pull, todo, threads)
  517. catch
  518. let lines = getline(4, '$')
  519. let printed = {}
  520. silent 4,$d
  521. for line in lines
  522. let name = get(matchlist(line, '^. \([^:]\+\):'), 1, '')
  523. if empty(name) || !has_key(printed, name)
  524. call append('$', line)
  525. if !empty(name)
  526. let printed[name] = 1
  527. if line[0] == 'x' && index(s:prev_update.errors, name) < 0
  528. call add(s:prev_update.errors, name)
  529. end
  530. endif
  531. endif
  532. endfor
  533. finally
  534. let &imd = imd
  535. endtry
  536. else
  537. call s:update_serial(a:pull, todo)
  538. endif
  539. call s:do(a:pull, filter(copy(todo), 'has_key(v:val, "do")'))
  540. call s:finish(a:pull)
  541. call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(st)))[0] . ' sec.')
  542. endfunction
  543. function! s:update_progress(pull, cnt, bar, total)
  544. call setline(1, (a:pull ? 'Updating' : 'Installing').
  545. \ ' plugins ('.a:cnt.'/'.a:total.')')
  546. call s:progress_bar(2, a:bar, a:total)
  547. normal! 2G
  548. redraw
  549. endfunction
  550. function! s:update_serial(pull, todo)
  551. let base = g:plug_home
  552. let todo = copy(a:todo)
  553. let total = len(todo)
  554. let done = {}
  555. let bar = ''
  556. for [name, spec] in items(todo)
  557. let done[name] = 1
  558. if isdirectory(spec.dir)
  559. execute 'cd '.s:esc(spec.dir)
  560. let [valid, msg] = s:git_valid(spec, 0, 0)
  561. if valid
  562. let result = a:pull ?
  563. \ s:system(
  564. \ printf('git checkout -q %s 2>&1 && git pull origin %s 2>&1 && git submodule update --init --recursive 2>&1',
  565. \ s:shellesc(spec.branch), s:shellesc(spec.branch))) : 'Already installed'
  566. let error = a:pull ? v:shell_error != 0 : 0
  567. else
  568. let result = msg
  569. let error = 1
  570. endif
  571. cd -
  572. else
  573. let result = s:system(
  574. \ printf('git clone --recursive %s -b %s %s 2>&1 && cd %s && git submodule update --init --recursive 2>&1',
  575. \ s:shellesc(spec.uri),
  576. \ s:shellesc(spec.branch),
  577. \ s:shellesc(s:trim(spec.dir)),
  578. \ s:shellesc(spec.dir)))
  579. let error = v:shell_error != 0
  580. if !error | let s:prev_update.new[name] = 1 | endif
  581. endif
  582. let bar .= error ? 'x' : '='
  583. if error
  584. call add(s:prev_update.errors, name)
  585. endif
  586. call append(3, s:format_message(!error, name, result))
  587. call s:update_progress(a:pull, len(done), bar, total)
  588. endfor
  589. endfunction
  590. function! s:update_parallel(pull, todo, threads)
  591. ruby << EOF
  592. module PlugStream
  593. SEP = ["\r", "\n", nil]
  594. def get_line
  595. buffer = ''
  596. loop do
  597. char = readchar rescue return
  598. if SEP.include? char.chr
  599. buffer << $/
  600. break
  601. else
  602. buffer << char
  603. end
  604. end
  605. buffer
  606. end
  607. end unless defined?(PlugStream)
  608. def esc arg
  609. %["#{arg.gsub('"', '\"')}"]
  610. end
  611. def killall pid
  612. pids = [pid]
  613. unless `which pgrep`.empty?
  614. children = pids
  615. until children.empty?
  616. children = children.map { |pid|
  617. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  618. }.flatten
  619. pids += children
  620. end
  621. end
  622. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  623. end
  624. require 'thread'
  625. require 'fileutils'
  626. require 'timeout'
  627. running = true
  628. iswin = VIM::evaluate('s:is_win').to_i == 1
  629. pull = VIM::evaluate('a:pull').to_i == 1
  630. base = VIM::evaluate('g:plug_home')
  631. all = VIM::evaluate('a:todo')
  632. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  633. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  634. nthr = VIM::evaluate('a:threads').to_i
  635. maxy = VIM::evaluate('winheight(".")').to_i
  636. cd = iswin ? 'cd /d' : 'cd'
  637. tot = VIM::evaluate('len(a:todo)') || 0
  638. bar = ''
  639. skip = 'Already installed'
  640. mtx = Mutex.new
  641. take1 = proc { mtx.synchronize { running && all.shift } }
  642. logh = proc {
  643. cnt = bar.length
  644. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  645. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  646. VIM::command('normal! 2G')
  647. VIM::command('redraw') unless iswin
  648. }
  649. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  650. log = proc { |name, result, type|
  651. mtx.synchronize do
  652. ing = ![true, false].include?(type)
  653. bar += type ? '=' : 'x' unless ing
  654. b = case type
  655. when :install then '+' when :update then '*'
  656. when true, nil then '-' else
  657. VIM::command("call add(s:prev_update.errors, '#{name}')")
  658. 'x'
  659. end
  660. result =
  661. if type || type.nil?
  662. ["#{b} #{name}: #{result.lines.to_a.last}"]
  663. elsif result =~ /^Interrupted|^Timeout/
  664. ["#{b} #{name}: #{result}"]
  665. else
  666. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  667. end
  668. if lnum = where.call(name)
  669. $curbuf.delete lnum
  670. lnum = 4 if ing && lnum > maxy
  671. end
  672. result.each_with_index do |line, offset|
  673. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  674. end
  675. logh.call
  676. end
  677. }
  678. bt = proc { |cmd, name, type|
  679. tried = timeout = 0
  680. begin
  681. tried += 1
  682. timeout += limit
  683. fd = nil
  684. data = ''
  685. if iswin
  686. Timeout::timeout(timeout) do
  687. tmp = VIM::evaluate('tempname()')
  688. system("#{cmd} > #{tmp}")
  689. data = File.read(tmp).chomp
  690. File.unlink tmp rescue nil
  691. end
  692. else
  693. fd = IO.popen(cmd).extend(PlugStream)
  694. first_line = true
  695. log_prob = 1.0 / nthr
  696. while line = Timeout::timeout(timeout) { fd.get_line }
  697. data << line
  698. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  699. first_line = false
  700. end
  701. fd.close
  702. end
  703. [$? == 0, data.chomp]
  704. rescue Timeout::Error, Interrupt => e
  705. if fd && !fd.closed?
  706. killall fd.pid
  707. fd.close
  708. end
  709. if e.is_a?(Timeout::Error) && tried < tries
  710. 3.downto(1) do |countdown|
  711. s = countdown > 1 ? 's' : ''
  712. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  713. sleep 1
  714. end
  715. log.call name, 'Retrying ...', type
  716. retry
  717. end
  718. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  719. end
  720. }
  721. main = Thread.current
  722. threads = []
  723. watcher = Thread.new {
  724. while VIM::evaluate('getchar(1)')
  725. sleep 0.1
  726. end
  727. mtx.synchronize do
  728. running = false
  729. threads.each { |t| t.raise Interrupt }
  730. end
  731. threads.each { |t| t.join rescue nil }
  732. main.kill
  733. }
  734. refresh = Thread.new {
  735. while true
  736. mtx.synchronize do
  737. break unless running
  738. VIM::command('noautocmd normal! a')
  739. end
  740. sleep 0.2
  741. end
  742. } if VIM::evaluate('s:mac_gui') == 1
  743. progress = iswin ? '' : '--progress'
  744. [all.length, nthr].min.times do
  745. mtx.synchronize do
  746. threads << Thread.new {
  747. while pair = take1.call
  748. name = pair.first
  749. dir, uri, branch = pair.last.values_at *%w[dir uri branch]
  750. branch = esc branch
  751. subm = "git submodule update --init --recursive 2>&1"
  752. exists = File.directory? dir
  753. ok, result =
  754. if exists
  755. dir = esc dir
  756. ret, data = bt.call "#{cd} #{dir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil
  757. current_uri = data.lines.to_a.last
  758. if !ret
  759. if data =~ /^Interrupted|^Timeout/
  760. [false, data]
  761. else
  762. [false, [data.chomp, "PlugClean required."].join($/)]
  763. end
  764. elsif current_uri.sub(/git:@/, '') != uri.sub(/git:@/, '')
  765. [false, ["Invalid URI: #{current_uri}",
  766. "Expected: #{uri}",
  767. "PlugClean required."].join($/)]
  768. else
  769. if pull
  770. log.call name, 'Updating ...', :update
  771. bt.call "#{cd} #{dir} && git checkout -q #{branch} 2>&1 && (git pull origin #{branch} #{progress} 2>&1 && #{subm})", name, :update
  772. else
  773. [true, skip]
  774. end
  775. end
  776. else
  777. d = esc dir.sub(%r{[\\/]+$}, '')
  778. log.call name, 'Installing ...', :install
  779. bt.call "(git clone #{progress} --recursive #{uri} -b #{branch} #{d} 2>&1 && cd #{esc dir} && #{subm})", name, :install
  780. end
  781. mtx.synchronize { VIM::command("let s:prev_update.new['#{name}'] = 1") } if !exists && ok
  782. log.call name, result, ok
  783. end
  784. } if running
  785. end
  786. end
  787. threads.each { |t| t.join rescue nil }
  788. logh.call
  789. refresh.kill if refresh
  790. watcher.kill
  791. EOF
  792. endfunction
  793. function! s:shellesc(arg)
  794. return '"'.substitute(a:arg, '"', '\\"', 'g').'"'
  795. endfunction
  796. function! s:glob_dir(path)
  797. return map(filter(split(globpath(a:path, '**'), '\n'), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  798. endfunction
  799. function! s:progress_bar(line, bar, total)
  800. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  801. endfunction
  802. function! s:compare_git_uri(a, b)
  803. let a = substitute(a:a, 'git:@', '', '')
  804. let b = substitute(a:b, 'git:@', '', '')
  805. return a ==# b
  806. endfunction
  807. function! s:format_message(ok, name, message)
  808. if a:ok
  809. return [printf('- %s: %s', a:name, s:lastline(a:message))]
  810. else
  811. let lines = map(split(a:message, '\n'), '" ".v:val')
  812. return extend([printf('x %s:', a:name)], lines)
  813. endif
  814. endfunction
  815. function! s:system(cmd)
  816. return system(s:is_win ? '('.a:cmd.')' : a:cmd)
  817. endfunction
  818. function! s:system_chomp(str)
  819. let ret = s:system(a:str)
  820. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  821. endfunction
  822. function! s:git_valid(spec, check_branch, cd)
  823. let ret = 1
  824. let msg = 'OK'
  825. if isdirectory(a:spec.dir)
  826. if a:cd | execute 'cd ' . s:esc(a:spec.dir) | endif
  827. let result = split(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url'), '\n')
  828. let remote = result[-1]
  829. if v:shell_error
  830. let msg = join([remote, 'PlugClean required.'], "\n")
  831. let ret = 0
  832. elseif !s:compare_git_uri(remote, a:spec.uri)
  833. let msg = join(['Invalid URI: '.remote,
  834. \ 'Expected: '.a:spec.uri,
  835. \ 'PlugClean required.'], "\n")
  836. let ret = 0
  837. elseif a:check_branch
  838. let branch = result[0]
  839. if a:spec.branch !=# branch
  840. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1')
  841. if a:spec.branch !=# tag
  842. let msg = printf('Invalid branch/tag: %s (expected: %s). Try PlugUpdate.',
  843. \ (empty(tag) ? branch : tag), a:spec.branch)
  844. let ret = 0
  845. endif
  846. endif
  847. endif
  848. if a:cd | cd - | endif
  849. else
  850. let msg = 'Not found'
  851. let ret = 0
  852. endif
  853. return [ret, msg]
  854. endfunction
  855. function! s:clean(force)
  856. call s:prepare()
  857. call append(0, 'Searching for unused plugins in '.g:plug_home)
  858. call append(1, '')
  859. " List of valid directories
  860. let dirs = []
  861. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  862. let [cnt, total] = [0, len(managed)]
  863. for spec in values(managed)
  864. if s:git_valid(spec, 0, 1)[0]
  865. call add(dirs, spec.dir)
  866. endif
  867. let cnt += 1
  868. call s:progress_bar(2, repeat('=', cnt), total)
  869. normal! 2G
  870. redraw
  871. endfor
  872. let allowed = {}
  873. for dir in dirs
  874. let allowed[dir] = 1
  875. for child in s:glob_dir(dir)
  876. let allowed[child] = 1
  877. endfor
  878. endfor
  879. let todo = []
  880. let found = sort(s:glob_dir(g:plug_home))
  881. while !empty(found)
  882. let f = remove(found, 0)
  883. if !has_key(allowed, f) && isdirectory(f)
  884. call add(todo, f)
  885. call append(line('$'), '- ' . f)
  886. let found = filter(found, 'stridx(v:val, f) != 0')
  887. end
  888. endwhile
  889. normal! G
  890. redraw
  891. if empty(todo)
  892. call append(line('$'), 'Already clean.')
  893. else
  894. call inputsave()
  895. let yes = a:force || (input('Proceed? (Y/N) ') =~? '^y')
  896. call inputrestore()
  897. if yes
  898. for dir in todo
  899. if isdirectory(dir)
  900. call system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(dir))
  901. endif
  902. endfor
  903. call append(line('$'), 'Removed.')
  904. else
  905. call append(line('$'), 'Cancelled.')
  906. endif
  907. endif
  908. normal! G
  909. endfunction
  910. function! s:upgrade()
  911. if executable('curl')
  912. let mee = s:shellesc(s:me)
  913. let new = s:shellesc(s:me . '.new')
  914. echo 'Downloading '. s:plug_source
  915. redraw
  916. let mv = s:is_win ? 'move /Y' : 'mv -f'
  917. let cp = s:is_win ? 'copy /Y' : 'cp -f'
  918. call system(printf(
  919. \ 'curl -fLo %s %s && '.cp.' %s %s.old && '.mv.' %s %s',
  920. \ new, s:plug_source, mee, mee, new, mee))
  921. if v:shell_error == 0
  922. unlet g:loaded_plug
  923. echo 'Downloaded '. s:plug_source
  924. return 1
  925. else
  926. return s:err('Error upgrading vim-plug')
  927. endif
  928. elseif has('ruby')
  929. echo 'Downloading '. s:plug_source
  930. ruby << EOF
  931. require 'open-uri'
  932. require 'fileutils'
  933. me = VIM::evaluate('s:me')
  934. old = me + '.old'
  935. new = me + '.new'
  936. File.open(new, 'w') do |f|
  937. f << open(VIM::evaluate('s:plug_source')).read
  938. end
  939. FileUtils.cp me, old
  940. File.rename new, me
  941. EOF
  942. unlet g:loaded_plug
  943. echo 'Downloaded '. s:plug_source
  944. return 1
  945. else
  946. return s:err('curl executable or ruby support not found')
  947. endif
  948. endfunction
  949. function! s:upgrade_specs()
  950. for spec in values(g:plugs)
  951. let spec.frozen = get(spec, 'frozen', 0)
  952. endfor
  953. endfunction
  954. function! s:status()
  955. call s:prepare()
  956. call append(0, 'Checking plugins')
  957. call append(1, '')
  958. let ecnt = 0
  959. let [cnt, total] = [0, len(g:plugs)]
  960. for [name, spec] in items(g:plugs)
  961. if has_key(spec, 'uri')
  962. if isdirectory(spec.dir)
  963. let [valid, msg] = s:git_valid(spec, 1, 1)
  964. else
  965. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  966. endif
  967. else
  968. if isdirectory(spec.dir)
  969. let [valid, msg] = [1, 'OK']
  970. else
  971. let [valid, msg] = [0, 'Not found.']
  972. endif
  973. endif
  974. let cnt += 1
  975. let ecnt += !valid
  976. call s:progress_bar(2, repeat('=', cnt), total)
  977. call append(3, s:format_message(valid, name, msg))
  978. normal! 2G
  979. redraw
  980. endfor
  981. call setline(1, 'Finished. '.ecnt.' error(s).')
  982. normal! gg
  983. endfunction
  984. function! s:is_preview_window_open()
  985. silent! wincmd P
  986. if &previewwindow
  987. wincmd p
  988. return 1
  989. endif
  990. return 0
  991. endfunction
  992. function! s:preview_commit()
  993. if b:plug_preview < 0
  994. let b:plug_preview = !s:is_preview_window_open()
  995. endif
  996. let sha = matchstr(getline('.'), '\(^ \)\@<=[0-9a-z]\{7}')
  997. if !empty(sha)
  998. let lnum = line('.')
  999. while lnum > 1
  1000. let lnum -= 1
  1001. let line = getline(lnum)
  1002. let name = matchstr(line, '\(^- \)\@<=[^:]\+')
  1003. if !empty(name)
  1004. let dir = g:plugs[name].dir
  1005. if isdirectory(dir)
  1006. execute 'cd '.s:esc(dir)
  1007. execute 'pedit '.sha
  1008. wincmd P
  1009. setlocal filetype=git buftype=nofile nobuflisted
  1010. execute 'silent read !git show '.sha
  1011. normal! ggdd
  1012. wincmd p
  1013. cd -
  1014. endif
  1015. break
  1016. endif
  1017. endwhile
  1018. endif
  1019. endfunction
  1020. function! s:section(flags)
  1021. call search('\(^- \)\@<=.', a:flags)
  1022. endfunction
  1023. function! s:diff()
  1024. call s:prepare()
  1025. call append(0, 'Collecting updated changes ...')
  1026. normal! gg
  1027. redraw
  1028. let cnt = 0
  1029. for [k, v] in items(g:plugs)
  1030. if !isdirectory(v.dir) || !s:is_managed(k)
  1031. continue
  1032. endif
  1033. execute 'cd '.s:esc(v.dir)
  1034. let diff = system('git log --pretty=format:"%h %s (%cr)" "HEAD...HEAD@{1}"')
  1035. if !v:shell_error && !empty(diff)
  1036. call append(1, '')
  1037. call append(2, '- '.k.':')
  1038. call append(3, map(split(diff, '\n'), '" ". v:val'))
  1039. let cnt += 1
  1040. normal! gg
  1041. redraw
  1042. endif
  1043. cd -
  1044. endfor
  1045. call setline(1, cnt == 0 ? 'No updates.' : 'Last update:')
  1046. nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
  1047. normal! gg
  1048. endfunction
  1049. let s:first_rtp = s:esc(get(split(&rtp, ','), 0, ''))
  1050. let s:last_rtp = s:esc(get(split(&rtp, ','), -1, ''))
  1051. let &cpo = s:cpo_save
  1052. unlet s:cpo_save