plug.vim 32 KB

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