plug.vim 41 KB

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