plug.vim 32 KB

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