plug.vim 41 KB

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