plug.vim 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570
  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.githubusercontent.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. " " Plugin outside ~/.vim/plugged with post-update hook
  29. " Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': 'yes \| ./install' }
  30. "
  31. " " Unmanaged plugin (manually installed and updated)
  32. " Plug '~/my-prototype-plugin'
  33. "
  34. " call plug#end()
  35. "
  36. " Then reload .vimrc and :PlugInstall to install plugins.
  37. " Visit https://github.com/junegunn/vim-plug for more information.
  38. "
  39. "
  40. " Copyright (c) 2014 Junegunn Choi
  41. "
  42. " MIT License
  43. "
  44. " Permission is hereby granted, free of charge, to any person obtaining
  45. " a copy of this software and associated documentation files (the
  46. " "Software"), to deal in the Software without restriction, including
  47. " without limitation the rights to use, copy, modify, merge, publish,
  48. " distribute, sublicense, and/or sell copies of the Software, and to
  49. " permit persons to whom the Software is furnished to do so, subject to
  50. " the following conditions:
  51. "
  52. " The above copyright notice and this permission notice shall be
  53. " included in all copies or substantial portions of the Software.
  54. "
  55. " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  56. " EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  57. " MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  58. " NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  59. " LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  60. " OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  61. " WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  62. if exists('g:loaded_plug')
  63. finish
  64. endif
  65. let g:loaded_plug = 1
  66. let s:cpo_save = &cpo
  67. set cpo&vim
  68. let s:plug_src = 'https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
  69. let s:plug_tab = get(s:, 'plug_tab', -1)
  70. let s:plug_buf = get(s:, 'plug_buf', -1)
  71. let s:mac_gui = has('gui_macvim') && has('gui_running')
  72. let s:is_win = has('win32') || has('win64')
  73. let s:nvim = has('nvim') && !s:is_win
  74. let s:me = resolve(expand('<sfile>:p'))
  75. let s:base_spec = { 'branch': 'master', 'frozen': 0 }
  76. let s:TYPE = {
  77. \ 'string': type(''),
  78. \ 'list': type([]),
  79. \ 'dict': type({}),
  80. \ 'funcref': type(function('call'))
  81. \ }
  82. let s:loaded = get(s:, 'loaded', {})
  83. let s:triggers = get(s:, 'triggers', {})
  84. function! plug#begin(...)
  85. if a:0 > 0
  86. let s:plug_home_org = a:1
  87. let home = s:path(fnamemodify(expand(a:1), ':p'))
  88. elseif exists('g:plug_home')
  89. let home = s:path(g:plug_home)
  90. elseif !empty(&rtp)
  91. let home = s:path(split(&rtp, ',')[0]) . '/plugged'
  92. else
  93. return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.')
  94. endif
  95. let g:plug_home = home
  96. let g:plugs = {}
  97. let g:plugs_order = []
  98. let s:triggers = {}
  99. call s:define_commands()
  100. return 1
  101. endfunction
  102. function! s:define_commands()
  103. command! -nargs=+ -bar Plug call s:add(<args>)
  104. if !executable('git')
  105. return s:err('`git` executable not found. vim-plug requires git.')
  106. endif
  107. command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install('<bang>' == '!', [<f-args>])
  108. command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update('<bang>' == '!', [<f-args>])
  109. command! -nargs=0 -bar -bang PlugClean call s:clean('<bang>' == '!')
  110. command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:me | endif
  111. command! -nargs=0 -bar PlugStatus call s:status()
  112. command! -nargs=0 -bar PlugDiff call s:diff()
  113. command! -nargs=? -bar PlugSnapshot call s:snapshot(<f-args>)
  114. endfunction
  115. function! s:to_a(v)
  116. return type(a:v) == s:TYPE.list ? a:v : [a:v]
  117. endfunction
  118. function! s:to_s(v)
  119. return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n"
  120. endfunction
  121. function! s:source(from, ...)
  122. for pattern in a:000
  123. for vim in s:lines(globpath(a:from, pattern))
  124. execute 'source' vim
  125. endfor
  126. endfor
  127. endfunction
  128. function! s:assoc(dict, key, val)
  129. let a:dict[a:key] = add(get(a:dict, a:key, []), a:val)
  130. endfunction
  131. function! plug#end()
  132. if !exists('g:plugs')
  133. return s:err('Call plug#begin() first')
  134. endif
  135. if exists('#PlugLOD')
  136. augroup PlugLOD
  137. autocmd!
  138. augroup END
  139. augroup! PlugLOD
  140. endif
  141. let lod = { 'ft': {}, 'map': {}, 'cmd': {} }
  142. filetype off
  143. for name in g:plugs_order
  144. let plug = g:plugs[name]
  145. if get(s:loaded, name, 0) || !has_key(plug, 'on') && !has_key(plug, 'for')
  146. let s:loaded[name] = 1
  147. continue
  148. endif
  149. if has_key(plug, 'on')
  150. let s:triggers[name] = { 'map': [], 'cmd': [] }
  151. for cmd in s:to_a(plug.on)
  152. if cmd =~ '^<Plug>.\+'
  153. if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i'))
  154. call s:assoc(lod.map, cmd, name)
  155. endif
  156. call add(s:triggers[name].map, cmd)
  157. elseif cmd =~ '^[A-Z]'
  158. if exists(':'.cmd) != 2
  159. call s:assoc(lod.cmd, cmd, name)
  160. endif
  161. call add(s:triggers[name].cmd, cmd)
  162. endif
  163. endfor
  164. endif
  165. if has_key(plug, 'for')
  166. let types = s:to_a(plug.for)
  167. if !empty(types)
  168. call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim')
  169. endif
  170. for type in types
  171. call s:assoc(lod.ft, type, name)
  172. endfor
  173. endif
  174. endfor
  175. for [cmd, names] in items(lod.cmd)
  176. execute printf(
  177. \ 'command! -nargs=* -range -bang %s call s:lod_cmd(%s, "<bang>", <line1>, <line2>, <q-args>, %s)',
  178. \ cmd, string(cmd), string(names))
  179. endfor
  180. for [map, names] in items(lod.map)
  181. for [mode, map_prefix, key_prefix] in
  182. \ [['i', '<C-O>', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']]
  183. execute printf(
  184. \ '%snoremap <silent> %s %s:<C-U>call <SID>lod_map(%s, %s, "%s")<CR>',
  185. \ mode, map, map_prefix, string(map), string(names), key_prefix)
  186. endfor
  187. endfor
  188. for [ft, names] in items(lod.ft)
  189. augroup PlugLOD
  190. execute printf('autocmd FileType %s call <SID>lod_ft(%s, %s)',
  191. \ ft, string(ft), string(names))
  192. augroup END
  193. endfor
  194. call s:reorg_rtp()
  195. filetype plugin indent on
  196. if has('vim_starting')
  197. syntax enable
  198. else
  199. call s:reload()
  200. endif
  201. endfunction
  202. function! s:loaded_names()
  203. return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)')
  204. endfunction
  205. function! s:reload()
  206. for name in s:loaded_names()
  207. call s:source(s:rtp(g:plugs[name]), 'plugin/**/*.vim', 'after/plugin/**/*.vim')
  208. endfor
  209. endfunction
  210. function! s:trim(str)
  211. return substitute(a:str, '[\/]\+$', '', '')
  212. endfunction
  213. if s:is_win
  214. function! s:rtp(spec)
  215. return s:path(a:spec.dir . get(a:spec, 'rtp', ''))
  216. endfunction
  217. function! s:path(path)
  218. return s:trim(substitute(a:path, '/', '\', 'g'))
  219. endfunction
  220. function! s:dirpath(path)
  221. return s:path(a:path) . '\'
  222. endfunction
  223. function! s:is_local_plug(repo)
  224. return a:repo =~? '^[a-z]:'
  225. endfunction
  226. else
  227. function! s:rtp(spec)
  228. return s:dirpath(a:spec.dir . get(a:spec, 'rtp', ''))
  229. endfunction
  230. function! s:path(path)
  231. return s:trim(a:path)
  232. endfunction
  233. function! s:dirpath(path)
  234. return substitute(a:path, '[/\\]*$', '/', '')
  235. endfunction
  236. function! s:is_local_plug(repo)
  237. return a:repo[0] =~ '[/$~]'
  238. endfunction
  239. endif
  240. function! s:err(msg)
  241. echohl ErrorMsg
  242. echom a:msg
  243. echohl None
  244. return 0
  245. endfunction
  246. function! s:esc(path)
  247. return escape(a:path, ' ')
  248. endfunction
  249. function! s:escrtp(path)
  250. return escape(a:path, ' ,')
  251. endfunction
  252. function! s:remove_rtp()
  253. for name in s:loaded_names()
  254. let rtp = s:rtp(g:plugs[name])
  255. execute 'set rtp-='.s:escrtp(rtp)
  256. let after = globpath(rtp, 'after')
  257. if isdirectory(after)
  258. execute 'set rtp-='.s:escrtp(after)
  259. endif
  260. endfor
  261. endfunction
  262. function! s:reorg_rtp()
  263. if !empty(s:first_rtp)
  264. execute 'set rtp-='.s:first_rtp
  265. execute 'set rtp-='.s:last_rtp
  266. endif
  267. " &rtp is modified from outside
  268. if exists('s:prtp') && s:prtp !=# &rtp
  269. call s:remove_rtp()
  270. unlet! s:middle
  271. endif
  272. let s:middle = get(s:, 'middle', &rtp)
  273. let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])')
  274. let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), 'isdirectory(v:val)')
  275. let rtp = join(map(rtps, 's:escrtp(v:val)'), ',')
  276. \ . ','.s:middle.','
  277. \ . join(map(afters, 's:escrtp(v:val)'), ',')
  278. let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g')
  279. let s:prtp = &rtp
  280. if !empty(s:first_rtp)
  281. execute 'set rtp^='.s:first_rtp
  282. execute 'set rtp+='.s:last_rtp
  283. endif
  284. endfunction
  285. function! plug#load(...)
  286. if a:0 == 0
  287. return s:err('Argument missing: plugin name(s) required')
  288. endif
  289. if !exists('g:plugs')
  290. return s:err('plug#begin was not called')
  291. endif
  292. let unknowns = filter(copy(a:000), '!has_key(g:plugs, v:val)')
  293. if !empty(unknowns)
  294. let s = len(unknowns) > 1 ? 's' : ''
  295. return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', ')))
  296. end
  297. for name in a:000
  298. call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  299. endfor
  300. doautocmd BufRead
  301. return 1
  302. endfunction
  303. function! s:remove_triggers(name)
  304. if !has_key(s:triggers, a:name)
  305. return
  306. endif
  307. for cmd in s:triggers[a:name].cmd
  308. execute 'silent! delc' cmd
  309. endfor
  310. for map in s:triggers[a:name].map
  311. execute 'silent! unmap' map
  312. execute 'silent! iunmap' map
  313. endfor
  314. call remove(s:triggers, a:name)
  315. endfunction
  316. function! s:lod(names, types)
  317. for name in a:names
  318. call s:remove_triggers(name)
  319. let s:loaded[name] = 1
  320. endfor
  321. call s:reorg_rtp()
  322. for name in a:names
  323. let rtp = s:rtp(g:plugs[name])
  324. for dir in a:types
  325. call s:source(rtp, dir.'/**/*.vim')
  326. endfor
  327. endfor
  328. endfunction
  329. function! s:lod_ft(pat, names)
  330. call s:lod(a:names, ['plugin', 'after/plugin'])
  331. execute 'autocmd! PlugLOD FileType' a:pat
  332. doautocmd filetypeplugin FileType
  333. doautocmd filetypeindent FileType
  334. endfunction
  335. function! s:lod_cmd(cmd, bang, l1, l2, args, names)
  336. call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  337. execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args)
  338. endfunction
  339. function! s:lod_map(map, names, prefix)
  340. call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  341. let extra = ''
  342. while 1
  343. let c = getchar(0)
  344. if c == 0
  345. break
  346. endif
  347. let extra .= nr2char(c)
  348. endwhile
  349. call feedkeys(a:prefix . substitute(a:map, '^<Plug>', "\<Plug>", '') . extra)
  350. endfunction
  351. function! s:add(repo, ...)
  352. if a:0 > 1
  353. return s:err('Invalid number of arguments (1..2)')
  354. endif
  355. try
  356. let repo = s:trim(a:repo)
  357. let name = fnamemodify(repo, ':t:s?\.git$??')
  358. let spec = extend(s:infer_properties(name, repo),
  359. \ a:0 == 1 ? s:parse_options(a:1) : s:base_spec)
  360. let g:plugs[name] = spec
  361. let g:plugs_order += [name]
  362. let s:loaded[name] = 0
  363. catch
  364. return s:err(v:exception)
  365. endtry
  366. endfunction
  367. function! s:parse_options(arg)
  368. let opts = copy(s:base_spec)
  369. let type = type(a:arg)
  370. if type == s:TYPE.string
  371. let opts.branch = a:arg
  372. elseif type == s:TYPE.dict
  373. call extend(opts, a:arg)
  374. if has_key(opts, 'tag')
  375. let opts.branch = remove(opts, 'tag')
  376. endif
  377. if has_key(opts, 'dir')
  378. let opts.dir = s:dirpath(expand(opts.dir))
  379. endif
  380. else
  381. throw 'Invalid argument type (expected: string or dictionary)'
  382. endif
  383. return opts
  384. endfunction
  385. function! s:infer_properties(name, repo)
  386. let repo = a:repo
  387. if s:is_local_plug(repo)
  388. return { 'dir': s:dirpath(expand(repo)) }
  389. else
  390. if repo =~ ':'
  391. let uri = repo
  392. else
  393. if repo !~ '/'
  394. let repo = 'vim-scripts/'. repo
  395. endif
  396. let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git')
  397. let uri = printf(fmt, repo)
  398. endif
  399. let dir = s:dirpath( fnamemodify(join([g:plug_home, a:name], '/'), ':p') )
  400. return { 'dir': dir, 'uri': uri }
  401. endif
  402. endfunction
  403. function! s:install(force, names)
  404. call s:update_impl(0, a:force, a:names)
  405. endfunction
  406. function! s:update(force, names)
  407. call s:update_impl(1, a:force, a:names)
  408. endfunction
  409. function! plug#helptags()
  410. if !exists('g:plugs')
  411. return s:err('plug#begin was not called')
  412. endif
  413. for spec in values(g:plugs)
  414. let docd = join([spec.dir, 'doc'], '/')
  415. if isdirectory(docd)
  416. silent! execute 'helptags' s:esc(docd)
  417. endif
  418. endfor
  419. return 1
  420. endfunction
  421. function! s:syntax()
  422. syntax clear
  423. syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber
  424. syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX
  425. syn match plugNumber /[0-9]\+[0-9.]*/ contained
  426. syn match plugBracket /[[\]]/ contained
  427. syn match plugX /x/ contained
  428. syn match plugDash /^-/
  429. syn match plugPlus /^+/
  430. syn match plugStar /^*/
  431. syn match plugMessage /\(^- \)\@<=.*/
  432. syn match plugName /\(^- \)\@<=[^ ]*:/
  433. syn match plugInstall /\(^+ \)\@<=[^:]*/
  434. syn match plugUpdate /\(^* \)\@<=[^:]*/
  435. syn match plugCommit /^ [0-9a-z]\{7} .*/ contains=plugRelDate,plugSha
  436. syn match plugSha /\(^ \)\@<=[0-9a-z]\{7}/ contained
  437. syn match plugRelDate /([^)]*)$/ contained
  438. syn match plugNotLoaded /(not loaded)$/
  439. syn match plugError /^x.*/
  440. syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean
  441. hi def link plug1 Title
  442. hi def link plug2 Repeat
  443. hi def link plugX Exception
  444. hi def link plugBracket Structure
  445. hi def link plugNumber Number
  446. hi def link plugDash Special
  447. hi def link plugPlus Constant
  448. hi def link plugStar Boolean
  449. hi def link plugMessage Function
  450. hi def link plugName Label
  451. hi def link plugInstall Function
  452. hi def link plugUpdate Type
  453. hi def link plugError Error
  454. hi def link plugRelDate Comment
  455. hi def link plugSha Identifier
  456. hi def link plugNotLoaded Comment
  457. endfunction
  458. function! s:lpad(str, len)
  459. return a:str . repeat(' ', a:len - len(a:str))
  460. endfunction
  461. function! s:lines(msg)
  462. return split(a:msg, "[\r\n]")
  463. endfunction
  464. function! s:lastline(msg)
  465. return get(s:lines(a:msg), -1, '')
  466. endfunction
  467. function! s:new_window()
  468. execute get(g:, 'plug_window', 'vertical topleft new')
  469. endfunction
  470. function! s:plug_window_exists()
  471. let buflist = tabpagebuflist(s:plug_tab)
  472. return !empty(buflist) && index(buflist, s:plug_buf) >= 0
  473. endfunction
  474. function! s:switch_in()
  475. if !s:plug_window_exists()
  476. return 0
  477. endif
  478. if winbufnr(0) != s:plug_buf
  479. let s:pos = [tabpagenr(), winnr(), winsaveview()]
  480. execute 'normal!' s:plug_tab.'gt'
  481. let winnr = bufwinnr(s:plug_buf)
  482. execute winnr.'wincmd w'
  483. call add(s:pos, winsaveview())
  484. else
  485. let s:pos = [winsaveview()]
  486. endif
  487. setlocal modifiable
  488. return 1
  489. endfunction
  490. function! s:switch_out(...)
  491. call winrestview(s:pos[-1])
  492. setlocal nomodifiable
  493. if a:0 > 0
  494. execute a:1
  495. endif
  496. if len(s:pos) > 1
  497. execute 'normal!' s:pos[0].'gt'
  498. execute s:pos[1] 'wincmd w'
  499. call winrestview(s:pos[2])
  500. endif
  501. endfunction
  502. function! s:prepare()
  503. call s:job_abort()
  504. if s:switch_in()
  505. silent %d _
  506. else
  507. call s:new_window()
  508. nnoremap <silent> <buffer> q :if b:plug_preview==1<bar>pc<bar>endif<bar>echo<bar>q<cr>
  509. nnoremap <silent> <buffer> R :silent! call <SID>retry()<cr>
  510. nnoremap <silent> <buffer> D :PlugDiff<cr>
  511. nnoremap <silent> <buffer> S :PlugStatus<cr>
  512. nnoremap <silent> <buffer> U :call <SID>status_update()<cr>
  513. xnoremap <silent> <buffer> U :call <SID>status_update()<cr>
  514. nnoremap <silent> <buffer> ]] :silent! call <SID>section('')<cr>
  515. nnoremap <silent> <buffer> [[ :silent! call <SID>section('b')<cr>
  516. let b:plug_preview = -1
  517. let s:plug_tab = tabpagenr()
  518. let s:plug_buf = winbufnr(0)
  519. call s:assign_name()
  520. endif
  521. silent! unmap <buffer> <cr>
  522. silent! unmap <buffer> L
  523. silent! unmap <buffer> X
  524. setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap cursorline modifiable
  525. setf vim-plug
  526. call s:syntax()
  527. endfunction
  528. function! s:assign_name()
  529. " Assign buffer name
  530. let prefix = '[Plugins]'
  531. let name = prefix
  532. let idx = 2
  533. while bufexists(name)
  534. let name = printf('%s (%s)', prefix, idx)
  535. let idx = idx + 1
  536. endwhile
  537. silent! execute 'f' fnameescape(name)
  538. endfunction
  539. function! s:do(pull, force, todo)
  540. for [name, spec] in items(a:todo)
  541. if !isdirectory(spec.dir)
  542. continue
  543. endif
  544. let installed = has_key(s:update.new, name)
  545. let updated = installed ? 0 :
  546. \ (a:pull && !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', spec.dir)))
  547. if a:force || installed || updated
  548. execute 'cd' s:esc(spec.dir)
  549. call append(3, '- Post-update hook for '. name .' ... ')
  550. let type = type(spec.do)
  551. if type == s:TYPE.string
  552. try
  553. " FIXME: Escaping is incomplete. We could use shellescape with eval,
  554. " but it won't work on Windows.
  555. let g:_plug_do = '!'.escape(spec.do, '#!%')
  556. execute "normal! :execute g:_plug_do\<cr>\<cr>"
  557. finally
  558. let result = v:shell_error ? ('Exit status: '.v:shell_error) : 'Done!'
  559. unlet g:_plug_do
  560. endtry
  561. elseif type == s:TYPE.funcref
  562. try
  563. let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
  564. call spec.do({ 'name': name, 'status': status, 'force': a:force })
  565. let result = 'Done!'
  566. catch
  567. let result = 'Error: ' . v:exception
  568. endtry
  569. else
  570. let result = 'Error: Invalid type!'
  571. endif
  572. call setline(4, getline(4) . result)
  573. cd -
  574. endif
  575. endfor
  576. endfunction
  577. function! s:finish(pull)
  578. let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
  579. if new_frozen
  580. let s = new_frozen > 1 ? 's' : ''
  581. call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
  582. endif
  583. call append(3, '- Finishing ... ')
  584. redraw
  585. call plug#helptags()
  586. call plug#end()
  587. call setline(4, getline(4) . 'Done!')
  588. redraw
  589. let msgs = []
  590. if !empty(s:update.errors)
  591. call add(msgs, "Press 'R' to retry.")
  592. endif
  593. if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
  594. \ "v:val =~ '^- ' && stridx(v:val, 'Already up-to-date') < 0"))
  595. call add(msgs, "Press 'D' to see the updated changes.")
  596. endif
  597. echo join(msgs, ' ')
  598. endfunction
  599. function! s:retry()
  600. if empty(s:update.errors)
  601. return
  602. endif
  603. call s:update_impl(s:update.pull, s:update.force,
  604. \ extend(copy(s:update.errors), [s:update.threads]))
  605. endfunction
  606. function! s:is_managed(name)
  607. return has_key(g:plugs[a:name], 'uri')
  608. endfunction
  609. function! s:names(...)
  610. return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
  611. endfunction
  612. function! s:update_impl(pull, force, args) abort
  613. let args = copy(a:args)
  614. let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
  615. \ remove(args, -1) : get(g:, 'plug_threads', 16)
  616. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  617. let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
  618. \ filter(managed, 'index(args, v:key) >= 0')
  619. if empty(todo)
  620. echohl WarningMsg
  621. echo 'No plugin to '. (a:pull ? 'update' : 'install') . '.'
  622. echohl None
  623. return
  624. endif
  625. if !isdirectory(g:plug_home)
  626. try
  627. call mkdir(g:plug_home, 'p')
  628. catch
  629. return s:err(printf('Invalid plug directory: %s. '.
  630. \ 'Try to call plug#begin with a valid directory', g:plug_home))
  631. endtry
  632. endif
  633. let s:update = {
  634. \ 'start': reltime(),
  635. \ 'all': todo,
  636. \ 'todo': copy(todo),
  637. \ 'errors': [],
  638. \ 'pull': a:pull,
  639. \ 'force': a:force,
  640. \ 'new': {},
  641. \ 'threads': (has('ruby') || s:nvim) ? min([len(todo), threads]) : 1,
  642. \ 'bar': '',
  643. \ 'fin': 0
  644. \ }
  645. call s:prepare()
  646. call append(0, ['', ''])
  647. normal! 2G
  648. if has('ruby') && s:update.threads > 1
  649. try
  650. let imd = &imd
  651. if s:mac_gui
  652. set noimd
  653. endif
  654. call s:update_ruby()
  655. catch
  656. let lines = getline(4, '$')
  657. let printed = {}
  658. silent! 4,$d _
  659. for line in lines
  660. let name = s:extract_name(line, '.', '')
  661. if empty(name) || !has_key(printed, name)
  662. call append('$', line)
  663. if !empty(name)
  664. let printed[name] = 1
  665. if line[0] == 'x' && index(s:update.errors, name) < 0
  666. call add(s:update.errors, name)
  667. end
  668. endif
  669. endif
  670. endfor
  671. finally
  672. let &imd = imd
  673. call s:update_finish()
  674. endtry
  675. else
  676. call s:update_vim()
  677. endif
  678. endfunction
  679. function! s:update_finish()
  680. if s:switch_in()
  681. call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'has_key(v:val, "do")'))
  682. call s:finish(s:update.pull)
  683. call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
  684. call s:switch_out('normal! gg')
  685. endif
  686. endfunction
  687. function! s:job_abort()
  688. if !s:nvim || !exists('s:jobs')
  689. return
  690. endif
  691. augroup PlugJobControl
  692. autocmd!
  693. augroup END
  694. for [name, j] in items(s:jobs)
  695. silent! call jobstop(j.jobid)
  696. if j.new
  697. call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir))
  698. endif
  699. endfor
  700. let s:jobs = {}
  701. endfunction
  702. function! s:job_handler(name) abort
  703. if !s:plug_window_exists() " plug window closed
  704. return s:job_abort()
  705. endif
  706. if !has_key(s:jobs, a:name)
  707. return
  708. endif
  709. let job = s:jobs[a:name]
  710. if v:job_data[1] == 'exit'
  711. let job.running = 0
  712. if s:lastline(job.result) ==# 'Error'
  713. let job.error = 1
  714. let job.result = substitute(job.result, "Error[\r\n]$", '', '')
  715. endif
  716. call s:reap(a:name)
  717. call s:tick()
  718. else
  719. let job.result .= s:to_s(v:job_data[2])
  720. " To reduce the number of buffer updates
  721. let job.tick = get(job, 'tick', -1) + 1
  722. if job.tick % len(s:jobs) == 0
  723. call s:log(job.new ? '+' : '*', a:name, job.result)
  724. endif
  725. endif
  726. endfunction
  727. function! s:spawn(name, cmd, opts)
  728. let job = { 'running': 1, 'new': get(a:opts, 'new', 0),
  729. \ 'error': 0, 'result': '' }
  730. let s:jobs[a:name] = job
  731. if s:nvim
  732. let x = jobstart(a:name, 'sh', ['-c',
  733. \ (has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd)
  734. \ . ' || echo Error'])
  735. if x > 0
  736. let job.jobid = x
  737. augroup PlugJobControl
  738. execute 'autocmd JobActivity' a:name printf('call s:job_handler(%s)', string(a:name))
  739. augroup END
  740. else
  741. let job.running = 0
  742. let job.error = 1
  743. let job.result = x < 0 ? 'sh is not executable' :
  744. \ 'Invalid arguments (or job table is full)'
  745. endif
  746. else
  747. let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd]
  748. let job.result = call('s:system', params)
  749. let job.error = v:shell_error != 0
  750. let job.running = 0
  751. endif
  752. endfunction
  753. function! s:reap(name)
  754. if s:nvim
  755. silent! execute 'autocmd! PlugJobControl JobActivity' a:name
  756. endif
  757. let job = s:jobs[a:name]
  758. if job.error
  759. call add(s:update.errors, a:name)
  760. elseif get(job, 'new', 0)
  761. let s:update.new[a:name] = 1
  762. endif
  763. let s:update.bar .= job.error ? 'x' : '='
  764. call s:log(job.error ? 'x' : '-', a:name, job.result)
  765. call s:bar()
  766. call remove(s:jobs, a:name)
  767. endfunction
  768. function! s:bar()
  769. if s:switch_in()
  770. let total = len(s:update.all)
  771. call setline(1, (s:update.pull ? 'Updating' : 'Installing').
  772. \ ' plugins ('.len(s:update.bar).'/'.total.')')
  773. call s:progress_bar(2, s:update.bar, total)
  774. call s:switch_out()
  775. endif
  776. endfunction
  777. function! s:logpos(name)
  778. for i in range(1, line('$'))
  779. if getline(i) =~# '^[-+x*] '.a:name.':'
  780. return i
  781. endif
  782. endfor
  783. return 0
  784. endfunction
  785. function! s:log(bullet, name, lines)
  786. if s:switch_in()
  787. let pos = s:logpos(a:name)
  788. if pos > 0
  789. execute pos 'd _'
  790. if pos > winheight('.')
  791. let pos = 4
  792. endif
  793. else
  794. let pos = 4
  795. endif
  796. call append(pos - 1, s:format_message(a:bullet, a:name, a:lines))
  797. call s:switch_out()
  798. endif
  799. endfunction
  800. function! s:update_vim()
  801. let s:jobs = {}
  802. call s:bar()
  803. call s:tick()
  804. endfunction
  805. function! s:tick()
  806. while 1 " Without TCO, Vim stack is bound to explode
  807. if empty(s:update.todo)
  808. if empty(s:jobs) && !s:update.fin
  809. let s:update.fin = 1
  810. call s:update_finish()
  811. endif
  812. return
  813. endif
  814. let name = keys(s:update.todo)[0]
  815. let spec = remove(s:update.todo, name)
  816. let pull = s:update.pull
  817. let new = !isdirectory(spec.dir)
  818. let prog = s:nvim ? '--progress' : ''
  819. call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
  820. redraw
  821. if !new
  822. let [valid, msg] = s:git_valid(spec, 0)
  823. if valid
  824. if pull
  825. call s:spawn(name,
  826. \ printf('(git fetch %s 2>&1 && git checkout -q %s 2>&1 && git merge --ff-only origin/%s 2>&1 && git submodule update --init --recursive 2>&1)',
  827. \ prog, s:shellesc(spec.branch), s:shellesc(spec.branch)), { 'dir': spec.dir })
  828. else
  829. let s:jobs[name] = { 'running': 0, 'result': 'Already installed', 'error': 0 }
  830. endif
  831. else
  832. let s:jobs[name] = { 'running': 0, 'result': msg, 'error': 1 }
  833. endif
  834. else
  835. call s:spawn(name,
  836. \ printf('git clone %s --recursive %s -b %s %s 2>&1',
  837. \ prog,
  838. \ s:shellesc(spec.uri),
  839. \ s:shellesc(spec.branch),
  840. \ s:shellesc(s:trim(spec.dir))), { 'new': 1 })
  841. endif
  842. if !s:jobs[name].running
  843. call s:reap(name)
  844. endif
  845. if len(s:jobs) >= s:update.threads
  846. break
  847. endif
  848. endwhile
  849. endfunction
  850. function! s:update_ruby()
  851. ruby << EOF
  852. module PlugStream
  853. SEP = ["\r", "\n", nil]
  854. def get_line
  855. buffer = ''
  856. loop do
  857. char = readchar rescue return
  858. if SEP.include? char.chr
  859. buffer << $/
  860. break
  861. else
  862. buffer << char
  863. end
  864. end
  865. buffer
  866. end
  867. end unless defined?(PlugStream)
  868. def esc arg
  869. %["#{arg.gsub('"', '\"')}"]
  870. end
  871. def killall pid
  872. pids = [pid]
  873. unless `which pgrep 2> /dev/null`.empty?
  874. children = pids
  875. until children.empty?
  876. children = children.map { |pid|
  877. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  878. }.flatten
  879. pids += children
  880. end
  881. end
  882. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  883. end
  884. require 'thread'
  885. require 'fileutils'
  886. require 'timeout'
  887. running = true
  888. iswin = VIM::evaluate('s:is_win').to_i == 1
  889. pull = VIM::evaluate('s:update.pull').to_i == 1
  890. base = VIM::evaluate('g:plug_home')
  891. all = VIM::evaluate('s:update.todo')
  892. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  893. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  894. nthr = VIM::evaluate('s:update.threads').to_i
  895. maxy = VIM::evaluate('winheight(".")').to_i
  896. cd = iswin ? 'cd /d' : 'cd'
  897. tot = VIM::evaluate('len(s:update.todo)') || 0
  898. bar = ''
  899. skip = 'Already installed'
  900. mtx = Mutex.new
  901. take1 = proc { mtx.synchronize { running && all.shift } }
  902. logh = proc {
  903. cnt = bar.length
  904. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  905. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  906. VIM::command('normal! 2G')
  907. VIM::command('redraw') unless iswin
  908. }
  909. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  910. log = proc { |name, result, type|
  911. mtx.synchronize do
  912. ing = ![true, false].include?(type)
  913. bar += type ? '=' : 'x' unless ing
  914. b = case type
  915. when :install then '+' when :update then '*'
  916. when true, nil then '-' else
  917. VIM::command("call add(s:update.errors, '#{name}')")
  918. 'x'
  919. end
  920. result =
  921. if type || type.nil?
  922. ["#{b} #{name}: #{result.lines.to_a.last}"]
  923. elsif result =~ /^Interrupted|^Timeout/
  924. ["#{b} #{name}: #{result}"]
  925. else
  926. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  927. end
  928. if lnum = where.call(name)
  929. $curbuf.delete lnum
  930. lnum = 4 if ing && lnum > maxy
  931. end
  932. result.each_with_index do |line, offset|
  933. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  934. end
  935. logh.call
  936. end
  937. }
  938. bt = proc { |cmd, name, type, cleanup|
  939. tried = timeout = 0
  940. begin
  941. tried += 1
  942. timeout += limit
  943. fd = nil
  944. data = ''
  945. if iswin
  946. Timeout::timeout(timeout) do
  947. tmp = VIM::evaluate('tempname()')
  948. system("#{cmd} > #{tmp}")
  949. data = File.read(tmp).chomp
  950. File.unlink tmp rescue nil
  951. end
  952. else
  953. fd = IO.popen(cmd).extend(PlugStream)
  954. first_line = true
  955. log_prob = 1.0 / nthr
  956. while line = Timeout::timeout(timeout) { fd.get_line }
  957. data << line
  958. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  959. first_line = false
  960. end
  961. fd.close
  962. end
  963. [$? == 0, data.chomp]
  964. rescue Timeout::Error, Interrupt => e
  965. if fd && !fd.closed?
  966. killall fd.pid
  967. fd.close
  968. end
  969. cleanup.call if cleanup
  970. if e.is_a?(Timeout::Error) && tried < tries
  971. 3.downto(1) do |countdown|
  972. s = countdown > 1 ? 's' : ''
  973. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  974. sleep 1
  975. end
  976. log.call name, 'Retrying ...', type
  977. retry
  978. end
  979. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  980. end
  981. }
  982. main = Thread.current
  983. threads = []
  984. watcher = Thread.new {
  985. while VIM::evaluate('getchar(1)')
  986. sleep 0.1
  987. end
  988. mtx.synchronize do
  989. running = false
  990. threads.each { |t| t.raise Interrupt }
  991. end
  992. threads.each { |t| t.join rescue nil }
  993. main.kill
  994. }
  995. refresh = Thread.new {
  996. while true
  997. mtx.synchronize do
  998. break unless running
  999. VIM::command('noautocmd normal! a')
  1000. end
  1001. sleep 0.2
  1002. end
  1003. } if VIM::evaluate('s:mac_gui') == 1
  1004. progress = iswin ? '' : '--progress'
  1005. nthr.times do
  1006. mtx.synchronize do
  1007. threads << Thread.new {
  1008. while pair = take1.call
  1009. name = pair.first
  1010. dir, uri, branch = pair.last.values_at *%w[dir uri branch]
  1011. branch = esc branch
  1012. subm = "git submodule update --init --recursive 2>&1"
  1013. exists = File.directory? dir
  1014. ok, result =
  1015. if exists
  1016. dir = esc dir
  1017. ret, data = bt.call "#{cd} #{dir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil, nil
  1018. current_uri = data.lines.to_a.last
  1019. if !ret
  1020. if data =~ /^Interrupted|^Timeout/
  1021. [false, data]
  1022. else
  1023. [false, [data.chomp, "PlugClean required."].join($/)]
  1024. end
  1025. elsif current_uri.sub(/git::?@/, '') != uri.sub(/git::?@/, '')
  1026. [false, ["Invalid URI: #{current_uri}",
  1027. "Expected: #{uri}",
  1028. "PlugClean required."].join($/)]
  1029. else
  1030. if pull
  1031. log.call name, 'Updating ...', :update
  1032. bt.call "#{cd} #{dir} && (git fetch #{progress} 2>&1 && git checkout -q #{branch} 2>&1 && git merge --ff-only origin/#{branch} 2>&1 && #{subm})", name, :update, nil
  1033. else
  1034. [true, skip]
  1035. end
  1036. end
  1037. else
  1038. d = esc dir.sub(%r{[\\/]+$}, '')
  1039. log.call name, 'Installing ...', :install
  1040. bt.call "git clone #{progress} --recursive #{uri} -b #{branch} #{d} 2>&1", name, :install, proc {
  1041. FileUtils.rm_rf dir
  1042. }
  1043. end
  1044. mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
  1045. log.call name, result, ok
  1046. end
  1047. } if running
  1048. end
  1049. end
  1050. threads.each { |t| t.join rescue nil }
  1051. logh.call
  1052. refresh.kill if refresh
  1053. watcher.kill
  1054. EOF
  1055. endfunction
  1056. function! s:shellesc(arg)
  1057. return '"'.substitute(a:arg, '"', '\\"', 'g').'"'
  1058. endfunction
  1059. function! s:glob_dir(path)
  1060. return map(filter(s:lines(globpath(a:path, '**')), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  1061. endfunction
  1062. function! s:progress_bar(line, bar, total)
  1063. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  1064. endfunction
  1065. function! s:compare_git_uri(a, b)
  1066. let a = substitute(a:a, 'git:\{1,2}@', '', '')
  1067. let b = substitute(a:b, 'git:\{1,2}@', '', '')
  1068. return a ==# b
  1069. endfunction
  1070. function! s:format_message(bullet, name, message)
  1071. if a:bullet != 'x'
  1072. return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
  1073. else
  1074. let lines = map(s:lines(a:message), '" ".v:val')
  1075. return extend([printf('x %s:', a:name)], lines)
  1076. endif
  1077. endfunction
  1078. function! s:with_cd(cmd, dir)
  1079. return (s:is_win ? 'cd /d ' : 'cd ').s:esc(a:dir).' && '.a:cmd
  1080. endfunction
  1081. function! s:system(cmd, ...)
  1082. try
  1083. let sh = &shell
  1084. if !s:is_win
  1085. set shell=sh
  1086. endif
  1087. let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
  1088. return system(s:is_win ? '('.cmd.')' : cmd)
  1089. finally
  1090. let &shell = sh
  1091. endtry
  1092. endfunction
  1093. function! s:system_chomp(...)
  1094. let ret = call('s:system', a:000)
  1095. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  1096. endfunction
  1097. function! s:git_valid(spec, check_branch)
  1098. let ret = 1
  1099. let msg = 'OK'
  1100. if isdirectory(a:spec.dir)
  1101. let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url', a:spec.dir))
  1102. let remote = result[-1]
  1103. if v:shell_error
  1104. let msg = join([remote, 'PlugClean required.'], "\n")
  1105. let ret = 0
  1106. elseif !s:compare_git_uri(remote, a:spec.uri)
  1107. let msg = join(['Invalid URI: '.remote,
  1108. \ 'Expected: '.a:spec.uri,
  1109. \ 'PlugClean required.'], "\n")
  1110. let ret = 0
  1111. elseif a:check_branch
  1112. let branch = result[0]
  1113. if a:spec.branch !=# branch
  1114. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
  1115. if a:spec.branch !=# tag
  1116. let msg = printf('Invalid branch/tag: %s (expected: %s). Try PlugUpdate.',
  1117. \ (empty(tag) ? branch : tag), a:spec.branch)
  1118. let ret = 0
  1119. endif
  1120. endif
  1121. endif
  1122. else
  1123. let msg = 'Not found'
  1124. let ret = 0
  1125. endif
  1126. return [ret, msg]
  1127. endfunction
  1128. function! s:clean(force)
  1129. call s:prepare()
  1130. call append(0, 'Searching for unused plugins in '.g:plug_home)
  1131. call append(1, '')
  1132. " List of valid directories
  1133. let dirs = []
  1134. let [cnt, total] = [0, len(g:plugs)]
  1135. for [name, spec] in items(g:plugs)
  1136. if !s:is_managed(name) || s:git_valid(spec, 0)[0]
  1137. call add(dirs, spec.dir)
  1138. endif
  1139. let cnt += 1
  1140. call s:progress_bar(2, repeat('=', cnt), total)
  1141. normal! 2G
  1142. redraw
  1143. endfor
  1144. let allowed = {}
  1145. for dir in dirs
  1146. let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
  1147. let allowed[dir] = 1
  1148. for child in s:glob_dir(dir)
  1149. let allowed[child] = 1
  1150. endfor
  1151. endfor
  1152. let todo = []
  1153. let found = sort(s:glob_dir(g:plug_home))
  1154. while !empty(found)
  1155. let f = remove(found, 0)
  1156. if !has_key(allowed, f) && isdirectory(f)
  1157. call add(todo, f)
  1158. call append(line('$'), '- ' . f)
  1159. let found = filter(found, 'stridx(v:val, f) != 0')
  1160. end
  1161. endwhile
  1162. normal! G
  1163. redraw
  1164. if empty(todo)
  1165. call append(line('$'), 'Already clean.')
  1166. else
  1167. call inputsave()
  1168. let yes = a:force || (input('Proceed? (y/N) ') =~? '^y')
  1169. call inputrestore()
  1170. if yes
  1171. for dir in todo
  1172. if isdirectory(dir)
  1173. call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(dir))
  1174. endif
  1175. endfor
  1176. call append(line('$'), 'Removed.')
  1177. else
  1178. call append(line('$'), 'Cancelled.')
  1179. endif
  1180. endif
  1181. normal! G
  1182. endfunction
  1183. function! s:upgrade()
  1184. let new = s:me . '.new'
  1185. echo 'Downloading '. s:plug_src
  1186. redraw
  1187. try
  1188. if executable('curl')
  1189. let output = s:system(printf('curl -fLo %s %s', s:shellesc(new), s:plug_src))
  1190. if v:shell_error
  1191. throw get(s:lines(output), -1, v:shell_error)
  1192. endif
  1193. elseif has('ruby')
  1194. call s:upgrade_using_ruby(new)
  1195. else
  1196. return s:err('curl executable or ruby support not found')
  1197. endif
  1198. catch
  1199. return s:err('Error upgrading vim-plug: '. v:exception)
  1200. endtry
  1201. if readfile(s:me) ==# readfile(new)
  1202. echo 'vim-plug is already up-to-date'
  1203. silent! call delete(new)
  1204. return 0
  1205. else
  1206. call rename(s:me, s:me . '.old')
  1207. call rename(new, s:me)
  1208. unlet g:loaded_plug
  1209. echo 'vim-plug has been upgraded'
  1210. return 1
  1211. endif
  1212. endfunction
  1213. function! s:upgrade_using_ruby(new)
  1214. ruby << EOF
  1215. require 'open-uri'
  1216. File.open(VIM::evaluate('a:new'), 'w') do |f|
  1217. f << open(VIM::evaluate('s:plug_src')).read
  1218. end
  1219. EOF
  1220. endfunction
  1221. function! s:upgrade_specs()
  1222. for spec in values(g:plugs)
  1223. let spec.frozen = get(spec, 'frozen', 0)
  1224. endfor
  1225. endfunction
  1226. function! s:status()
  1227. call s:prepare()
  1228. call append(0, 'Checking plugins')
  1229. call append(1, '')
  1230. let ecnt = 0
  1231. let unloaded = 0
  1232. let [cnt, total] = [0, len(g:plugs)]
  1233. for [name, spec] in items(g:plugs)
  1234. if has_key(spec, 'uri')
  1235. if isdirectory(spec.dir)
  1236. let [valid, msg] = s:git_valid(spec, 1)
  1237. else
  1238. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  1239. endif
  1240. else
  1241. if isdirectory(spec.dir)
  1242. let [valid, msg] = [1, 'OK']
  1243. else
  1244. let [valid, msg] = [0, 'Not found.']
  1245. endif
  1246. endif
  1247. let cnt += 1
  1248. let ecnt += !valid
  1249. " `s:loaded` entry can be missing if PlugUpgraded
  1250. if valid && get(s:loaded, name, -1) == 0
  1251. let unloaded = 1
  1252. let msg .= ' (not loaded)'
  1253. endif
  1254. call s:progress_bar(2, repeat('=', cnt), total)
  1255. call append(3, s:format_message(valid ? '-' : 'x', name, msg))
  1256. normal! 2G
  1257. redraw
  1258. endfor
  1259. call setline(1, 'Finished. '.ecnt.' error(s).')
  1260. normal! gg
  1261. setlocal nomodifiable
  1262. if unloaded
  1263. echo "Press 'L' on each line to load plugin, or 'U' to update"
  1264. nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1265. xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1266. end
  1267. endfunction
  1268. function! s:extract_name(str, prefix, suffix)
  1269. return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
  1270. endfunction
  1271. function! s:status_load(lnum)
  1272. let line = getline(a:lnum)
  1273. let name = s:extract_name(line, '-', '(not loaded)')
  1274. if !empty(name)
  1275. call plug#load(name)
  1276. setlocal modifiable
  1277. call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
  1278. setlocal nomodifiable
  1279. endif
  1280. endfunction
  1281. function! s:status_update() range
  1282. let lines = getline(a:firstline, a:lastline)
  1283. let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
  1284. if !empty(names)
  1285. echo
  1286. execute 'PlugUpdate' join(names)
  1287. endif
  1288. endfunction
  1289. function! s:is_preview_window_open()
  1290. silent! wincmd P
  1291. if &previewwindow
  1292. wincmd p
  1293. return 1
  1294. endif
  1295. return 0
  1296. endfunction
  1297. function! s:find_name(lnum)
  1298. for lnum in reverse(range(1, a:lnum))
  1299. let line = getline(lnum)
  1300. if empty(line)
  1301. return ''
  1302. endif
  1303. let name = s:extract_name(line, '-', '')
  1304. if !empty(name)
  1305. return name
  1306. endif
  1307. endfor
  1308. return ''
  1309. endfunction
  1310. function! s:preview_commit()
  1311. if b:plug_preview < 0
  1312. let b:plug_preview = !s:is_preview_window_open()
  1313. endif
  1314. let sha = matchstr(getline('.'), '\(^ \)\@<=[0-9a-z]\{7}')
  1315. if empty(sha)
  1316. return
  1317. endif
  1318. let name = s:find_name(line('.'))
  1319. if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
  1320. return
  1321. endif
  1322. execute 'pedit' sha
  1323. wincmd P
  1324. setlocal filetype=git buftype=nofile nobuflisted
  1325. execute 'silent read !cd' s:esc(g:plugs[name].dir) '&& git show' sha
  1326. normal! gg"_dd
  1327. wincmd p
  1328. endfunction
  1329. function! s:section(flags)
  1330. call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
  1331. endfunction
  1332. function! s:diff()
  1333. call s:prepare()
  1334. call append(0, 'Collecting updated changes ...')
  1335. normal! gg
  1336. redraw
  1337. let cnt = 0
  1338. for [k, v] in items(g:plugs)
  1339. if !isdirectory(v.dir) || !s:is_managed(k)
  1340. continue
  1341. endif
  1342. let diff = s:system_chomp('git log --pretty=format:"%h %s (%cr)" "HEAD...HEAD@{1}"', v.dir)
  1343. if !empty(diff)
  1344. call append(1, '')
  1345. call append(2, '- '.k.':')
  1346. call append(3, map(s:lines(diff), '" ". v:val'))
  1347. let cnt += 1
  1348. normal! gg
  1349. redraw
  1350. endif
  1351. endfor
  1352. call setline(1, cnt == 0 ? 'No updates.' : 'Last update:')
  1353. nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
  1354. nnoremap <silent> <buffer> X :call <SID>revert()<cr>
  1355. normal! gg
  1356. setlocal nomodifiable
  1357. if cnt > 0
  1358. echo "Press 'X' on each block to revert the update"
  1359. endif
  1360. endfunction
  1361. function! s:revert()
  1362. let name = s:find_name(line('.'))
  1363. if empty(name) || !has_key(g:plugs, name) ||
  1364. \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
  1365. return
  1366. endif
  1367. call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir)
  1368. setlocal modifiable
  1369. normal! "_dap
  1370. setlocal nomodifiable
  1371. echo 'Reverted.'
  1372. endfunction
  1373. function! s:snapshot(...) abort
  1374. let home = get(s:, 'plug_home_org', g:plug_home)
  1375. let [type, var, header] = s:is_win ?
  1376. \ ['dosbatch', '%PLUG_HOME%',
  1377. \ ['@echo off', ':: Generated by vim-plug', ':: '.strftime("%c"), '',
  1378. \ ':: Make sure to PlugUpdate first', '', 'set PLUG_HOME='.s:esc(home)]] :
  1379. \ ['sh', '$PLUG_HOME',
  1380. \ ['#!/bin/sh', '# Generated by vim-plug', '# '.strftime("%c"), '',
  1381. \ 'vim +PlugUpdate +qa', '', 'PLUG_HOME='.s:esc(home)]]
  1382. call s:prepare()
  1383. execute 'setf' type
  1384. call append(0, header)
  1385. call append('$', '')
  1386. 1
  1387. redraw
  1388. let dirs = sort(map(values(filter(copy(g:plugs),
  1389. \'has_key(v:val, "uri") && isdirectory(v:val.dir)')), 'v:val.dir'))
  1390. let anchor = line('$') - 1
  1391. for dir in reverse(dirs)
  1392. let sha = s:system_chomp('git rev-parse --short HEAD', dir)
  1393. if !empty(sha)
  1394. call append(anchor, printf('cd %s && git reset --hard %s',
  1395. \ substitute(dir, '^'.g:plug_home, var, ''), sha))
  1396. redraw
  1397. endif
  1398. endfor
  1399. if a:0 > 0
  1400. let fn = s:esc(expand(a:1))
  1401. call writefile(getline(1, '$'), fn)
  1402. if !s:is_win | call s:system('chmod +x ' . fn) | endif
  1403. echo 'Saved to '.a:1
  1404. silent execute 'e' fn
  1405. endif
  1406. endfunction
  1407. function! s:split_rtp()
  1408. return split(&rtp, '\\\@<!,')
  1409. endfunction
  1410. let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
  1411. let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
  1412. if exists('g:plugs')
  1413. let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
  1414. call s:upgrade_specs()
  1415. call s:define_commands()
  1416. endif
  1417. let &cpo = s:cpo_save
  1418. unlet s:cpo_save