plug.vim 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. execute 'cd '.s:esc(spec.dir)
  405. if has_key(s:prev_update.new, name) || (a:pull &&
  406. \ !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"')))
  407. call append(3, '- Post-update hook for '. name .' ... ')
  408. let type = type(spec.do)
  409. if type == 1 " String
  410. call system(spec.do)
  411. let result = v:shell_error ? ('Exit status: '.v:shell_error) : 'Done!'
  412. elseif type == 2 " Funcref
  413. try
  414. call spec.do()
  415. let result = 'Done!'
  416. catch
  417. let result = 'Error: ' . v:exception
  418. endtry
  419. else
  420. let result = 'Error: Invalid type!'
  421. endif
  422. call setline(4, getline(4) . result)
  423. endif
  424. cd -
  425. endfor
  426. endfunction
  427. function! s:finish(pull)
  428. call append(3, '- Finishing ... ')
  429. redraw
  430. call s:apply()
  431. call s:syntax()
  432. call setline(4, getline(4) . 'Done!')
  433. normal! gg
  434. redraw
  435. let msgs = []
  436. if !empty(s:prev_update.errors)
  437. call add(msgs, "Press 'R' to retry.")
  438. endif
  439. if a:pull
  440. call add(msgs, "Press 'D' to see the updated changes.")
  441. endif
  442. echo join(msgs, ' ')
  443. endfunction
  444. function! s:retry()
  445. if empty(s:prev_update.errors)
  446. return
  447. endif
  448. call s:update_impl(s:prev_update.pull,
  449. \ extend(copy(s:prev_update.errors), [s:prev_update.threads]))
  450. endfunction
  451. function! s:is_managed(name)
  452. return has_key(g:plugs[a:name], 'uri')
  453. endfunction
  454. function! s:names(...)
  455. return filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)')
  456. endfunction
  457. function! s:update_impl(pull, args) abort
  458. let args = copy(a:args)
  459. let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
  460. \ remove(args, -1) : get(g:, 'plug_threads', 16)
  461. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  462. let todo = empty(args) ? filter(managed, '!get(v:val, "frozen", 0)') :
  463. \ filter(managed, 'index(args, v:key) >= 0')
  464. if empty(todo)
  465. echohl WarningMsg
  466. echo 'No plugin to '. (a:pull ? 'update' : 'install') . '.'
  467. echohl None
  468. return
  469. endif
  470. call s:prepare()
  471. call append(0, a:pull ? 'Updating plugins' : 'Installing plugins')
  472. call append(1, '['. s:lpad('', len(todo)) .']')
  473. normal! 2G
  474. redraw
  475. if !isdirectory(g:plug_home)
  476. call mkdir(g:plug_home, 'p')
  477. endif
  478. let len = len(g:plugs)
  479. let s:prev_update = { 'errors': [], 'pull': a:pull, 'new': {}, 'threads': threads }
  480. if has('ruby') && threads > 1
  481. try
  482. let imd = &imd
  483. if s:mac_gui
  484. set noimd
  485. endif
  486. call s:update_parallel(a:pull, todo, threads)
  487. catch
  488. let lines = getline(4, '$')
  489. let printed = {}
  490. silent 4,$d
  491. for line in lines
  492. let name = get(matchlist(line, '^. \([^:]\+\):'), 1, '')
  493. if empty(name) || !has_key(printed, name)
  494. call append('$', line)
  495. if !empty(name)
  496. let printed[name] = 1
  497. if line[0] == 'x' && index(s:prev_update.errors, name) < 0
  498. call add(s:prev_update.errors, name)
  499. end
  500. endif
  501. endif
  502. endfor
  503. finally
  504. let &imd = imd
  505. endtry
  506. else
  507. call s:update_serial(a:pull, todo)
  508. endif
  509. call s:do(a:pull, filter(copy(todo), 'has_key(v:val, "do")'))
  510. if len(g:plugs) > len
  511. call plug#end()
  512. endif
  513. call s:finish(a:pull)
  514. endfunction
  515. function! s:extend(names)
  516. let s:extended = {}
  517. try
  518. command! -nargs=+ Plug call s:add(0, <args>)
  519. for name in a:names
  520. let plugfile = globpath(s:rtp(g:plugs[name]), s:plug_file)
  521. if filereadable(plugfile)
  522. execute "source ". s:esc(plugfile)
  523. endif
  524. endfor
  525. finally
  526. command! -nargs=+ Plug call s:add(1, <args>)
  527. endtry
  528. return s:extended
  529. endfunction
  530. function! s:update_progress(pull, cnt, bar, total)
  531. call setline(1, (a:pull ? 'Updating' : 'Installing').
  532. \ " plugins (".a:cnt."/".a:total.")")
  533. call s:progress_bar(2, a:bar, a:total)
  534. normal! 2G
  535. redraw
  536. endfunction
  537. function! s:update_serial(pull, todo)
  538. let st = reltime()
  539. let base = g:plug_home
  540. let todo = copy(a:todo)
  541. let total = len(todo)
  542. let done = {}
  543. let bar = ''
  544. while !empty(todo)
  545. for [name, spec] in items(todo)
  546. let done[name] = 1
  547. if isdirectory(spec.dir)
  548. execute 'cd '.s:esc(spec.dir)
  549. let [valid, msg] = s:git_valid(spec, 0, 0)
  550. if valid
  551. let result = a:pull ?
  552. \ s:system(
  553. \ printf('git checkout -q %s 2>&1 && git pull origin %s 2>&1 && git submodule update --init --recursive 2>&1',
  554. \ s:shellesc(spec.branch), s:shellesc(spec.branch))) : 'Already installed'
  555. let error = a:pull ? v:shell_error != 0 : 0
  556. else
  557. let result = msg
  558. let error = 1
  559. endif
  560. cd -
  561. else
  562. let result = s:system(
  563. \ printf('git clone --recursive %s -b %s %s 2>&1 && cd %s && git submodule update --init --recursive 2>&1',
  564. \ s:shellesc(spec.uri),
  565. \ s:shellesc(spec.branch),
  566. \ s:shellesc(substitute(spec.dir, '[\/]\+$', '', '')),
  567. \ s:shellesc(spec.dir)))
  568. let error = v:shell_error != 0
  569. if !error | let s:prev_update.new[name] = 1 | endif
  570. endif
  571. let bar .= error ? 'x' : '='
  572. if error
  573. call add(s:prev_update.errors, name)
  574. endif
  575. call append(3, s:format_message(!error, name, result))
  576. call s:update_progress(a:pull, len(done), bar, total)
  577. endfor
  578. let extended = s:extend(keys(todo))
  579. if !empty(extended)
  580. let todo = filter(extended, '!has_key(done, v:key)')
  581. let total += len(todo)
  582. call s:update_progress(a:pull, len(done), bar, total)
  583. else
  584. break
  585. endif
  586. endwhile
  587. call setline(1, "Updated. Elapsed time: " . split(reltimestr(reltime(st)))[0] . ' sec.')
  588. endfunction
  589. function! s:update_parallel(pull, todo, threads)
  590. ruby << EOF
  591. module PlugStream
  592. SEP = ["\r", "\n", nil]
  593. def get_line
  594. buffer = ''
  595. loop do
  596. char = readchar rescue return
  597. if SEP.include? char.chr
  598. buffer << $/
  599. break
  600. else
  601. buffer << char
  602. end
  603. end
  604. buffer
  605. end
  606. end unless defined?(PlugStream)
  607. def esc arg
  608. %["#{arg.gsub('"', '\"')}"]
  609. end
  610. require 'set'
  611. require 'thread'
  612. require 'fileutils'
  613. require 'timeout'
  614. running = true
  615. st = Time.now
  616. iswin = VIM::evaluate('s:is_win').to_i == 1
  617. pull = VIM::evaluate('a:pull').to_i == 1
  618. base = VIM::evaluate('g:plug_home')
  619. all = VIM::evaluate('copy(a:todo)')
  620. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  621. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  622. nthr = VIM::evaluate('a:threads').to_i
  623. maxy = VIM::evaluate('winheight(".")').to_i
  624. cd = iswin ? 'cd /d' : 'cd'
  625. tot = VIM::evaluate('len(a:todo)') || 0
  626. bar = ''
  627. skip = 'Already installed'
  628. mtx = Mutex.new
  629. take1 = proc { mtx.synchronize { running && all.shift } }
  630. logh = proc {
  631. cnt = bar.length
  632. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  633. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  634. VIM::command('normal! 2G')
  635. VIM::command('redraw') unless iswin
  636. }
  637. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  638. log = proc { |name, result, type|
  639. mtx.synchronize do
  640. ing = ![true, false].include?(type)
  641. bar += type ? '=' : 'x' unless ing
  642. b = case type
  643. when :install then '+' when :update then '*'
  644. when true, nil then '-' else
  645. VIM::command("call add(s:prev_update.errors, '#{name}')")
  646. 'x'
  647. end
  648. result =
  649. if type || type.nil?
  650. ["#{b} #{name}: #{result.lines.to_a.last}"]
  651. elsif result =~ /^Interrupted|^Timeout/
  652. ["#{b} #{name}: #{result}"]
  653. else
  654. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  655. end
  656. if lnum = where.call(name)
  657. $curbuf.delete lnum
  658. lnum = 4 if ing && lnum > maxy
  659. end
  660. result.each_with_index do |line, offset|
  661. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  662. end
  663. logh.call
  664. end
  665. }
  666. bt = proc { |cmd, name, type|
  667. tried = timeout = 0
  668. begin
  669. tried += 1
  670. timeout += limit
  671. fd = nil
  672. data = ''
  673. if iswin
  674. Timeout::timeout(timeout) do
  675. tmp = VIM::evaluate('tempname()')
  676. system("#{cmd} > #{tmp}")
  677. data = File.read(tmp).chomp
  678. File.unlink tmp rescue nil
  679. end
  680. else
  681. fd = IO.popen(cmd).extend(PlugStream)
  682. first_line = true
  683. log_prob = 1.0 / nthr
  684. while line = Timeout::timeout(timeout) { fd.get_line }
  685. data << line
  686. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  687. first_line = false
  688. end
  689. fd.close
  690. end
  691. [$? == 0, data.chomp]
  692. rescue Timeout::Error, Interrupt => e
  693. if fd && !fd.closed?
  694. pids = [fd.pid]
  695. unless `which pgrep`.empty?
  696. children = pids
  697. until children.empty?
  698. children = children.map { |pid|
  699. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  700. }.flatten
  701. pids += children
  702. end
  703. end
  704. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  705. fd.close
  706. end
  707. if e.is_a?(Timeout::Error) && tried < tries
  708. 3.downto(1) do |countdown|
  709. s = countdown > 1 ? 's' : ''
  710. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  711. sleep 1
  712. end
  713. log.call name, 'Retrying ...', type
  714. retry
  715. end
  716. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  717. end
  718. }
  719. main = Thread.current
  720. threads = []
  721. watcher = Thread.new {
  722. while VIM::evaluate('getchar(1)')
  723. sleep 0.1
  724. end
  725. mtx.synchronize do
  726. running = false
  727. threads.each { |t| t.raise Interrupt }
  728. end
  729. threads.each { |t| t.join rescue nil }
  730. main.kill
  731. }
  732. refresh = Thread.new {
  733. while true
  734. mtx.synchronize do
  735. break unless running
  736. VIM::command('noautocmd normal! a')
  737. end
  738. sleep 0.2
  739. end
  740. } if VIM::evaluate('s:mac_gui') == 1
  741. processed = Set.new
  742. progress = iswin ? '' : '--progress'
  743. until all.empty?
  744. names = all.keys
  745. processed.merge names
  746. [names.length, nthr].min.times do
  747. mtx.synchronize do
  748. threads << Thread.new {
  749. while pair = take1.call
  750. name = pair.first
  751. dir, uri, branch = pair.last.values_at *%w[dir uri branch]
  752. branch = esc branch
  753. subm = "git submodule update --init --recursive 2>&1"
  754. exists = File.directory? dir
  755. ok, result =
  756. if exists
  757. dir = esc dir
  758. ret, data = bt.call "#{cd} #{dir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil
  759. current_uri = data.lines.to_a.last
  760. if !ret
  761. if data =~ /^Interrupted|^Timeout/
  762. [false, data]
  763. else
  764. [false, [data.chomp, "PlugClean required."].join($/)]
  765. end
  766. elsif current_uri.sub(/git:@/, '') != uri.sub(/git:@/, '')
  767. [false, ["Invalid URI: #{current_uri}",
  768. "Expected: #{uri}",
  769. "PlugClean required."].join($/)]
  770. else
  771. if pull
  772. log.call name, 'Updating ...', :update
  773. bt.call "#{cd} #{dir} && git checkout -q #{branch} 2>&1 && (git pull origin #{branch} #{progress} 2>&1 && #{subm})", name, :update
  774. else
  775. [true, skip]
  776. end
  777. end
  778. else
  779. d = esc dir.sub(%r{[\\/]+$}, '')
  780. log.call name, 'Installing ...', :install
  781. bt.call "(git clone #{progress} --recursive #{uri} -b #{branch} #{d} 2>&1 && cd #{esc dir} && #{subm})", name, :install
  782. end
  783. mtx.synchronize { VIM::command("let s:prev_update.new['#{name}'] = 1") } if !exists && ok
  784. log.call name, result, ok
  785. end
  786. } if running
  787. end
  788. end
  789. threads.each { |t| t.join rescue nil }
  790. mtx.synchronize { threads.clear }
  791. extended = Hash[(VIM::evaluate("s:extend(#{names.inspect})") || {}).reject { |k, _|
  792. processed.include? k
  793. }]
  794. tot += extended.length
  795. all.merge!(extended)
  796. logh.call
  797. end
  798. refresh.kill if refresh
  799. watcher.kill
  800. $curbuf[1] = "Updated. Elapsed time: #{"%.6f" % (Time.now - st)} sec."
  801. EOF
  802. endfunction
  803. function! s:shellesc(arg)
  804. return '"'.substitute(a:arg, '"', '\\"', 'g').'"'
  805. endfunction
  806. function! s:glob_dir(path)
  807. return map(filter(split(globpath(a:path, '**'), '\n'), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  808. endfunction
  809. function! s:progress_bar(line, bar, total)
  810. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  811. endfunction
  812. function! s:compare_git_uri(a, b)
  813. let a = substitute(a:a, 'git:@', '', '')
  814. let b = substitute(a:b, 'git:@', '', '')
  815. return a ==# b
  816. endfunction
  817. function! s:format_message(ok, name, message)
  818. if a:ok
  819. return [printf('- %s: %s', a:name, s:lastline(a:message))]
  820. else
  821. let lines = map(split(a:message, '\n'), '" ".v:val')
  822. return extend([printf('x %s:', a:name)], lines)
  823. endif
  824. endfunction
  825. function! s:system(cmd)
  826. return system(s:is_win ? '('.a:cmd.')' : a:cmd)
  827. endfunction
  828. function! s:system_chomp(str)
  829. let ret = s:system(a:str)
  830. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  831. endfunction
  832. function! s:git_valid(spec, check_branch, cd)
  833. let ret = 1
  834. let msg = 'OK'
  835. if isdirectory(a:spec.dir)
  836. if a:cd | execute "cd " . s:esc(a:spec.dir) | endif
  837. let result = split(s:system("git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url"), '\n')
  838. let remote = result[-1]
  839. if v:shell_error
  840. let msg = join([remote, "PlugClean required."], "\n")
  841. let ret = 0
  842. elseif !s:compare_git_uri(remote, a:spec.uri)
  843. let msg = join(['Invalid URI: '.remote,
  844. \ 'Expected: '.a:spec.uri,
  845. \ "PlugClean required."], "\n")
  846. let ret = 0
  847. elseif a:check_branch
  848. let branch = result[0]
  849. if a:spec.branch !=# branch
  850. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1')
  851. if a:spec.branch !=# tag
  852. let msg = printf('Invalid branch/tag: %s (expected: %s). Try PlugUpdate.',
  853. \ (empty(tag) ? branch : tag), a:spec.branch)
  854. let ret = 0
  855. endif
  856. endif
  857. endif
  858. if a:cd | cd - | endif
  859. else
  860. let msg = 'Not found'
  861. let ret = 0
  862. endif
  863. return [ret, msg]
  864. endfunction
  865. function! s:clean(force)
  866. call s:prepare()
  867. call append(0, 'Searching for unused plugins in '.g:plug_home)
  868. call append(1, '')
  869. " List of valid directories
  870. let dirs = []
  871. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  872. let [cnt, total] = [0, len(managed)]
  873. for spec in values(managed)
  874. if s:git_valid(spec, 0, 1)[0]
  875. call add(dirs, spec.dir)
  876. endif
  877. let cnt += 1
  878. call s:progress_bar(2, repeat('=', cnt), total)
  879. normal! 2G
  880. redraw
  881. endfor
  882. let allowed = {}
  883. for dir in dirs
  884. let allowed[dir] = 1
  885. for child in s:glob_dir(dir)
  886. let allowed[child] = 1
  887. endfor
  888. endfor
  889. let todo = []
  890. let found = sort(s:glob_dir(g:plug_home))
  891. while !empty(found)
  892. let f = remove(found, 0)
  893. if !has_key(allowed, f) && isdirectory(f)
  894. call add(todo, f)
  895. call append(line('$'), '- ' . f)
  896. let found = filter(found, 'stridx(v:val, f) != 0')
  897. end
  898. endwhile
  899. normal! G
  900. redraw
  901. if empty(todo)
  902. call append(line('$'), 'Already clean.')
  903. else
  904. call inputsave()
  905. let yes = a:force || (input("Proceed? (Y/N) ") =~? '^y')
  906. call inputrestore()
  907. if yes
  908. for dir in todo
  909. if isdirectory(dir)
  910. call system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(dir))
  911. endif
  912. endfor
  913. call append(line('$'), 'Removed.')
  914. else
  915. call append(line('$'), 'Cancelled.')
  916. endif
  917. endif
  918. normal! G
  919. endfunction
  920. function! s:upgrade()
  921. if executable('curl')
  922. let mee = s:shellesc(s:me)
  923. let new = s:shellesc(s:me . '.new')
  924. echo "Downloading ". s:plug_source
  925. redraw
  926. let mv = s:is_win ? 'move /Y' : 'mv -f'
  927. let cp = s:is_win ? 'copy /Y' : 'cp -f'
  928. call system(printf(
  929. \ "curl -fLo %s %s && ".cp." %s %s.old && ".mv." %s %s",
  930. \ new, s:plug_source, mee, mee, new, mee))
  931. if v:shell_error == 0
  932. unlet g:loaded_plug
  933. echo "Downloaded ". s:plug_source
  934. return 1
  935. else
  936. echoerr "Error upgrading vim-plug"
  937. return 0
  938. endif
  939. elseif has('ruby')
  940. echo "Downloading ". s:plug_source
  941. ruby << EOF
  942. require 'open-uri'
  943. require 'fileutils'
  944. me = VIM::evaluate('s:me')
  945. old = me + '.old'
  946. new = me + '.new'
  947. File.open(new, 'w') do |f|
  948. f << open(VIM::evaluate('s:plug_source')).read
  949. end
  950. FileUtils.cp me, old
  951. File.rename new, me
  952. EOF
  953. unlet g:loaded_plug
  954. echo "Downloaded ". s:plug_source
  955. return 1
  956. else
  957. echoerr "curl executable or ruby support not found"
  958. return 0
  959. endif
  960. endfunction
  961. function! s:status()
  962. call s:prepare()
  963. call append(0, 'Checking plugins')
  964. call append(1, '')
  965. let ecnt = 0
  966. let [cnt, total] = [0, len(g:plugs)]
  967. for [name, spec] in items(g:plugs)
  968. if has_key(spec, 'uri')
  969. if isdirectory(spec.dir)
  970. let [valid, msg] = s:git_valid(spec, 1, 1)
  971. else
  972. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  973. endif
  974. else
  975. if isdirectory(spec.dir)
  976. let [valid, msg] = [1, 'OK']
  977. else
  978. let [valid, msg] = [0, 'Not found.']
  979. endif
  980. endif
  981. let cnt += 1
  982. let ecnt += !valid
  983. call s:progress_bar(2, repeat('=', cnt), total)
  984. call append(3, s:format_message(valid, name, msg))
  985. normal! 2G
  986. redraw
  987. endfor
  988. call setline(1, 'Finished. '.ecnt.' error(s).')
  989. normal! gg
  990. endfunction
  991. function! s:is_preview_window_open()
  992. silent! wincmd P
  993. if &previewwindow
  994. wincmd p
  995. return 1
  996. endif
  997. return 0
  998. endfunction
  999. function! s:preview_commit()
  1000. if b:plug_preview < 0
  1001. let b:plug_preview = !s:is_preview_window_open()
  1002. endif
  1003. let sha = matchstr(getline('.'), '\(^ \)\@<=[0-9a-z]\{7}')
  1004. if !empty(sha)
  1005. let lnum = line('.')
  1006. while lnum > 1
  1007. let lnum -= 1
  1008. let line = getline(lnum)
  1009. let name = matchstr(line, '\(^- \)\@<=[^:]\+')
  1010. if !empty(name)
  1011. let dir = g:plugs[name].dir
  1012. if isdirectory(dir)
  1013. execute 'cd '.s:esc(dir)
  1014. execute 'pedit '.sha
  1015. wincmd P
  1016. setlocal filetype=git buftype=nofile nobuflisted
  1017. execute 'silent read !git show '.sha
  1018. normal! ggdd
  1019. wincmd p
  1020. cd -
  1021. endif
  1022. break
  1023. endif
  1024. endwhile
  1025. endif
  1026. endfunction
  1027. function! s:section(flags)
  1028. call search('\(^- \)\@<=.', a:flags)
  1029. endfunction
  1030. function! s:diff()
  1031. call s:prepare()
  1032. call append(0, 'Collecting updated changes ...')
  1033. normal! gg
  1034. redraw
  1035. let cnt = 0
  1036. for [k, v] in items(g:plugs)
  1037. if !isdirectory(v.dir) || !s:is_managed(k)
  1038. continue
  1039. endif
  1040. execute 'cd '.s:esc(v.dir)
  1041. let diff = system('git log --pretty=format:"%h %s (%cr)" "HEAD...HEAD@{1}"')
  1042. if !v:shell_error && !empty(diff)
  1043. call append(1, '')
  1044. call append(2, '- '.k.':')
  1045. call append(3, map(split(diff, '\n'), '" ". v:val'))
  1046. let cnt += 1
  1047. normal! gg
  1048. redraw
  1049. endif
  1050. cd -
  1051. endfor
  1052. call setline(1, cnt == 0 ? 'No updates.' : 'Last update:')
  1053. nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
  1054. normal! gg
  1055. endfunction
  1056. let s:first_rtp = s:esc(get(split(&rtp, ','), 0, ''))
  1057. let s:last_rtp = s:esc(get(split(&rtp, ','), -1, ''))
  1058. let &cpo = s:cpo_save
  1059. unlet s:cpo_save