plug.vim 37 KB

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