plug.vim 33 KB

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