plug.vim 32 KB

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