plug.vim 42 KB

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