plug.vim 43 KB

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