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