plug.vim 41 KB

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