plug.vim 37 KB

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