plug.vim 32 KB

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