plug.vim 32 KB

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