plug.vim 41 KB

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