plug.vim 42 KB

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