plug.vim 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  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 || v:version == 702 && has('patch374'))
  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, 'escape(v:val, ",")'), ',')
  292. \ . ','.s:middle.','
  293. \ . join(map(afters, 'escape(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.tag = 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> o
  540. silent! unmap <buffer> X
  541. setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap cursorline modifiable
  542. setf vim-plug
  543. call s:syntax()
  544. endfunction
  545. function! s:assign_name()
  546. " Assign buffer name
  547. let prefix = '[Plugins]'
  548. let name = prefix
  549. let idx = 2
  550. while bufexists(name)
  551. let name = printf('%s (%s)', prefix, idx)
  552. let idx = idx + 1
  553. endwhile
  554. silent! execute 'f' fnameescape(name)
  555. endfunction
  556. function! s:do(pull, force, todo)
  557. for [name, spec] in items(a:todo)
  558. if !isdirectory(spec.dir)
  559. continue
  560. endif
  561. let installed = has_key(s:update.new, name)
  562. let updated = installed ? 0 :
  563. \ (a:pull && !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', spec.dir)))
  564. if a:force || installed || updated
  565. execute 'cd' s:esc(spec.dir)
  566. call append(3, '- Post-update hook for '. name .' ... ')
  567. let type = type(spec.do)
  568. if type == s:TYPE.string
  569. try
  570. " FIXME: Escaping is incomplete. We could use shellescape with eval,
  571. " but it won't work on Windows.
  572. let g:_plug_do = '!'.escape(spec.do, '#!%')
  573. execute "normal! :execute g:_plug_do\<cr>\<cr>"
  574. finally
  575. let result = v:shell_error ? ('Exit status: '.v:shell_error) : 'Done!'
  576. unlet g:_plug_do
  577. endtry
  578. elseif type == s:TYPE.funcref
  579. try
  580. let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
  581. call spec.do({ 'name': name, 'status': status, 'force': a:force })
  582. let result = 'Done!'
  583. catch
  584. let result = 'Error: ' . v:exception
  585. endtry
  586. else
  587. let result = 'Error: Invalid type!'
  588. endif
  589. call setline(4, getline(4) . result)
  590. cd -
  591. endif
  592. endfor
  593. endfunction
  594. function! s:finish(pull)
  595. let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
  596. if new_frozen
  597. let s = new_frozen > 1 ? 's' : ''
  598. call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
  599. endif
  600. call append(3, '- Finishing ... ')
  601. redraw
  602. call plug#helptags()
  603. call plug#end()
  604. call setline(4, getline(4) . 'Done!')
  605. redraw
  606. let msgs = []
  607. if !empty(s:update.errors)
  608. call add(msgs, "Press 'R' to retry.")
  609. endif
  610. if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
  611. \ "v:val =~ '^- ' && stridx(v:val, 'Already up-to-date') < 0"))
  612. call add(msgs, "Press 'D' to see the updated changes.")
  613. endif
  614. echo join(msgs, ' ')
  615. endfunction
  616. function! s:retry()
  617. if empty(s:update.errors)
  618. return
  619. endif
  620. call s:update_impl(s:update.pull, s:update.force,
  621. \ extend(copy(s:update.errors), [s:update.threads]))
  622. endfunction
  623. function! s:is_managed(name)
  624. return has_key(g:plugs[a:name], 'uri')
  625. endfunction
  626. function! s:names(...)
  627. return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
  628. endfunction
  629. function! s:update_impl(pull, force, args) abort
  630. let args = copy(a:args)
  631. let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
  632. \ remove(args, -1) : get(g:, 'plug_threads', 16)
  633. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  634. let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
  635. \ filter(managed, 'index(args, v:key) >= 0')
  636. if empty(todo)
  637. echohl WarningMsg
  638. echo 'No plugin to '. (a:pull ? 'update' : 'install') . '.'
  639. echohl None
  640. return
  641. endif
  642. if !s:is_win && s:git_version_requirement(2, 3)
  643. let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : ''
  644. let $GIT_TERMINAL_PROMPT = 0
  645. for plug in values(todo)
  646. let plug.uri = substitute(plug.uri,
  647. \ '^https://git::@github\.com', 'https://github.com', '')
  648. endfor
  649. endif
  650. if !isdirectory(g:plug_home)
  651. try
  652. call mkdir(g:plug_home, 'p')
  653. catch
  654. return s:err(printf('Invalid plug directory: %s. '.
  655. \ 'Try to call plug#begin with a valid directory', g:plug_home))
  656. endtry
  657. endif
  658. let s:update = {
  659. \ 'start': reltime(),
  660. \ 'all': todo,
  661. \ 'todo': copy(todo),
  662. \ 'errors': [],
  663. \ 'pull': a:pull,
  664. \ 'force': a:force,
  665. \ 'new': {},
  666. \ 'threads': (s:ruby || s:nvim) ? min([len(todo), threads]) : 1,
  667. \ 'bar': '',
  668. \ 'fin': 0
  669. \ }
  670. call s:prepare()
  671. call append(0, ['', ''])
  672. normal! 2G
  673. if s:ruby && s:update.threads > 1
  674. try
  675. let imd = &imd
  676. if s:mac_gui
  677. set noimd
  678. endif
  679. call s:update_ruby()
  680. catch
  681. let lines = getline(4, '$')
  682. let printed = {}
  683. silent! 4,$d _
  684. for line in lines
  685. let name = s:extract_name(line, '.', '')
  686. if empty(name) || !has_key(printed, name)
  687. call append('$', line)
  688. if !empty(name)
  689. let printed[name] = 1
  690. if line[0] == 'x' && index(s:update.errors, name) < 0
  691. call add(s:update.errors, name)
  692. end
  693. endif
  694. endif
  695. endfor
  696. finally
  697. let &imd = imd
  698. call s:update_finish()
  699. endtry
  700. else
  701. call s:update_vim()
  702. endif
  703. endfunction
  704. function! s:update_finish()
  705. if exists('s:git_terminal_prompt')
  706. let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt
  707. endif
  708. if s:switch_in()
  709. call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'has_key(v:val, "do")'))
  710. call s:finish(s:update.pull)
  711. call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
  712. call s:switch_out('normal! gg')
  713. endif
  714. endfunction
  715. function! s:job_abort()
  716. if !s:nvim || !exists('s:jobs')
  717. return
  718. endif
  719. augroup PlugJobControl
  720. autocmd!
  721. augroup END
  722. for [name, j] in items(s:jobs)
  723. silent! call jobstop(j.jobid)
  724. if j.new
  725. call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir))
  726. endif
  727. endfor
  728. let s:jobs = {}
  729. endfunction
  730. function! s:job_handler(name) abort
  731. if !s:plug_window_exists() " plug window closed
  732. return s:job_abort()
  733. endif
  734. if !has_key(s:jobs, a:name)
  735. return
  736. endif
  737. let job = s:jobs[a:name]
  738. if v:job_data[1] == 'exit'
  739. let job.running = 0
  740. if s:lastline(job.result) ==# 'Error'
  741. let job.error = 1
  742. let job.result = substitute(job.result, "Error[\r\n]$", '', '')
  743. endif
  744. call s:reap(a:name)
  745. call s:tick()
  746. else
  747. let job.result .= s:to_s(v:job_data[2])
  748. " To reduce the number of buffer updates
  749. let job.tick = get(job, 'tick', -1) + 1
  750. if job.tick % len(s:jobs) == 0
  751. call s:log(job.new ? '+' : '*', a:name, job.result)
  752. endif
  753. endif
  754. endfunction
  755. function! s:spawn(name, cmd, opts)
  756. let job = { 'running': 1, 'new': get(a:opts, 'new', 0),
  757. \ 'error': 0, 'result': '' }
  758. let s:jobs[a:name] = job
  759. if s:nvim
  760. let x = jobstart(a:name, 'sh', ['-c',
  761. \ (has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd)
  762. \ . ' || echo Error'])
  763. if x > 0
  764. let job.jobid = x
  765. augroup PlugJobControl
  766. execute 'autocmd JobActivity' a:name printf('call s:job_handler(%s)', string(a:name))
  767. augroup END
  768. else
  769. let job.running = 0
  770. let job.error = 1
  771. let job.result = x < 0 ? 'sh is not executable' :
  772. \ 'Invalid arguments (or job table is full)'
  773. endif
  774. else
  775. let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd]
  776. let job.result = call('s:system', params)
  777. let job.error = v:shell_error != 0
  778. let job.running = 0
  779. endif
  780. endfunction
  781. function! s:reap(name)
  782. if s:nvim
  783. silent! execute 'autocmd! PlugJobControl JobActivity' a:name
  784. endif
  785. let job = s:jobs[a:name]
  786. if job.error
  787. call add(s:update.errors, a:name)
  788. elseif get(job, 'new', 0)
  789. let s:update.new[a:name] = 1
  790. endif
  791. let s:update.bar .= job.error ? 'x' : '='
  792. call s:log(job.error ? 'x' : '-', a:name, job.result)
  793. call s:bar()
  794. call remove(s:jobs, a:name)
  795. endfunction
  796. function! s:bar()
  797. if s:switch_in()
  798. let total = len(s:update.all)
  799. call setline(1, (s:update.pull ? 'Updating' : 'Installing').
  800. \ ' plugins ('.len(s:update.bar).'/'.total.')')
  801. call s:progress_bar(2, s:update.bar, total)
  802. call s:switch_out()
  803. endif
  804. endfunction
  805. function! s:logpos(name)
  806. for i in range(1, line('$'))
  807. if getline(i) =~# '^[-+x*] '.a:name.':'
  808. return i
  809. endif
  810. endfor
  811. return 0
  812. endfunction
  813. function! s:log(bullet, name, lines)
  814. if s:switch_in()
  815. let pos = s:logpos(a:name)
  816. if pos > 0
  817. execute pos 'd _'
  818. if pos > winheight('.')
  819. let pos = 4
  820. endif
  821. else
  822. let pos = 4
  823. endif
  824. call append(pos - 1, s:format_message(a:bullet, a:name, a:lines))
  825. call s:switch_out()
  826. endif
  827. endfunction
  828. function! s:update_vim()
  829. let s:jobs = {}
  830. call s:bar()
  831. call s:tick()
  832. endfunction
  833. function! s:tick()
  834. let pull = s:update.pull
  835. let prog = s:progress_opt(s:nvim)
  836. while 1 " Without TCO, Vim stack is bound to explode
  837. if empty(s:update.todo)
  838. if empty(s:jobs) && !s:update.fin
  839. let s:update.fin = 1
  840. call s:update_finish()
  841. endif
  842. return
  843. endif
  844. let name = keys(s:update.todo)[0]
  845. let spec = remove(s:update.todo, name)
  846. let new = !isdirectory(spec.dir)
  847. call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
  848. redraw
  849. let checkout = s:shellesc(has_key(spec, 'tag') ? spec.tag : spec.branch)
  850. let merge = s:shellesc(has_key(spec, 'tag') ? spec.tag : 'origin/'.spec.branch)
  851. if !new
  852. let [valid, msg] = s:git_valid(spec, 0)
  853. if valid
  854. if pull
  855. call s:spawn(name,
  856. \ printf('(git fetch %s 2>&1 && git checkout -q %s 2>&1 && git merge --ff-only %s 2>&1 && git submodule update --init --recursive 2>&1)',
  857. \ prog, checkout, merge), { 'dir': spec.dir })
  858. else
  859. let s:jobs[name] = { 'running': 0, 'result': 'Already installed', 'error': 0 }
  860. endif
  861. else
  862. let s:jobs[name] = { 'running': 0, 'result': msg, 'error': 1 }
  863. endif
  864. else
  865. call s:spawn(name,
  866. \ printf('git clone %s --recursive %s -b %s %s 2>&1',
  867. \ prog,
  868. \ s:shellesc(spec.uri),
  869. \ checkout,
  870. \ s:shellesc(s:trim(spec.dir))), { 'new': 1 })
  871. endif
  872. if !s:jobs[name].running
  873. call s:reap(name)
  874. endif
  875. if len(s:jobs) >= s:update.threads
  876. break
  877. endif
  878. endwhile
  879. endfunction
  880. function! s:update_ruby()
  881. ruby << EOF
  882. module PlugStream
  883. SEP = ["\r", "\n", nil]
  884. def get_line
  885. buffer = ''
  886. loop do
  887. char = readchar rescue return
  888. if SEP.include? char.chr
  889. buffer << $/
  890. break
  891. else
  892. buffer << char
  893. end
  894. end
  895. buffer
  896. end
  897. end unless defined?(PlugStream)
  898. def esc arg
  899. %["#{arg.gsub('"', '\"')}"]
  900. end
  901. def killall pid
  902. pids = [pid]
  903. unless `which pgrep 2> /dev/null`.empty?
  904. children = pids
  905. until children.empty?
  906. children = children.map { |pid|
  907. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  908. }.flatten
  909. pids += children
  910. end
  911. end
  912. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  913. end
  914. require 'thread'
  915. require 'fileutils'
  916. require 'timeout'
  917. running = true
  918. iswin = VIM::evaluate('s:is_win').to_i == 1
  919. pull = VIM::evaluate('s:update.pull').to_i == 1
  920. base = VIM::evaluate('g:plug_home')
  921. all = VIM::evaluate('s:update.todo')
  922. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  923. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  924. nthr = VIM::evaluate('s:update.threads').to_i
  925. maxy = VIM::evaluate('winheight(".")').to_i
  926. cd = iswin ? 'cd /d' : 'cd'
  927. tot = VIM::evaluate('len(s:update.todo)') || 0
  928. bar = ''
  929. skip = 'Already installed'
  930. mtx = Mutex.new
  931. take1 = proc { mtx.synchronize { running && all.shift } }
  932. logh = proc {
  933. cnt = bar.length
  934. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  935. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  936. VIM::command('normal! 2G')
  937. VIM::command('redraw') unless iswin
  938. }
  939. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  940. log = proc { |name, result, type|
  941. mtx.synchronize do
  942. ing = ![true, false].include?(type)
  943. bar += type ? '=' : 'x' unless ing
  944. b = case type
  945. when :install then '+' when :update then '*'
  946. when true, nil then '-' else
  947. VIM::command("call add(s:update.errors, '#{name}')")
  948. 'x'
  949. end
  950. result =
  951. if type || type.nil?
  952. ["#{b} #{name}: #{result.lines.to_a.last}"]
  953. elsif result =~ /^Interrupted|^Timeout/
  954. ["#{b} #{name}: #{result}"]
  955. else
  956. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  957. end
  958. if lnum = where.call(name)
  959. $curbuf.delete lnum
  960. lnum = 4 if ing && lnum > maxy
  961. end
  962. result.each_with_index do |line, offset|
  963. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  964. end
  965. logh.call
  966. end
  967. }
  968. bt = proc { |cmd, name, type, cleanup|
  969. tried = timeout = 0
  970. begin
  971. tried += 1
  972. timeout += limit
  973. fd = nil
  974. data = ''
  975. if iswin
  976. Timeout::timeout(timeout) do
  977. tmp = VIM::evaluate('tempname()')
  978. system("#{cmd} > #{tmp}")
  979. data = File.read(tmp).chomp
  980. File.unlink tmp rescue nil
  981. end
  982. else
  983. fd = IO.popen(cmd).extend(PlugStream)
  984. first_line = true
  985. log_prob = 1.0 / nthr
  986. while line = Timeout::timeout(timeout) { fd.get_line }
  987. data << line
  988. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  989. first_line = false
  990. end
  991. fd.close
  992. end
  993. [$? == 0, data.chomp]
  994. rescue Timeout::Error, Interrupt => e
  995. if fd && !fd.closed?
  996. killall fd.pid
  997. fd.close
  998. end
  999. cleanup.call if cleanup
  1000. if e.is_a?(Timeout::Error) && tried < tries
  1001. 3.downto(1) do |countdown|
  1002. s = countdown > 1 ? 's' : ''
  1003. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  1004. sleep 1
  1005. end
  1006. log.call name, 'Retrying ...', type
  1007. retry
  1008. end
  1009. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  1010. end
  1011. }
  1012. main = Thread.current
  1013. threads = []
  1014. watcher = Thread.new {
  1015. while VIM::evaluate('getchar(1)')
  1016. sleep 0.1
  1017. end
  1018. mtx.synchronize do
  1019. running = false
  1020. threads.each { |t| t.raise Interrupt }
  1021. end
  1022. threads.each { |t| t.join rescue nil }
  1023. main.kill
  1024. }
  1025. refresh = Thread.new {
  1026. while true
  1027. mtx.synchronize do
  1028. break unless running
  1029. VIM::command('noautocmd normal! a')
  1030. end
  1031. sleep 0.2
  1032. end
  1033. } if VIM::evaluate('s:mac_gui') == 1
  1034. progress = VIM::evaluate('s:progress_opt(1)')
  1035. nthr.times do
  1036. mtx.synchronize do
  1037. threads << Thread.new {
  1038. while pair = take1.call
  1039. name = pair.first
  1040. dir, uri, branch, tag = pair.last.values_at *%w[dir uri branch tag]
  1041. checkout = esc(tag ? tag : branch)
  1042. merge = esc(tag ? tag : "origin/#{branch}")
  1043. subm = "git submodule update --init --recursive 2>&1"
  1044. exists = File.directory? dir
  1045. ok, result =
  1046. if exists
  1047. dir = esc dir
  1048. ret, data = bt.call "#{cd} #{dir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil, nil
  1049. current_uri = data.lines.to_a.last
  1050. if !ret
  1051. if data =~ /^Interrupted|^Timeout/
  1052. [false, data]
  1053. else
  1054. [false, [data.chomp, "PlugClean required."].join($/)]
  1055. end
  1056. elsif current_uri.sub(/git::?@/, '') != uri.sub(/git::?@/, '')
  1057. [false, ["Invalid URI: #{current_uri}",
  1058. "Expected: #{uri}",
  1059. "PlugClean required."].join($/)]
  1060. else
  1061. if pull
  1062. log.call name, 'Updating ...', :update
  1063. bt.call "#{cd} #{dir} && (git fetch #{progress} 2>&1 && git checkout -q #{checkout} 2>&1 && git merge --ff-only #{merge} 2>&1 && #{subm})", name, :update, nil
  1064. else
  1065. [true, skip]
  1066. end
  1067. end
  1068. else
  1069. d = esc dir.sub(%r{[\\/]+$}, '')
  1070. log.call name, 'Installing ...', :install
  1071. bt.call "git clone #{progress} --recursive #{uri} -b #{checkout} #{d} 2>&1", name, :install, proc {
  1072. FileUtils.rm_rf dir
  1073. }
  1074. end
  1075. mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
  1076. log.call name, result, ok
  1077. end
  1078. } if running
  1079. end
  1080. end
  1081. threads.each { |t| t.join rescue nil }
  1082. logh.call
  1083. refresh.kill if refresh
  1084. watcher.kill
  1085. EOF
  1086. endfunction
  1087. function! s:shellesc(arg)
  1088. return '"'.substitute(a:arg, '"', '\\"', 'g').'"'
  1089. endfunction
  1090. function! s:glob_dir(path)
  1091. return map(filter(s:lines(globpath(a:path, '**')), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  1092. endfunction
  1093. function! s:progress_bar(line, bar, total)
  1094. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  1095. endfunction
  1096. function! s:compare_git_uri(a, b)
  1097. let a = substitute(a:a, 'git:\{1,2}@', '', '')
  1098. let b = substitute(a:b, 'git:\{1,2}@', '', '')
  1099. return a ==# b
  1100. endfunction
  1101. function! s:format_message(bullet, name, message)
  1102. if a:bullet != 'x'
  1103. return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
  1104. else
  1105. let lines = map(s:lines(a:message), '" ".v:val')
  1106. return extend([printf('x %s:', a:name)], lines)
  1107. endif
  1108. endfunction
  1109. function! s:with_cd(cmd, dir)
  1110. return (s:is_win ? 'cd /d ' : 'cd ').s:esc(a:dir).' && '.a:cmd
  1111. endfunction
  1112. function! s:system(cmd, ...)
  1113. try
  1114. let sh = &shell
  1115. if !s:is_win
  1116. set shell=sh
  1117. endif
  1118. let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
  1119. return system(s:is_win ? '('.cmd.')' : cmd)
  1120. finally
  1121. let &shell = sh
  1122. endtry
  1123. endfunction
  1124. function! s:system_chomp(...)
  1125. let ret = call('s:system', a:000)
  1126. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  1127. endfunction
  1128. function! s:git_valid(spec, check_branch)
  1129. let ret = 1
  1130. let msg = 'OK'
  1131. if isdirectory(a:spec.dir)
  1132. let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url', a:spec.dir))
  1133. let remote = result[-1]
  1134. if v:shell_error
  1135. let msg = join([remote, 'PlugClean required.'], "\n")
  1136. let ret = 0
  1137. elseif !s:compare_git_uri(remote, a:spec.uri)
  1138. let msg = join(['Invalid URI: '.remote,
  1139. \ 'Expected: '.a:spec.uri,
  1140. \ 'PlugClean required.'], "\n")
  1141. let ret = 0
  1142. elseif a:check_branch
  1143. let branch = result[0]
  1144. " Check tag
  1145. if has_key(a:spec, 'tag')
  1146. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
  1147. if a:spec.tag !=# tag
  1148. let msg = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.',
  1149. \ (empty(tag) ? 'N/A' : tag), a:spec.tag)
  1150. let ret = 0
  1151. endif
  1152. " Check branch
  1153. elseif a:spec.branch !=# branch
  1154. let msg = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.',
  1155. \ branch, a:spec.branch)
  1156. let ret = 0
  1157. endif
  1158. endif
  1159. else
  1160. let msg = 'Not found'
  1161. let ret = 0
  1162. endif
  1163. return [ret, msg]
  1164. endfunction
  1165. function! s:clean(force)
  1166. call s:prepare()
  1167. call append(0, 'Searching for unused plugins in '.g:plug_home)
  1168. call append(1, '')
  1169. " List of valid directories
  1170. let dirs = []
  1171. let [cnt, total] = [0, len(g:plugs)]
  1172. for [name, spec] in items(g:plugs)
  1173. if !s:is_managed(name) || s:git_valid(spec, 0)[0]
  1174. call add(dirs, spec.dir)
  1175. endif
  1176. let cnt += 1
  1177. call s:progress_bar(2, repeat('=', cnt), total)
  1178. normal! 2G
  1179. redraw
  1180. endfor
  1181. let allowed = {}
  1182. for dir in dirs
  1183. let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
  1184. let allowed[dir] = 1
  1185. for child in s:glob_dir(dir)
  1186. let allowed[child] = 1
  1187. endfor
  1188. endfor
  1189. let todo = []
  1190. let found = sort(s:glob_dir(g:plug_home))
  1191. while !empty(found)
  1192. let f = remove(found, 0)
  1193. if !has_key(allowed, f) && isdirectory(f)
  1194. call add(todo, f)
  1195. call append(line('$'), '- ' . f)
  1196. let found = filter(found, 'stridx(v:val, f) != 0')
  1197. end
  1198. endwhile
  1199. normal! G
  1200. redraw
  1201. if empty(todo)
  1202. call append(line('$'), 'Already clean.')
  1203. else
  1204. call inputsave()
  1205. let yes = a:force || (input('Proceed? (y/N) ') =~? '^y')
  1206. call inputrestore()
  1207. if yes
  1208. for dir in todo
  1209. if isdirectory(dir)
  1210. call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(dir))
  1211. endif
  1212. endfor
  1213. call append(line('$'), 'Removed.')
  1214. else
  1215. call append(line('$'), 'Cancelled.')
  1216. endif
  1217. endif
  1218. normal! G
  1219. endfunction
  1220. function! s:upgrade()
  1221. let new = s:me . '.new'
  1222. echo 'Downloading '. s:plug_src
  1223. redraw
  1224. try
  1225. if executable('curl')
  1226. let output = s:system(printf('curl -fLo %s %s', s:shellesc(new), s:plug_src))
  1227. if v:shell_error
  1228. throw get(s:lines(output), -1, v:shell_error)
  1229. endif
  1230. elseif s:ruby
  1231. call s:upgrade_using_ruby(new)
  1232. else
  1233. return s:err('curl executable or ruby support not found')
  1234. endif
  1235. catch
  1236. return s:err('Error upgrading vim-plug: '. v:exception)
  1237. endtry
  1238. if readfile(s:me) ==# readfile(new)
  1239. echo 'vim-plug is already up-to-date'
  1240. silent! call delete(new)
  1241. return 0
  1242. else
  1243. call rename(s:me, s:me . '.old')
  1244. call rename(new, s:me)
  1245. unlet g:loaded_plug
  1246. echo 'vim-plug has been upgraded'
  1247. return 1
  1248. endif
  1249. endfunction
  1250. function! s:upgrade_using_ruby(new)
  1251. ruby << EOF
  1252. require 'open-uri'
  1253. File.open(VIM::evaluate('a:new'), 'w') do |f|
  1254. f << open(VIM::evaluate('s:plug_src')).read
  1255. end
  1256. EOF
  1257. endfunction
  1258. function! s:upgrade_specs()
  1259. for spec in values(g:plugs)
  1260. let spec.frozen = get(spec, 'frozen', 0)
  1261. endfor
  1262. endfunction
  1263. function! s:status()
  1264. call s:prepare()
  1265. call append(0, 'Checking plugins')
  1266. call append(1, '')
  1267. let ecnt = 0
  1268. let unloaded = 0
  1269. let [cnt, total] = [0, len(g:plugs)]
  1270. for [name, spec] in items(g:plugs)
  1271. if has_key(spec, 'uri')
  1272. if isdirectory(spec.dir)
  1273. let [valid, msg] = s:git_valid(spec, 1)
  1274. else
  1275. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  1276. endif
  1277. else
  1278. if isdirectory(spec.dir)
  1279. let [valid, msg] = [1, 'OK']
  1280. else
  1281. let [valid, msg] = [0, 'Not found.']
  1282. endif
  1283. endif
  1284. let cnt += 1
  1285. let ecnt += !valid
  1286. " `s:loaded` entry can be missing if PlugUpgraded
  1287. if valid && get(s:loaded, name, -1) == 0
  1288. let unloaded = 1
  1289. let msg .= ' (not loaded)'
  1290. endif
  1291. call s:progress_bar(2, repeat('=', cnt), total)
  1292. call append(3, s:format_message(valid ? '-' : 'x', name, msg))
  1293. normal! 2G
  1294. redraw
  1295. endfor
  1296. call setline(1, 'Finished. '.ecnt.' error(s).')
  1297. normal! gg
  1298. setlocal nomodifiable
  1299. if unloaded
  1300. echo "Press 'L' on each line to load plugin, or 'U' to update"
  1301. nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1302. xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1303. end
  1304. endfunction
  1305. function! s:extract_name(str, prefix, suffix)
  1306. return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
  1307. endfunction
  1308. function! s:status_load(lnum)
  1309. let line = getline(a:lnum)
  1310. let name = s:extract_name(line, '-', '(not loaded)')
  1311. if !empty(name)
  1312. call plug#load(name)
  1313. setlocal modifiable
  1314. call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
  1315. setlocal nomodifiable
  1316. endif
  1317. endfunction
  1318. function! s:status_update() range
  1319. let lines = getline(a:firstline, a:lastline)
  1320. let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
  1321. if !empty(names)
  1322. echo
  1323. execute 'PlugUpdate' join(names)
  1324. endif
  1325. endfunction
  1326. function! s:is_preview_window_open()
  1327. silent! wincmd P
  1328. if &previewwindow
  1329. wincmd p
  1330. return 1
  1331. endif
  1332. return 0
  1333. endfunction
  1334. function! s:find_name(lnum)
  1335. for lnum in reverse(range(1, a:lnum))
  1336. let line = getline(lnum)
  1337. if empty(line)
  1338. return ''
  1339. endif
  1340. let name = s:extract_name(line, '-', '')
  1341. if !empty(name)
  1342. return name
  1343. endif
  1344. endfor
  1345. return ''
  1346. endfunction
  1347. function! s:preview_commit()
  1348. if b:plug_preview < 0
  1349. let b:plug_preview = !s:is_preview_window_open()
  1350. endif
  1351. let sha = matchstr(getline('.'), '\(^ \)\@<=[0-9a-z]\{7}')
  1352. if empty(sha)
  1353. return
  1354. endif
  1355. let name = s:find_name(line('.'))
  1356. if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
  1357. return
  1358. endif
  1359. execute 'pedit' sha
  1360. wincmd P
  1361. setlocal filetype=git buftype=nofile nobuflisted
  1362. execute 'silent read !cd' s:esc(g:plugs[name].dir) '&& git show' sha
  1363. normal! gg"_dd
  1364. wincmd p
  1365. endfunction
  1366. function! s:section(flags)
  1367. call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
  1368. endfunction
  1369. function! s:diff()
  1370. call s:prepare()
  1371. call append(0, 'Collecting updated changes ...')
  1372. normal! gg
  1373. redraw
  1374. let cnt = 0
  1375. for [k, v] in items(g:plugs)
  1376. if !isdirectory(v.dir) || !s:is_managed(k)
  1377. continue
  1378. endif
  1379. let diff = s:system_chomp('git log --pretty=format:"%h %s (%cr)" "HEAD...HEAD@{1}"', v.dir)
  1380. if !empty(diff)
  1381. call append(1, '')
  1382. call append(2, '- '.k.':')
  1383. call append(3, map(s:lines(diff), '" ". v:val'))
  1384. let cnt += 1
  1385. normal! gg
  1386. redraw
  1387. endif
  1388. endfor
  1389. call setline(1, cnt == 0 ? 'No updates.' : 'Last update:')
  1390. nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
  1391. nnoremap <silent> <buffer> o :silent! call <SID>preview_commit()<cr>
  1392. nnoremap <silent> <buffer> X :call <SID>revert()<cr>
  1393. normal! gg
  1394. setlocal nomodifiable
  1395. if cnt > 0
  1396. echo "Press 'X' on each block to revert the update"
  1397. endif
  1398. endfunction
  1399. function! s:revert()
  1400. let name = s:find_name(line('.'))
  1401. if empty(name) || !has_key(g:plugs, name) ||
  1402. \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
  1403. return
  1404. endif
  1405. call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir)
  1406. setlocal modifiable
  1407. normal! "_dap
  1408. setlocal nomodifiable
  1409. echo 'Reverted.'
  1410. endfunction
  1411. function! s:snapshot(...) abort
  1412. let home = get(s:, 'plug_home_org', g:plug_home)
  1413. let [type, var, header] = s:is_win ?
  1414. \ ['dosbatch', '%PLUG_HOME%',
  1415. \ ['@echo off', ':: Generated by vim-plug', ':: '.strftime("%c"), '',
  1416. \ ':: Make sure to PlugUpdate first', '', 'set PLUG_HOME='.s:esc(home)]] :
  1417. \ ['sh', '$PLUG_HOME',
  1418. \ ['#!/bin/sh', '# Generated by vim-plug', '# '.strftime("%c"), '',
  1419. \ 'vim +PlugUpdate +qa', '', 'PLUG_HOME='.s:esc(home)]]
  1420. call s:prepare()
  1421. execute 'setf' type
  1422. call append(0, header)
  1423. call append('$', '')
  1424. 1
  1425. redraw
  1426. let dirs = sort(map(values(filter(copy(g:plugs),
  1427. \'has_key(v:val, "uri") && isdirectory(v:val.dir)')), 'v:val.dir'))
  1428. let anchor = line('$') - 1
  1429. for dir in reverse(dirs)
  1430. let sha = s:system_chomp('git rev-parse --short HEAD', dir)
  1431. if !empty(sha)
  1432. call append(anchor, printf('cd %s && git reset --hard %s',
  1433. \ substitute(dir, '^'.g:plug_home, var, ''), sha))
  1434. redraw
  1435. endif
  1436. endfor
  1437. if a:0 > 0
  1438. let fn = expand(a:1)
  1439. let fne = s:esc(fn)
  1440. call writefile(getline(1, '$'), fn)
  1441. if !s:is_win | call s:system('chmod +x ' . fne) | endif
  1442. echo 'Saved to '.a:1
  1443. silent execute 'e' fne
  1444. endif
  1445. endfunction
  1446. function! s:split_rtp()
  1447. return split(&rtp, '\\\@<!,')
  1448. endfunction
  1449. let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
  1450. let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
  1451. if exists('g:plugs')
  1452. let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
  1453. call s:upgrade_specs()
  1454. call s:define_commands()
  1455. endif
  1456. let &cpo = s:cpo_save
  1457. unlet s:cpo_save