plug.vim 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120
  1. " vim-plug: Vim plugin manager
  2. " ============================
  3. "
  4. " Download plug.vim and put it in ~/.vim/autoload
  5. "
  6. " curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
  7. " https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
  8. "
  9. " Edit your .vimrc
  10. "
  11. " call plug#begin('~/.vim/plugged')
  12. "
  13. " " Make sure you use single quotes
  14. " Plug 'junegunn/seoul256.vim'
  15. " Plug 'junegunn/vim-easy-align'
  16. "
  17. " " Group dependencies, vim-snippets depends on ultisnips
  18. " Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets'
  19. "
  20. " " On-demand loading
  21. " Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
  22. " Plug 'tpope/vim-fireplace', { 'for': 'clojure' }
  23. "
  24. " " Using git URL
  25. " Plug 'https://github.com/junegunn/vim-github-dashboard.git'
  26. "
  27. " " Using a non-master branch
  28. " Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' }
  29. "
  30. " " Plugin options
  31. " Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' }
  32. "
  33. " " Plugin outside ~/.vim/plugged with post-update hook
  34. " Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
  35. "
  36. " " Unmanaged plugin (manually installed and updated)
  37. " Plug '~/my-prototype-plugin'
  38. "
  39. " " Add plugins to &runtimepath
  40. " call plug#end()
  41. "
  42. " Then reload .vimrc and :PlugInstall to install plugins.
  43. " Visit https://github.com/junegunn/vim-plug for more information.
  44. "
  45. "
  46. " Copyright (c) 2015 Junegunn Choi
  47. "
  48. " MIT License
  49. "
  50. " Permission is hereby granted, free of charge, to any person obtaining
  51. " a copy of this software and associated documentation files (the
  52. " "Software"), to deal in the Software without restriction, including
  53. " without limitation the rights to use, copy, modify, merge, publish,
  54. " distribute, sublicense, and/or sell copies of the Software, and to
  55. " permit persons to whom the Software is furnished to do so, subject to
  56. " the following conditions:
  57. "
  58. " The above copyright notice and this permission notice shall be
  59. " included in all copies or substantial portions of the Software.
  60. "
  61. " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  62. " EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  63. " MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  64. " NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  65. " LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  66. " OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  67. " WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  68. if exists('g:loaded_plug')
  69. finish
  70. endif
  71. let g:loaded_plug = 1
  72. let s:cpo_save = &cpo
  73. set cpo&vim
  74. let s:plug_src = 'https://github.com/junegunn/vim-plug.git'
  75. let s:plug_tab = get(s:, 'plug_tab', -1)
  76. let s:plug_buf = get(s:, 'plug_buf', -1)
  77. let s:mac_gui = has('gui_macvim') && has('gui_running')
  78. let s:is_win = has('win32') || has('win64')
  79. let s:nvim = has('nvim') && exists('*jobwait') && !s:is_win
  80. let s:me = resolve(expand('<sfile>:p'))
  81. let s:base_spec = { 'branch': 'master', 'frozen': 0 }
  82. let s:TYPE = {
  83. \ 'string': type(''),
  84. \ 'list': type([]),
  85. \ 'dict': type({}),
  86. \ 'funcref': type(function('call'))
  87. \ }
  88. let s:loaded = get(s:, 'loaded', {})
  89. let s:triggers = get(s:, 'triggers', {})
  90. function! plug#begin(...)
  91. if a:0 > 0
  92. let s:plug_home_org = a:1
  93. let home = s:path(fnamemodify(expand(a:1), ':p'))
  94. elseif exists('g:plug_home')
  95. let home = s:path(g:plug_home)
  96. elseif !empty(&rtp)
  97. let home = s:path(split(&rtp, ',')[0]) . '/plugged'
  98. else
  99. return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.')
  100. endif
  101. let g:plug_home = home
  102. let g:plugs = {}
  103. let g:plugs_order = []
  104. let s:triggers = {}
  105. call s:define_commands()
  106. return 1
  107. endfunction
  108. function! s:define_commands()
  109. command! -nargs=+ -bar Plug call s:add(<args>)
  110. if !executable('git')
  111. return s:err('`git` executable not found. vim-plug requires git.')
  112. endif
  113. command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install(<bang>0, [<f-args>])
  114. command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update(<bang>0, [<f-args>])
  115. command! -nargs=0 -bar -bang PlugClean call s:clean(<bang>0)
  116. command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:esc(s:me) | endif
  117. command! -nargs=0 -bar PlugStatus call s:status()
  118. command! -nargs=0 -bar PlugDiff call s:diff()
  119. command! -nargs=? -bar -bang -complete=file PlugSnapshot call s:snapshot(<bang>0, <f-args>)
  120. endfunction
  121. function! s:to_a(v)
  122. return type(a:v) == s:TYPE.list ? a:v : [a:v]
  123. endfunction
  124. function! s:to_s(v)
  125. return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n"
  126. endfunction
  127. function! s:source(from, ...)
  128. for pattern in a:000
  129. for vim in s:lines(globpath(a:from, pattern))
  130. execute 'source' s:esc(vim)
  131. endfor
  132. endfor
  133. endfunction
  134. function! s:assoc(dict, key, val)
  135. let a:dict[a:key] = add(get(a:dict, a:key, []), a:val)
  136. endfunction
  137. function! s:ask(message)
  138. call inputsave()
  139. echohl WarningMsg
  140. let proceed = input(a:message.' (y/N) ') =~? '^y'
  141. echohl None
  142. call inputrestore()
  143. echo "\r"
  144. return proceed
  145. endfunction
  146. function! plug#end()
  147. if !exists('g:plugs')
  148. return s:err('Call plug#begin() first')
  149. endif
  150. if exists('#PlugLOD')
  151. augroup PlugLOD
  152. autocmd!
  153. augroup END
  154. augroup! PlugLOD
  155. endif
  156. let lod = { 'ft': {}, 'map': {}, 'cmd': {} }
  157. filetype off
  158. for name in g:plugs_order
  159. let plug = g:plugs[name]
  160. if get(s:loaded, name, 0) || !has_key(plug, 'on') && !has_key(plug, 'for')
  161. let s:loaded[name] = 1
  162. continue
  163. endif
  164. if has_key(plug, 'on')
  165. let s:triggers[name] = { 'map': [], 'cmd': [] }
  166. for cmd in s:to_a(plug.on)
  167. if cmd =~? '^<Plug>.\+'
  168. if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i'))
  169. call s:assoc(lod.map, cmd, name)
  170. endif
  171. call add(s:triggers[name].map, cmd)
  172. elseif cmd =~# '^[A-Z]'
  173. if exists(':'.cmd) != 2
  174. call s:assoc(lod.cmd, cmd, name)
  175. endif
  176. call add(s:triggers[name].cmd, cmd)
  177. else
  178. call s:err('Invalid `on` option: '.cmd.
  179. \ '. Should start with an uppercase letter or `<Plug>`.')
  180. endif
  181. endfor
  182. endif
  183. if has_key(plug, 'for')
  184. let types = s:to_a(plug.for)
  185. if !empty(types)
  186. call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim')
  187. endif
  188. for type in types
  189. call s:assoc(lod.ft, type, name)
  190. endfor
  191. endif
  192. endfor
  193. for [cmd, names] in items(lod.cmd)
  194. execute printf(
  195. \ 'command! -nargs=* -range -bang %s call s:lod_cmd(%s, "<bang>", <line1>, <line2>, <q-args>, %s)',
  196. \ cmd, string(cmd), string(names))
  197. endfor
  198. for [map, names] in items(lod.map)
  199. for [mode, map_prefix, key_prefix] in
  200. \ [['i', '<C-O>', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']]
  201. execute printf(
  202. \ '%snoremap <silent> %s %s:<C-U>call <SID>lod_map(%s, %s, "%s")<CR>',
  203. \ mode, map, map_prefix, string(map), string(names), key_prefix)
  204. endfor
  205. endfor
  206. for [ft, names] in items(lod.ft)
  207. augroup PlugLOD
  208. execute printf('autocmd FileType %s call <SID>lod_ft(%s, %s)',
  209. \ ft, string(ft), string(names))
  210. augroup END
  211. endfor
  212. call s:reorg_rtp()
  213. filetype plugin indent on
  214. if has('vim_starting')
  215. syntax enable
  216. else
  217. call s:reload()
  218. endif
  219. endfunction
  220. function! s:loaded_names()
  221. return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)')
  222. endfunction
  223. function! s:reload()
  224. for name in s:loaded_names()
  225. call s:source(s:rtp(g:plugs[name]), 'plugin/**/*.vim', 'after/plugin/**/*.vim')
  226. endfor
  227. endfunction
  228. function! s:trim(str)
  229. return substitute(a:str, '[\/]\+$', '', '')
  230. endfunction
  231. function! s:version_requirement(val, min)
  232. for idx in range(0, len(a:min) - 1)
  233. let v = get(a:val, idx, 0)
  234. if v < a:min[idx] | return 0
  235. elseif v > a:min[idx] | return 1
  236. endif
  237. endfor
  238. return 1
  239. endfunction
  240. function! s:git_version_requirement(...)
  241. let s:git_version = get(s:, 'git_version',
  242. \ map(split(split(s:system('git --version'))[-1], '\.'), 'str2nr(v:val)'))
  243. return s:version_requirement(s:git_version, a:000)
  244. endfunction
  245. function! s:progress_opt(base)
  246. return a:base && !s:is_win &&
  247. \ s:git_version_requirement(1, 7, 1) ? '--progress' : ''
  248. endfunction
  249. if s:is_win
  250. function! s:rtp(spec)
  251. return s:path(a:spec.dir . get(a:spec, 'rtp', ''))
  252. endfunction
  253. function! s:path(path)
  254. return s:trim(substitute(a:path, '/', '\', 'g'))
  255. endfunction
  256. function! s:dirpath(path)
  257. return s:path(a:path) . '\'
  258. endfunction
  259. function! s:is_local_plug(repo)
  260. return a:repo =~? '^[a-z]:\|^[%~]'
  261. endfunction
  262. else
  263. function! s:rtp(spec)
  264. return s:dirpath(a:spec.dir . get(a:spec, 'rtp', ''))
  265. endfunction
  266. function! s:path(path)
  267. return s:trim(a:path)
  268. endfunction
  269. function! s:dirpath(path)
  270. return substitute(a:path, '[/\\]*$', '/', '')
  271. endfunction
  272. function! s:is_local_plug(repo)
  273. return a:repo[0] =~ '[/$~]'
  274. endfunction
  275. endif
  276. function! s:err(msg)
  277. echohl ErrorMsg
  278. echom '[vim-plug] '.a:msg
  279. echohl None
  280. return 0
  281. endfunction
  282. function! s:esc(path)
  283. return escape(a:path, ' ')
  284. endfunction
  285. function! s:escrtp(path)
  286. return escape(a:path, ' ,')
  287. endfunction
  288. function! s:remove_rtp()
  289. for name in s:loaded_names()
  290. let rtp = s:rtp(g:plugs[name])
  291. execute 'set rtp-='.s:escrtp(rtp)
  292. let after = globpath(rtp, 'after')
  293. if isdirectory(after)
  294. execute 'set rtp-='.s:escrtp(after)
  295. endif
  296. endfor
  297. endfunction
  298. function! s:reorg_rtp()
  299. if !empty(s:first_rtp)
  300. execute 'set rtp-='.s:first_rtp
  301. execute 'set rtp-='.s:last_rtp
  302. endif
  303. " &rtp is modified from outside
  304. if exists('s:prtp') && s:prtp !=# &rtp
  305. call s:remove_rtp()
  306. unlet! s:middle
  307. endif
  308. let s:middle = get(s:, 'middle', &rtp)
  309. let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])')
  310. let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), 'isdirectory(v:val)')
  311. let rtp = join(map(rtps, 'escape(v:val, ",")'), ',')
  312. \ . ','.s:middle.','
  313. \ . join(map(afters, 'escape(v:val, ",")'), ',')
  314. let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g')
  315. let s:prtp = &rtp
  316. if !empty(s:first_rtp)
  317. execute 'set rtp^='.s:first_rtp
  318. execute 'set rtp+='.s:last_rtp
  319. endif
  320. endfunction
  321. function! plug#load(...)
  322. if a:0 == 0
  323. return s:err('Argument missing: plugin name(s) required')
  324. endif
  325. if !exists('g:plugs')
  326. return s:err('plug#begin was not called')
  327. endif
  328. let unknowns = filter(copy(a:000), '!has_key(g:plugs, v:val)')
  329. if !empty(unknowns)
  330. let s = len(unknowns) > 1 ? 's' : ''
  331. return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', ')))
  332. end
  333. for name in a:000
  334. call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  335. endfor
  336. if exists('#BufRead')
  337. doautocmd BufRead
  338. endif
  339. return 1
  340. endfunction
  341. function! s:remove_triggers(name)
  342. if !has_key(s:triggers, a:name)
  343. return
  344. endif
  345. for cmd in s:triggers[a:name].cmd
  346. execute 'silent! delc' cmd
  347. endfor
  348. for map in s:triggers[a:name].map
  349. execute 'silent! unmap' map
  350. execute 'silent! iunmap' map
  351. endfor
  352. call remove(s:triggers, a:name)
  353. endfunction
  354. function! s:lod(names, types)
  355. for name in a:names
  356. call s:remove_triggers(name)
  357. let s:loaded[name] = 1
  358. endfor
  359. call s:reorg_rtp()
  360. for name in a:names
  361. let rtp = s:rtp(g:plugs[name])
  362. for dir in a:types
  363. call s:source(rtp, dir.'/**/*.vim')
  364. endfor
  365. if exists('#User#'.name)
  366. execute 'doautocmd User' name
  367. endif
  368. endfor
  369. endfunction
  370. function! s:lod_ft(pat, names)
  371. call s:lod(a:names, ['plugin', 'after/plugin', 'syntax', 'after/syntax'])
  372. execute 'autocmd! PlugLOD FileType' a:pat
  373. if exists('#filetypeplugin#FileType')
  374. doautocmd filetypeplugin FileType
  375. endif
  376. if exists('#filetypeindent#FileType')
  377. doautocmd filetypeindent FileType
  378. endif
  379. endfunction
  380. function! s:lod_cmd(cmd, bang, l1, l2, args, names)
  381. call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  382. execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args)
  383. endfunction
  384. function! s:lod_map(map, names, prefix)
  385. call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  386. let extra = ''
  387. while 1
  388. let c = getchar(0)
  389. if c == 0
  390. break
  391. endif
  392. let extra .= nr2char(c)
  393. endwhile
  394. call feedkeys(a:prefix . substitute(a:map, '^<Plug>', "\<Plug>", '') . extra)
  395. endfunction
  396. function! s:add(repo, ...)
  397. if a:0 > 1
  398. return s:err('Invalid number of arguments (1..2)')
  399. endif
  400. try
  401. let repo = s:trim(a:repo)
  402. let name = fnamemodify(repo, ':t:s?\.git$??')
  403. let spec = extend(s:infer_properties(name, repo),
  404. \ a:0 == 1 ? s:parse_options(a:1) : s:base_spec)
  405. if !has_key(g:plugs, name)
  406. call add(g:plugs_order, name)
  407. endif
  408. let g:plugs[name] = spec
  409. let s:loaded[name] = get(s:loaded, name, 0)
  410. catch
  411. return s:err(v:exception)
  412. endtry
  413. endfunction
  414. function! s:parse_options(arg)
  415. let opts = copy(s:base_spec)
  416. let type = type(a:arg)
  417. if type == s:TYPE.string
  418. let opts.tag = a:arg
  419. elseif type == s:TYPE.dict
  420. call extend(opts, a:arg)
  421. if has_key(opts, 'dir')
  422. let opts.dir = s:dirpath(expand(opts.dir))
  423. endif
  424. else
  425. throw 'Invalid argument type (expected: string or dictionary)'
  426. endif
  427. return opts
  428. endfunction
  429. function! s:infer_properties(name, repo)
  430. let repo = a:repo
  431. if s:is_local_plug(repo)
  432. return { 'dir': s:dirpath(expand(repo)) }
  433. else
  434. if repo =~ ':'
  435. let uri = repo
  436. else
  437. if repo !~ '/'
  438. let repo = 'vim-scripts/'. repo
  439. endif
  440. let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git')
  441. let uri = printf(fmt, repo)
  442. endif
  443. let dir = s:dirpath( fnamemodify(join([g:plug_home, a:name], '/'), ':p') )
  444. return { 'dir': dir, 'uri': uri }
  445. endif
  446. endfunction
  447. function! s:install(force, names)
  448. call s:update_impl(0, a:force, a:names)
  449. endfunction
  450. function! s:update(force, names)
  451. call s:update_impl(1, a:force, a:names)
  452. endfunction
  453. function! plug#helptags()
  454. if !exists('g:plugs')
  455. return s:err('plug#begin was not called')
  456. endif
  457. for spec in values(g:plugs)
  458. let docd = join([spec.dir, 'doc'], '/')
  459. if isdirectory(docd)
  460. silent! execute 'helptags' s:esc(docd)
  461. endif
  462. endfor
  463. return 1
  464. endfunction
  465. function! s:syntax()
  466. syntax clear
  467. syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber
  468. syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX
  469. syn match plugNumber /[0-9]\+[0-9.]*/ contained
  470. syn match plugBracket /[[\]]/ contained
  471. syn match plugX /x/ contained
  472. syn match plugDash /^-/
  473. syn match plugPlus /^+/
  474. syn match plugStar /^*/
  475. syn match plugMessage /\(^- \)\@<=.*/
  476. syn match plugName /\(^- \)\@<=[^ ]*:/
  477. syn match plugSha /\%(: \)\@<=[0-9a-z]\{4,}$/
  478. syn match plugTag /(tag: [^)]\+)/
  479. syn match plugInstall /\(^+ \)\@<=[^:]*/
  480. syn match plugUpdate /\(^* \)\@<=[^:]*/
  481. syn match plugCommit /^ [0-9a-z]\{7} .*/ contains=plugRelDate,plugSha,plugTag
  482. syn match plugSha /\(^ \)\@<=[0-9a-z]\{7}/ contained
  483. syn match plugRelDate /([^)]*)$/ contained
  484. syn match plugNotLoaded /(not loaded)$/
  485. syn match plugError /^x.*/
  486. syn match plugH2 /^.*:\n-\+$/
  487. syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean
  488. hi def link plug1 Title
  489. hi def link plug2 Repeat
  490. hi def link plugH2 Type
  491. hi def link plugX Exception
  492. hi def link plugBracket Structure
  493. hi def link plugNumber Number
  494. hi def link plugDash Special
  495. hi def link plugPlus Constant
  496. hi def link plugStar Boolean
  497. hi def link plugMessage Function
  498. hi def link plugName Label
  499. hi def link plugInstall Function
  500. hi def link plugUpdate Type
  501. hi def link plugError Error
  502. hi def link plugRelDate Comment
  503. hi def link plugSha Identifier
  504. hi def link plugTag Constant
  505. hi def link plugNotLoaded Comment
  506. endfunction
  507. function! s:lpad(str, len)
  508. return a:str . repeat(' ', a:len - len(a:str))
  509. endfunction
  510. function! s:lines(msg)
  511. return split(a:msg, "[\r\n]")
  512. endfunction
  513. function! s:lastline(msg)
  514. return get(s:lines(a:msg), -1, '')
  515. endfunction
  516. function! s:new_window()
  517. execute get(g:, 'plug_window', 'vertical topleft new')
  518. endfunction
  519. function! s:plug_window_exists()
  520. let buflist = tabpagebuflist(s:plug_tab)
  521. return !empty(buflist) && index(buflist, s:plug_buf) >= 0
  522. endfunction
  523. function! s:switch_in()
  524. if !s:plug_window_exists()
  525. return 0
  526. endif
  527. if winbufnr(0) != s:plug_buf
  528. let s:pos = [tabpagenr(), winnr(), winsaveview()]
  529. execute 'normal!' s:plug_tab.'gt'
  530. let winnr = bufwinnr(s:plug_buf)
  531. execute winnr.'wincmd w'
  532. call add(s:pos, winsaveview())
  533. else
  534. let s:pos = [winsaveview()]
  535. endif
  536. setlocal modifiable
  537. return 1
  538. endfunction
  539. function! s:switch_out(...)
  540. call winrestview(s:pos[-1])
  541. setlocal nomodifiable
  542. if a:0 > 0
  543. execute a:1
  544. endif
  545. if len(s:pos) > 1
  546. execute 'normal!' s:pos[0].'gt'
  547. execute s:pos[1] 'wincmd w'
  548. call winrestview(s:pos[2])
  549. endif
  550. endfunction
  551. function! s:prepare()
  552. call s:job_abort()
  553. if s:switch_in()
  554. silent %d _
  555. else
  556. call s:new_window()
  557. nnoremap <silent> <buffer> q :if b:plug_preview==1<bar>pc<bar>endif<bar>bd<cr>
  558. nnoremap <silent> <buffer> R :silent! call <SID>retry()<cr>
  559. nnoremap <silent> <buffer> D :PlugDiff<cr>
  560. nnoremap <silent> <buffer> S :PlugStatus<cr>
  561. nnoremap <silent> <buffer> U :call <SID>status_update()<cr>
  562. xnoremap <silent> <buffer> U :call <SID>status_update()<cr>
  563. nnoremap <silent> <buffer> ]] :silent! call <SID>section('')<cr>
  564. nnoremap <silent> <buffer> [[ :silent! call <SID>section('b')<cr>
  565. let b:plug_preview = -1
  566. let s:plug_tab = tabpagenr()
  567. let s:plug_buf = winbufnr(0)
  568. call s:assign_name()
  569. endif
  570. silent! unmap <buffer> <cr>
  571. silent! unmap <buffer> L
  572. silent! unmap <buffer> o
  573. silent! unmap <buffer> X
  574. setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap cursorline modifiable
  575. setf vim-plug
  576. if exists('g:syntax_on')
  577. call s:syntax()
  578. endif
  579. endfunction
  580. function! s:assign_name()
  581. " Assign buffer name
  582. let prefix = '[Plugins]'
  583. let name = prefix
  584. let idx = 2
  585. while bufexists(name)
  586. let name = printf('%s (%s)', prefix, idx)
  587. let idx = idx + 1
  588. endwhile
  589. silent! execute 'f' fnameescape(name)
  590. endfunction
  591. function! s:do(pull, force, todo)
  592. for [name, spec] in items(a:todo)
  593. if !isdirectory(spec.dir)
  594. continue
  595. endif
  596. let installed = has_key(s:update.new, name)
  597. let updated = installed ? 0 :
  598. \ (a:pull && index(s:update.errors, name) < 0 && !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', spec.dir)))
  599. if a:force || installed || updated
  600. execute 'cd' s:esc(spec.dir)
  601. call append(3, '- Post-update hook for '. name .' ... ')
  602. let error = ''
  603. let type = type(spec.do)
  604. if type == s:TYPE.string
  605. try
  606. " FIXME: Escaping is incomplete. We could use shellescape with eval,
  607. " but it won't work on Windows.
  608. let g:_plug_do = '!'.escape(spec.do, '#!%')
  609. execute "normal! :execute g:_plug_do\<cr>\<cr>"
  610. finally
  611. if v:shell_error
  612. let error = 'Exit status: ' . v:shell_error
  613. endif
  614. unlet g:_plug_do
  615. endtry
  616. elseif type == s:TYPE.funcref
  617. try
  618. let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
  619. call spec.do({ 'name': name, 'status': status, 'force': a:force })
  620. catch
  621. let error = v:exception
  622. endtry
  623. else
  624. let error = 'Invalid hook type'
  625. endif
  626. call setline(4, empty(error) ? (getline(4) . 'OK')
  627. \ : ('x' . getline(4)[1:] . error))
  628. cd -
  629. endif
  630. endfor
  631. endfunction
  632. function! s:hash_match(a, b)
  633. return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0
  634. endfunction
  635. function! s:checkout(plugs)
  636. for [name, spec] in items(a:plugs)
  637. let sha = spec.commit
  638. call append(3, '- Checking out '.sha[:6].' of '.name.' ... ')
  639. redraw
  640. let error = []
  641. let output = s:lines(s:system('git rev-parse HEAD', spec.dir))
  642. if v:shell_error
  643. let error = output
  644. elseif !s:hash_match(sha, output[0])
  645. let output = s:lines(s:system(
  646. \ 'git fetch --depth 999999 && git checkout '.sha, spec.dir))
  647. if v:shell_error
  648. let error = output
  649. endif
  650. endif
  651. if empty(error)
  652. call setline(4, getline(4) . 'OK')
  653. else
  654. call setline(4, 'x'.getline(4)[1:] . 'Error')
  655. for line in reverse(error)
  656. call append(4, ' '.line)
  657. endfor
  658. endif
  659. endfor
  660. endfunction
  661. function! s:finish(pull)
  662. let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
  663. if new_frozen
  664. let s = new_frozen > 1 ? 's' : ''
  665. call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
  666. endif
  667. call append(3, '- Finishing ... ')
  668. redraw
  669. call plug#helptags()
  670. call plug#end()
  671. call setline(4, getline(4) . 'Done!')
  672. redraw
  673. let msgs = []
  674. if !empty(s:update.errors)
  675. call add(msgs, "Press 'R' to retry.")
  676. endif
  677. if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
  678. \ "v:val =~ '^- ' && stridx(v:val, 'Already up-to-date') < 0"))
  679. call add(msgs, "Press 'D' to see the updated changes.")
  680. endif
  681. echo join(msgs, ' ')
  682. endfunction
  683. function! s:retry()
  684. if empty(s:update.errors)
  685. return
  686. endif
  687. call s:update_impl(s:update.pull, s:update.force,
  688. \ extend(copy(s:update.errors), [s:update.threads]))
  689. endfunction
  690. function! s:is_managed(name)
  691. return has_key(g:plugs[a:name], 'uri')
  692. endfunction
  693. function! s:names(...)
  694. return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
  695. endfunction
  696. function! s:update_impl(pull, force, args) abort
  697. let args = copy(a:args)
  698. let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
  699. \ remove(args, -1) : get(g:, 'plug_threads', 16)
  700. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  701. let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
  702. \ filter(managed, 'index(args, v:key) >= 0')
  703. if empty(todo)
  704. echohl WarningMsg
  705. echo 'No plugin to '. (a:pull ? 'update' : 'install') . '.'
  706. echohl None
  707. return
  708. endif
  709. if !s:is_win && s:git_version_requirement(2, 3)
  710. let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : ''
  711. let $GIT_TERMINAL_PROMPT = 0
  712. for plug in values(todo)
  713. let plug.uri = substitute(plug.uri,
  714. \ '^https://git::@github\.com', 'https://github.com', '')
  715. endfor
  716. endif
  717. if !isdirectory(g:plug_home)
  718. try
  719. call mkdir(g:plug_home, 'p')
  720. catch
  721. return s:err(printf('Invalid plug directory: %s. '.
  722. \ 'Try to call plug#begin with a valid directory', g:plug_home))
  723. endtry
  724. endif
  725. if has('nvim') && !exists('*jobwait') && threads > 1
  726. echohl WarningMsg
  727. echomsg 'vim-plug: update Neovim for parallel installer'
  728. echohl None
  729. endif
  730. let python = (has('python') || has('python3')) && (!s:nvim || has('vim_starting'))
  731. let ruby = has('ruby') && !s:nvim && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running'))
  732. let s:update = {
  733. \ 'start': reltime(),
  734. \ 'all': todo,
  735. \ 'todo': copy(todo),
  736. \ 'errors': [],
  737. \ 'pull': a:pull,
  738. \ 'force': a:force,
  739. \ 'new': {},
  740. \ 'threads': (python || ruby || s:nvim) ? min([len(todo), threads]) : 1,
  741. \ 'bar': '',
  742. \ 'fin': 0
  743. \ }
  744. call s:prepare()
  745. call append(0, ['', ''])
  746. normal! 2G
  747. silent! redraw
  748. let s:clone_opt = get(g:, 'plug_shallow', 1) ?
  749. \ '--depth 1' . (s:git_version_requirement(1, 7, 10) ? ' --no-single-branch' : '') : ''
  750. " Python version requirement (>= 2.7)
  751. if python && !has('python3') && !ruby && !s:nvim && s:update.threads > 1
  752. redir => pyv
  753. silent python import platform; print(platform.python_version())
  754. redir END
  755. let python = s:version_requirement(
  756. \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6])
  757. endif
  758. if (python || ruby) && s:update.threads > 1
  759. try
  760. let imd = &imd
  761. if s:mac_gui
  762. set noimd
  763. endif
  764. if ruby
  765. call s:update_ruby()
  766. else
  767. call s:update_python()
  768. endif
  769. catch
  770. let lines = getline(4, '$')
  771. let printed = {}
  772. silent! 4,$d _
  773. for line in lines
  774. let name = s:extract_name(line, '.', '')
  775. if empty(name) || !has_key(printed, name)
  776. call append('$', line)
  777. if !empty(name)
  778. let printed[name] = 1
  779. if line[0] == 'x' && index(s:update.errors, name) < 0
  780. call add(s:update.errors, name)
  781. end
  782. endif
  783. endif
  784. endfor
  785. finally
  786. let &imd = imd
  787. call s:update_finish()
  788. endtry
  789. else
  790. call s:update_vim()
  791. endif
  792. endfunction
  793. function! s:update_finish()
  794. if exists('s:git_terminal_prompt')
  795. let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt
  796. endif
  797. if s:switch_in()
  798. call s:checkout(filter(copy(s:update.all), 'has_key(v:val, "commit")'))
  799. call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'has_key(v:val, "do")'))
  800. call s:finish(s:update.pull)
  801. call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
  802. call s:switch_out('normal! gg')
  803. endif
  804. endfunction
  805. function! s:job_abort()
  806. if !s:nvim || !exists('s:jobs')
  807. return
  808. endif
  809. for [name, j] in items(s:jobs)
  810. silent! call jobstop(j.jobid)
  811. if j.new
  812. call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir))
  813. endif
  814. endfor
  815. let s:jobs = {}
  816. endfunction
  817. " When a:event == 'stdout', data = list of strings
  818. " When a:event == 'exit', data = returncode
  819. function! s:job_handler(job_id, data, event) abort
  820. if !s:plug_window_exists() " plug window closed
  821. return s:job_abort()
  822. endif
  823. if a:event == 'stdout'
  824. let complete = empty(a:data[-1])
  825. let lines = map(filter(a:data, 'len(v:val) > 0'), 'split(v:val, "[\r\n]")[-1]')
  826. call extend(self.lines, lines)
  827. let self.result = join(self.lines, "\n")
  828. if !complete
  829. call remove(self.lines, -1)
  830. endif
  831. " To reduce the number of buffer updates
  832. let self.tick = get(self, 'tick', -1) + 1
  833. if self.tick % len(s:jobs) == 0
  834. call s:log(self.new ? '+' : '*', self.name, self.result)
  835. endif
  836. elseif a:event == 'exit'
  837. let self.running = 0
  838. if a:data != 0
  839. let self.error = 1
  840. endif
  841. call s:reap(self.name)
  842. call s:tick()
  843. endif
  844. endfunction
  845. function! s:spawn(name, cmd, opts)
  846. let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [], 'result': '',
  847. \ 'new': get(a:opts, 'new', 0),
  848. \ 'on_stdout': function('s:job_handler'),
  849. \ 'on_exit' : function('s:job_handler'),
  850. \ }
  851. let s:jobs[a:name] = job
  852. if s:nvim
  853. let argv = [ 'sh', '-c',
  854. \ (has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd) ]
  855. let jid = jobstart(argv, job)
  856. if jid > 0
  857. let job.jobid = jid
  858. else
  859. let job.running = 0
  860. let job.error = 1
  861. let job.result = jid < 0 ? 'sh is not executable' :
  862. \ 'Invalid arguments (or job table is full)'
  863. endif
  864. else
  865. let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd]
  866. let job.result = call('s:system', params)
  867. let job.error = v:shell_error != 0
  868. let job.running = 0
  869. endif
  870. endfunction
  871. function! s:reap(name)
  872. let job = s:jobs[a:name]
  873. if job.error
  874. call add(s:update.errors, a:name)
  875. elseif get(job, 'new', 0)
  876. let s:update.new[a:name] = 1
  877. endif
  878. let s:update.bar .= job.error ? 'x' : '='
  879. call s:log(job.error ? 'x' : '-', a:name, job.result)
  880. call s:bar()
  881. call remove(s:jobs, a:name)
  882. endfunction
  883. function! s:bar()
  884. if s:switch_in()
  885. let total = len(s:update.all)
  886. call setline(1, (s:update.pull ? 'Updating' : 'Installing').
  887. \ ' plugins ('.len(s:update.bar).'/'.total.')')
  888. call s:progress_bar(2, s:update.bar, total)
  889. call s:switch_out()
  890. endif
  891. endfunction
  892. function! s:logpos(name)
  893. for i in range(1, line('$'))
  894. if getline(i) =~# '^[-+x*] '.a:name.':'
  895. return i
  896. endif
  897. endfor
  898. return 0
  899. endfunction
  900. function! s:log(bullet, name, lines)
  901. if s:switch_in()
  902. let pos = s:logpos(a:name)
  903. if pos > 0
  904. execute pos 'd _'
  905. if pos > winheight('.')
  906. let pos = 4
  907. endif
  908. else
  909. let pos = 4
  910. endif
  911. call append(pos - 1, s:format_message(a:bullet, a:name, a:lines))
  912. call s:switch_out()
  913. endif
  914. endfunction
  915. function! s:update_vim()
  916. let s:jobs = {}
  917. call s:bar()
  918. call s:tick()
  919. endfunction
  920. function! s:tick()
  921. let pull = s:update.pull
  922. let prog = s:progress_opt(s:nvim)
  923. while 1 " Without TCO, Vim stack is bound to explode
  924. if empty(s:update.todo)
  925. if empty(s:jobs) && !s:update.fin
  926. let s:update.fin = 1
  927. call s:update_finish()
  928. endif
  929. return
  930. endif
  931. let name = keys(s:update.todo)[0]
  932. let spec = remove(s:update.todo, name)
  933. let new = !isdirectory(spec.dir)
  934. call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
  935. redraw
  936. let has_tag = has_key(spec, 'tag')
  937. let checkout = s:shellesc(has_tag ? spec.tag : spec.branch)
  938. let merge = s:shellesc(has_tag ? spec.tag : 'origin/'.spec.branch)
  939. if !new
  940. let error = s:git_validate(spec, 0)
  941. if empty(error)
  942. if pull
  943. let fetch_opt = (has_tag && !empty(globpath(spec.dir, '.git/shallow'))) ? '--depth 99999999' : ''
  944. call s:spawn(name,
  945. \ printf('(git fetch %s %s 2>&1 && git checkout -q %s 2>&1 && git merge --ff-only %s 2>&1 && git submodule update --init --recursive 2>&1)',
  946. \ fetch_opt, prog, checkout, merge), { 'dir': spec.dir })
  947. else
  948. let s:jobs[name] = { 'running': 0, 'result': 'Already installed', 'error': 0 }
  949. endif
  950. else
  951. let s:jobs[name] = { 'running': 0, 'result': error, 'error': 1 }
  952. endif
  953. else
  954. call s:spawn(name,
  955. \ printf('git clone %s %s --recursive %s -b %s %s 2>&1',
  956. \ has_tag ? '' : s:clone_opt,
  957. \ prog,
  958. \ s:shellesc(spec.uri),
  959. \ checkout,
  960. \ s:shellesc(s:trim(spec.dir))), { 'new': 1 })
  961. endif
  962. if !s:jobs[name].running
  963. call s:reap(name)
  964. endif
  965. if len(s:jobs) >= s:update.threads
  966. break
  967. endif
  968. endwhile
  969. endfunction
  970. function! s:update_python()
  971. let py_exe = has('python') ? 'python' : 'python3'
  972. execute py_exe "<< EOF"
  973. import datetime
  974. import functools
  975. import os
  976. try:
  977. import queue
  978. except ImportError:
  979. import Queue as queue
  980. import random
  981. import re
  982. import shutil
  983. import signal
  984. import subprocess
  985. import tempfile
  986. import threading as thr
  987. import time
  988. import traceback
  989. import vim
  990. G_NVIM = vim.eval("has('nvim')") == '1'
  991. G_PULL = vim.eval('s:update.pull') == '1'
  992. G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1
  993. G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)'))
  994. G_CLONE_OPT = vim.eval('s:clone_opt')
  995. G_PROGRESS = vim.eval('s:progress_opt(1)')
  996. G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads'))
  997. G_STOP = thr.Event()
  998. G_IS_WIN = vim.eval('s:is_win') == '1'
  999. class PlugError(Exception):
  1000. def __init__(self, msg):
  1001. self.msg = msg
  1002. class CmdTimedOut(PlugError):
  1003. pass
  1004. class CmdFailed(PlugError):
  1005. pass
  1006. class InvalidURI(PlugError):
  1007. pass
  1008. class Action(object):
  1009. INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-']
  1010. class Buffer(object):
  1011. def __init__(self, lock, num_plugs, is_pull):
  1012. self.bar = ''
  1013. self.event = 'Updating' if is_pull else 'Installing'
  1014. self.lock = lock
  1015. self.maxy = int(vim.eval('winheight(".")'))
  1016. self.num_plugs = num_plugs
  1017. def __where(self, name):
  1018. """ Find first line with name in current buffer. Return line num. """
  1019. found, lnum = False, 0
  1020. matcher = re.compile('^[-+x*] {0}:'.format(name))
  1021. for line in vim.current.buffer:
  1022. if matcher.search(line) is not None:
  1023. found = True
  1024. break
  1025. lnum += 1
  1026. if not found:
  1027. lnum = -1
  1028. return lnum
  1029. def header(self):
  1030. curbuf = vim.current.buffer
  1031. curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs)
  1032. num_spaces = self.num_plugs - len(self.bar)
  1033. curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ')
  1034. with self.lock:
  1035. vim.command('normal! 2G')
  1036. vim.command('redraw')
  1037. def write(self, action, name, lines):
  1038. first, rest = lines[0], lines[1:]
  1039. msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)]
  1040. msg.extend([' ' + line for line in rest])
  1041. try:
  1042. if action == Action.ERROR:
  1043. self.bar += 'x'
  1044. vim.command("call add(s:update.errors, '{0}')".format(name))
  1045. elif action == Action.DONE:
  1046. self.bar += '='
  1047. curbuf = vim.current.buffer
  1048. lnum = self.__where(name)
  1049. if lnum != -1: # Found matching line num
  1050. del curbuf[lnum]
  1051. if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]):
  1052. lnum = 3
  1053. else:
  1054. lnum = 3
  1055. curbuf.append(msg, lnum)
  1056. self.header()
  1057. except vim.error:
  1058. pass
  1059. class Command(object):
  1060. CD = 'cd /d' if G_IS_WIN else 'cd'
  1061. def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None):
  1062. self.cmd = cmd
  1063. if cmd_dir:
  1064. self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd)
  1065. self.timeout = timeout
  1066. self.callback = cb if cb else (lambda msg: None)
  1067. self.clean = clean if clean else (lambda: None)
  1068. self.proc = None
  1069. @property
  1070. def alive(self):
  1071. """ Returns true only if command still running. """
  1072. return self.proc and self.proc.poll() is None
  1073. def execute(self, ntries=3):
  1074. """ Execute the command with ntries if CmdTimedOut.
  1075. Returns the output of the command if no Exception.
  1076. """
  1077. attempt, finished, limit = 0, False, self.timeout
  1078. while not finished:
  1079. try:
  1080. attempt += 1
  1081. result = self.try_command()
  1082. finished = True
  1083. return result
  1084. except CmdTimedOut:
  1085. if attempt != ntries:
  1086. self.notify_retry()
  1087. self.timeout += limit
  1088. else:
  1089. raise
  1090. def notify_retry(self):
  1091. """ Retry required for command, notify user. """
  1092. for count in range(3, 0, -1):
  1093. if G_STOP.is_set():
  1094. raise KeyboardInterrupt
  1095. msg = 'Timeout. Will retry in {0} second{1} ...'.format(
  1096. count, 's' if count != 1 else '')
  1097. self.callback([msg])
  1098. time.sleep(1)
  1099. self.callback(['Retrying ...'])
  1100. def try_command(self):
  1101. """ Execute a cmd & poll for callback. Returns list of output.
  1102. Raises CmdFailed -> return code for Popen isn't 0
  1103. Raises CmdTimedOut -> command exceeded timeout without new output
  1104. """
  1105. first_line = True
  1106. try:
  1107. tfile = tempfile.NamedTemporaryFile(mode='w+b')
  1108. preexec_fn = not G_IS_WIN and os.setsid or None
  1109. self.proc = subprocess.Popen(self.cmd, stdout=tfile,
  1110. stderr=subprocess.STDOUT,
  1111. stdin=subprocess.PIPE, shell=True,
  1112. preexec_fn=preexec_fn)
  1113. thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,))
  1114. thrd.start()
  1115. thread_not_started = True
  1116. while thread_not_started:
  1117. try:
  1118. thrd.join(0.1)
  1119. thread_not_started = False
  1120. except RuntimeError:
  1121. pass
  1122. while self.alive:
  1123. if G_STOP.is_set():
  1124. raise KeyboardInterrupt
  1125. if first_line or random.random() < G_LOG_PROB:
  1126. first_line = False
  1127. line = '' if G_IS_WIN else nonblock_read(tfile.name)
  1128. if line:
  1129. self.callback([line])
  1130. time_diff = time.time() - os.path.getmtime(tfile.name)
  1131. if time_diff > self.timeout:
  1132. raise CmdTimedOut(['Timeout!'])
  1133. thrd.join(0.5)
  1134. tfile.seek(0)
  1135. result = [line.decode('utf-8', 'replace').rstrip() for line in tfile]
  1136. if self.proc.returncode != 0:
  1137. raise CmdFailed([''] + result)
  1138. return result
  1139. except:
  1140. self.terminate()
  1141. raise
  1142. def terminate(self):
  1143. """ Terminate process and cleanup. """
  1144. if self.alive:
  1145. if G_IS_WIN:
  1146. os.kill(self.proc.pid, signal.SIGINT)
  1147. else:
  1148. os.killpg(self.proc.pid, signal.SIGTERM)
  1149. self.clean()
  1150. class Plugin(object):
  1151. def __init__(self, name, args, buf_q, lock):
  1152. self.name = name
  1153. self.args = args
  1154. self.buf_q = buf_q
  1155. self.lock = lock
  1156. tag = args.get('tag', 0)
  1157. self.checkout = esc(tag if tag else args['branch'])
  1158. self.merge = esc(tag if tag else 'origin/' + args['branch'])
  1159. self.tag = tag
  1160. def manage(self):
  1161. try:
  1162. if os.path.exists(self.args['dir']):
  1163. self.update()
  1164. else:
  1165. self.install()
  1166. with self.lock:
  1167. thread_vim_command("let s:update.new['{0}'] = 1".format(self.name))
  1168. except PlugError as exc:
  1169. self.write(Action.ERROR, self.name, exc.msg)
  1170. except KeyboardInterrupt:
  1171. G_STOP.set()
  1172. self.write(Action.ERROR, self.name, ['Interrupted!'])
  1173. except:
  1174. # Any exception except those above print stack trace
  1175. msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip())
  1176. self.write(Action.ERROR, self.name, msg.split('\n'))
  1177. raise
  1178. def install(self):
  1179. target = self.args['dir']
  1180. if target[-1] == '\\':
  1181. target = target[0:-1]
  1182. def clean(target):
  1183. def _clean():
  1184. try:
  1185. shutil.rmtree(target)
  1186. except OSError:
  1187. pass
  1188. return _clean
  1189. self.write(Action.INSTALL, self.name, ['Installing ...'])
  1190. callback = functools.partial(self.write, Action.INSTALL, self.name)
  1191. cmd = 'git clone {0} {1} --recursive {2} -b {3} {4} 2>&1'.format(
  1192. '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'],
  1193. self.checkout, esc(target))
  1194. com = Command(cmd, None, G_TIMEOUT, callback, clean(target))
  1195. result = com.execute(G_RETRIES)
  1196. self.write(Action.DONE, self.name, result[-1:])
  1197. def repo_uri(self):
  1198. cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url'
  1199. command = Command(cmd, self.args['dir'], G_TIMEOUT,)
  1200. result = command.execute(G_RETRIES)
  1201. return result[-1]
  1202. def update(self):
  1203. match = re.compile(r'git::?@')
  1204. actual_uri = re.sub(match, '', self.repo_uri())
  1205. expect_uri = re.sub(match, '', self.args['uri'])
  1206. if actual_uri != expect_uri:
  1207. msg = ['',
  1208. 'Invalid URI: {0}'.format(actual_uri),
  1209. 'Expected {0}'.format(expect_uri),
  1210. 'PlugClean required.']
  1211. raise InvalidURI(msg)
  1212. if G_PULL:
  1213. self.write(Action.UPDATE, self.name, ['Updating ...'])
  1214. callback = functools.partial(self.write, Action.UPDATE, self.name)
  1215. fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else ''
  1216. cmds = ['git fetch {0} {1}'.format(fetch_opt, G_PROGRESS),
  1217. 'git checkout -q {0}'.format(self.checkout),
  1218. 'git merge --ff-only {0}'.format(self.merge),
  1219. 'git submodule update --init --recursive']
  1220. cmd = ' 2>&1 && '.join(cmds)
  1221. com = Command(cmd, self.args['dir'], G_TIMEOUT, callback)
  1222. result = com.execute(G_RETRIES)
  1223. self.write(Action.DONE, self.name, result[-1:])
  1224. else:
  1225. self.write(Action.DONE, self.name, ['Already installed'])
  1226. def write(self, action, name, msg):
  1227. self.buf_q.put((action, name, msg))
  1228. class PlugThread(thr.Thread):
  1229. def __init__(self, tname, args):
  1230. super(PlugThread, self).__init__()
  1231. self.tname = tname
  1232. self.args = args
  1233. def run(self):
  1234. thr.current_thread().name = self.tname
  1235. buf_q, work_q, lock = self.args
  1236. try:
  1237. while not G_STOP.is_set():
  1238. name, args = work_q.get_nowait()
  1239. plug = Plugin(name, args, buf_q, lock)
  1240. plug.manage()
  1241. work_q.task_done()
  1242. except queue.Empty:
  1243. pass
  1244. class RefreshThread(thr.Thread):
  1245. def __init__(self, lock):
  1246. super(RefreshThread, self).__init__()
  1247. self.lock = lock
  1248. self.running = True
  1249. def run(self):
  1250. while self.running:
  1251. with self.lock:
  1252. thread_vim_command('noautocmd normal! a')
  1253. time.sleep(0.33)
  1254. def stop(self):
  1255. self.running = False
  1256. if G_NVIM:
  1257. def thread_vim_command(cmd):
  1258. vim.session.threadsafe_call(lambda: vim.command(cmd))
  1259. else:
  1260. def thread_vim_command(cmd):
  1261. vim.command(cmd)
  1262. def esc(name):
  1263. return '"' + name.replace('"', '\"') + '"'
  1264. def nonblock_read(fname):
  1265. """ Read a file with nonblock flag. Return the last line. """
  1266. fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK)
  1267. buf = os.read(fread, 100000).decode('utf-8', 'replace')
  1268. os.close(fread)
  1269. line = buf.rstrip('\r\n')
  1270. left = max(line.rfind('\r'), line.rfind('\n'))
  1271. if left != -1:
  1272. left += 1
  1273. line = line[left:]
  1274. return line
  1275. def main():
  1276. thr.current_thread().name = 'main'
  1277. nthreads = int(vim.eval('s:update.threads'))
  1278. plugs = vim.eval('s:update.todo')
  1279. mac_gui = vim.eval('s:mac_gui') == '1'
  1280. lock = thr.Lock()
  1281. buf = Buffer(lock, len(plugs), G_PULL)
  1282. buf_q, work_q = queue.Queue(), queue.Queue()
  1283. for work in plugs.items():
  1284. work_q.put(work)
  1285. start_cnt = thr.active_count()
  1286. for num in range(nthreads):
  1287. tname = 'PlugT-{0:02}'.format(num)
  1288. thread = PlugThread(tname, (buf_q, work_q, lock))
  1289. thread.start()
  1290. if mac_gui:
  1291. rthread = RefreshThread(lock)
  1292. rthread.start()
  1293. while not buf_q.empty() or thr.active_count() != start_cnt:
  1294. try:
  1295. action, name, msg = buf_q.get(True, 0.25)
  1296. buf.write(action, name, msg)
  1297. buf_q.task_done()
  1298. except queue.Empty:
  1299. pass
  1300. except KeyboardInterrupt:
  1301. G_STOP.set()
  1302. if mac_gui:
  1303. rthread.stop()
  1304. rthread.join()
  1305. main()
  1306. EOF
  1307. endfunction
  1308. function! s:update_ruby()
  1309. ruby << EOF
  1310. module PlugStream
  1311. SEP = ["\r", "\n", nil]
  1312. def get_line
  1313. buffer = ''
  1314. loop do
  1315. char = readchar rescue return
  1316. if SEP.include? char.chr
  1317. buffer << $/
  1318. break
  1319. else
  1320. buffer << char
  1321. end
  1322. end
  1323. buffer
  1324. end
  1325. end unless defined?(PlugStream)
  1326. def esc arg
  1327. %["#{arg.gsub('"', '\"')}"]
  1328. end
  1329. def killall pid
  1330. pids = [pid]
  1331. if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM
  1332. pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil }
  1333. else
  1334. unless `which pgrep 2> /dev/null`.empty?
  1335. children = pids
  1336. until children.empty?
  1337. children = children.map { |pid|
  1338. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  1339. }.flatten
  1340. pids += children
  1341. end
  1342. end
  1343. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  1344. end
  1345. end
  1346. require 'thread'
  1347. require 'fileutils'
  1348. require 'timeout'
  1349. running = true
  1350. iswin = VIM::evaluate('s:is_win').to_i == 1
  1351. pull = VIM::evaluate('s:update.pull').to_i == 1
  1352. base = VIM::evaluate('g:plug_home')
  1353. all = VIM::evaluate('s:update.todo')
  1354. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  1355. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  1356. nthr = VIM::evaluate('s:update.threads').to_i
  1357. maxy = VIM::evaluate('winheight(".")').to_i
  1358. cd = iswin ? 'cd /d' : 'cd'
  1359. tot = VIM::evaluate('len(s:update.todo)') || 0
  1360. bar = ''
  1361. skip = 'Already installed'
  1362. mtx = Mutex.new
  1363. take1 = proc { mtx.synchronize { running && all.shift } }
  1364. logh = proc {
  1365. cnt = bar.length
  1366. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  1367. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  1368. VIM::command('normal! 2G')
  1369. VIM::command('redraw')
  1370. }
  1371. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  1372. log = proc { |name, result, type|
  1373. mtx.synchronize do
  1374. ing = ![true, false].include?(type)
  1375. bar += type ? '=' : 'x' unless ing
  1376. b = case type
  1377. when :install then '+' when :update then '*'
  1378. when true, nil then '-' else
  1379. VIM::command("call add(s:update.errors, '#{name}')")
  1380. 'x'
  1381. end
  1382. result =
  1383. if type || type.nil?
  1384. ["#{b} #{name}: #{result.lines.to_a.last}"]
  1385. elsif result =~ /^Interrupted|^Timeout/
  1386. ["#{b} #{name}: #{result}"]
  1387. else
  1388. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  1389. end
  1390. if lnum = where.call(name)
  1391. $curbuf.delete lnum
  1392. lnum = 4 if ing && lnum > maxy
  1393. end
  1394. result.each_with_index do |line, offset|
  1395. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  1396. end
  1397. logh.call
  1398. end
  1399. }
  1400. bt = proc { |cmd, name, type, cleanup|
  1401. tried = timeout = 0
  1402. begin
  1403. tried += 1
  1404. timeout += limit
  1405. fd = nil
  1406. data = ''
  1407. if iswin
  1408. Timeout::timeout(timeout) do
  1409. tmp = VIM::evaluate('tempname()')
  1410. system("(#{cmd}) > #{tmp}")
  1411. data = File.read(tmp).chomp
  1412. File.unlink tmp rescue nil
  1413. end
  1414. else
  1415. fd = IO.popen(cmd).extend(PlugStream)
  1416. first_line = true
  1417. log_prob = 1.0 / nthr
  1418. while line = Timeout::timeout(timeout) { fd.get_line }
  1419. data << line
  1420. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  1421. first_line = false
  1422. end
  1423. fd.close
  1424. end
  1425. [$? == 0, data.chomp]
  1426. rescue Timeout::Error, Interrupt => e
  1427. if fd && !fd.closed?
  1428. killall fd.pid
  1429. fd.close
  1430. end
  1431. cleanup.call if cleanup
  1432. if e.is_a?(Timeout::Error) && tried < tries
  1433. 3.downto(1) do |countdown|
  1434. s = countdown > 1 ? 's' : ''
  1435. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  1436. sleep 1
  1437. end
  1438. log.call name, 'Retrying ...', type
  1439. retry
  1440. end
  1441. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  1442. end
  1443. }
  1444. main = Thread.current
  1445. threads = []
  1446. watcher = Thread.new {
  1447. while VIM::evaluate('getchar(1)')
  1448. sleep 0.1
  1449. end
  1450. mtx.synchronize do
  1451. running = false
  1452. threads.each { |t| t.raise Interrupt }
  1453. end
  1454. threads.each { |t| t.join rescue nil }
  1455. main.kill
  1456. }
  1457. refresh = Thread.new {
  1458. while true
  1459. mtx.synchronize do
  1460. break unless running
  1461. VIM::command('noautocmd normal! a')
  1462. end
  1463. sleep 0.2
  1464. end
  1465. } if VIM::evaluate('s:mac_gui') == 1
  1466. clone_opt = VIM::evaluate('s:clone_opt')
  1467. progress = VIM::evaluate('s:progress_opt(1)')
  1468. nthr.times do
  1469. mtx.synchronize do
  1470. threads << Thread.new {
  1471. while pair = take1.call
  1472. name = pair.first
  1473. dir, uri, branch, tag = pair.last.values_at *%w[dir uri branch tag]
  1474. checkout = esc(tag ? tag : branch)
  1475. merge = esc(tag ? tag : "origin/#{branch}")
  1476. subm = "git submodule update --init --recursive 2>&1"
  1477. exists = File.directory? dir
  1478. ok, result =
  1479. if exists
  1480. chdir = "#{cd} #{iswin ? dir : esc(dir)}"
  1481. ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil, nil
  1482. current_uri = data.lines.to_a.last
  1483. if !ret
  1484. if data =~ /^Interrupted|^Timeout/
  1485. [false, data]
  1486. else
  1487. [false, [data.chomp, "PlugClean required."].join($/)]
  1488. end
  1489. elsif current_uri.sub(/git::?@/, '') != uri.sub(/git::?@/, '')
  1490. [false, ["Invalid URI: #{current_uri}",
  1491. "Expected: #{uri}",
  1492. "PlugClean required."].join($/)]
  1493. else
  1494. if pull
  1495. log.call name, 'Updating ...', :update
  1496. fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : ''
  1497. bt.call "#{chdir} && git fetch #{fetch_opt} #{progress} 2>&1 && git checkout -q #{checkout} 2>&1 && git merge --ff-only #{merge} 2>&1 && #{subm}", name, :update, nil
  1498. else
  1499. [true, skip]
  1500. end
  1501. end
  1502. else
  1503. d = esc dir.sub(%r{[\\/]+$}, '')
  1504. log.call name, 'Installing ...', :install
  1505. bt.call "git clone #{clone_opt unless tag} #{progress} --recursive #{uri} -b #{checkout} #{d} 2>&1", name, :install, proc {
  1506. FileUtils.rm_rf dir
  1507. }
  1508. end
  1509. mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
  1510. log.call name, result, ok
  1511. end
  1512. } if running
  1513. end
  1514. end
  1515. threads.each { |t| t.join rescue nil }
  1516. logh.call
  1517. refresh.kill if refresh
  1518. watcher.kill
  1519. EOF
  1520. endfunction
  1521. function! s:shellesc(arg)
  1522. return '"'.escape(a:arg, '"').'"'
  1523. endfunction
  1524. function! s:glob_dir(path)
  1525. return map(filter(s:lines(globpath(a:path, '**')), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  1526. endfunction
  1527. function! s:progress_bar(line, bar, total)
  1528. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  1529. endfunction
  1530. function! s:compare_git_uri(a, b)
  1531. let a = substitute(a:a, 'git:\{1,2}@', '', '')
  1532. let b = substitute(a:b, 'git:\{1,2}@', '', '')
  1533. return a ==# b
  1534. endfunction
  1535. function! s:format_message(bullet, name, message)
  1536. if a:bullet != 'x'
  1537. return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
  1538. else
  1539. let lines = map(s:lines(a:message), '" ".v:val')
  1540. return extend([printf('x %s:', a:name)], lines)
  1541. endif
  1542. endfunction
  1543. function! s:with_cd(cmd, dir)
  1544. return printf('cd%s %s && %s', s:is_win ? ' /d' : '', s:shellesc(a:dir), a:cmd)
  1545. endfunction
  1546. function! s:system(cmd, ...)
  1547. try
  1548. let [sh, shrd] = [&shell, &shellredir]
  1549. if !s:is_win
  1550. set shell=sh shellredir=>%s\ 2>&1
  1551. endif
  1552. let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
  1553. return system(s:is_win ? '('.cmd.')' : cmd)
  1554. finally
  1555. let [&shell, &shellredir] = [sh, shrd]
  1556. endtry
  1557. endfunction
  1558. function! s:system_chomp(...)
  1559. let ret = call('s:system', a:000)
  1560. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  1561. endfunction
  1562. function! s:git_validate(spec, check_branch)
  1563. let err = ''
  1564. if isdirectory(a:spec.dir)
  1565. let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url', a:spec.dir))
  1566. let remote = result[-1]
  1567. if v:shell_error
  1568. let err = join([remote, 'PlugClean required.'], "\n")
  1569. elseif !s:compare_git_uri(remote, a:spec.uri)
  1570. let err = join(['Invalid URI: '.remote,
  1571. \ 'Expected: '.a:spec.uri,
  1572. \ 'PlugClean required.'], "\n")
  1573. elseif a:check_branch && has_key(a:spec, 'commit')
  1574. let result = s:lines(s:system('git rev-parse HEAD 2>&1', a:spec.dir))
  1575. let sha = result[-1]
  1576. if v:shell_error
  1577. let err = join(add(result, 'PlugClean required.'), "\n")
  1578. elseif !s:hash_match(sha, a:spec.commit)
  1579. let err = join([printf('Invalid HEAD (expected: %s, actual: %s)',
  1580. \ a:spec.commit[:6], sha[:6]),
  1581. \ 'PlugUpdate required.'], "\n")
  1582. endif
  1583. elseif a:check_branch
  1584. let branch = result[0]
  1585. " Check tag
  1586. if has_key(a:spec, 'tag')
  1587. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
  1588. if a:spec.tag !=# tag
  1589. let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.',
  1590. \ (empty(tag) ? 'N/A' : tag), a:spec.tag)
  1591. endif
  1592. " Check branch
  1593. elseif a:spec.branch !=# branch
  1594. let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.',
  1595. \ branch, a:spec.branch)
  1596. endif
  1597. endif
  1598. else
  1599. let err = 'Not found'
  1600. endif
  1601. return err
  1602. endfunction
  1603. function! s:rm_rf(dir)
  1604. if isdirectory(a:dir)
  1605. call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(a:dir))
  1606. endif
  1607. endfunction
  1608. function! s:clean(force)
  1609. call s:prepare()
  1610. call append(0, 'Searching for unused plugins in '.g:plug_home)
  1611. call append(1, '')
  1612. " List of valid directories
  1613. let dirs = []
  1614. let [cnt, total] = [0, len(g:plugs)]
  1615. for [name, spec] in items(g:plugs)
  1616. if !s:is_managed(name) || empty(s:git_validate(spec, 0))
  1617. call add(dirs, spec.dir)
  1618. endif
  1619. let cnt += 1
  1620. call s:progress_bar(2, repeat('=', cnt), total)
  1621. normal! 2G
  1622. redraw
  1623. endfor
  1624. let allowed = {}
  1625. for dir in dirs
  1626. let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
  1627. let allowed[dir] = 1
  1628. for child in s:glob_dir(dir)
  1629. let allowed[child] = 1
  1630. endfor
  1631. endfor
  1632. let todo = []
  1633. let found = sort(s:glob_dir(g:plug_home))
  1634. while !empty(found)
  1635. let f = remove(found, 0)
  1636. if !has_key(allowed, f) && isdirectory(f)
  1637. call add(todo, f)
  1638. call append(line('$'), '- ' . f)
  1639. let found = filter(found, 'stridx(v:val, f) != 0')
  1640. end
  1641. endwhile
  1642. normal! G
  1643. redraw
  1644. if empty(todo)
  1645. call append(line('$'), 'Already clean.')
  1646. else
  1647. if a:force || s:ask('Proceed?')
  1648. for dir in todo
  1649. call s:rm_rf(dir)
  1650. endfor
  1651. call append(line('$'), 'Removed.')
  1652. else
  1653. call append(line('$'), 'Cancelled.')
  1654. endif
  1655. endif
  1656. normal! G
  1657. endfunction
  1658. function! s:upgrade()
  1659. echo 'Downloading the latest version of vim-plug'
  1660. redraw
  1661. let tmp = tempname()
  1662. let new = tmp . '/plug.vim'
  1663. try
  1664. let out = s:system(printf('git clone --depth 1 %s %s', s:plug_src, tmp))
  1665. if v:shell_error
  1666. return s:err('Error upgrading vim-plug: '. out)
  1667. endif
  1668. if readfile(s:me) ==# readfile(new)
  1669. echo 'vim-plug is already up-to-date'
  1670. return 0
  1671. else
  1672. call rename(s:me, s:me . '.old')
  1673. call rename(new, s:me)
  1674. unlet g:loaded_plug
  1675. echo 'vim-plug has been upgraded'
  1676. return 1
  1677. endif
  1678. finally
  1679. silent! call s:rm_rf(tmp)
  1680. endtry
  1681. endfunction
  1682. function! s:upgrade_specs()
  1683. for spec in values(g:plugs)
  1684. let spec.frozen = get(spec, 'frozen', 0)
  1685. endfor
  1686. endfunction
  1687. function! s:status()
  1688. call s:prepare()
  1689. call append(0, 'Checking plugins')
  1690. call append(1, '')
  1691. let ecnt = 0
  1692. let unloaded = 0
  1693. let [cnt, total] = [0, len(g:plugs)]
  1694. for [name, spec] in items(g:plugs)
  1695. if has_key(spec, 'uri')
  1696. if isdirectory(spec.dir)
  1697. let err = s:git_validate(spec, 1)
  1698. let [valid, msg] = [empty(err), empty(err) ? 'OK' : err]
  1699. else
  1700. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  1701. endif
  1702. else
  1703. if isdirectory(spec.dir)
  1704. let [valid, msg] = [1, 'OK']
  1705. else
  1706. let [valid, msg] = [0, 'Not found.']
  1707. endif
  1708. endif
  1709. let cnt += 1
  1710. let ecnt += !valid
  1711. " `s:loaded` entry can be missing if PlugUpgraded
  1712. if valid && get(s:loaded, name, -1) == 0
  1713. let unloaded = 1
  1714. let msg .= ' (not loaded)'
  1715. endif
  1716. call s:progress_bar(2, repeat('=', cnt), total)
  1717. call append(3, s:format_message(valid ? '-' : 'x', name, msg))
  1718. normal! 2G
  1719. redraw
  1720. endfor
  1721. call setline(1, 'Finished. '.ecnt.' error(s).')
  1722. normal! gg
  1723. setlocal nomodifiable
  1724. if unloaded
  1725. echo "Press 'L' on each line to load plugin, or 'U' to update"
  1726. nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1727. xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1728. end
  1729. endfunction
  1730. function! s:extract_name(str, prefix, suffix)
  1731. return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
  1732. endfunction
  1733. function! s:status_load(lnum)
  1734. let line = getline(a:lnum)
  1735. let name = s:extract_name(line, '-', '(not loaded)')
  1736. if !empty(name)
  1737. call plug#load(name)
  1738. setlocal modifiable
  1739. call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
  1740. setlocal nomodifiable
  1741. endif
  1742. endfunction
  1743. function! s:status_update() range
  1744. let lines = getline(a:firstline, a:lastline)
  1745. let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
  1746. if !empty(names)
  1747. echo
  1748. execute 'PlugUpdate' join(names)
  1749. endif
  1750. endfunction
  1751. function! s:is_preview_window_open()
  1752. silent! wincmd P
  1753. if &previewwindow
  1754. wincmd p
  1755. return 1
  1756. endif
  1757. return 0
  1758. endfunction
  1759. function! s:find_name(lnum)
  1760. for lnum in reverse(range(1, a:lnum))
  1761. let line = getline(lnum)
  1762. if empty(line)
  1763. return ''
  1764. endif
  1765. let name = s:extract_name(line, '-', '')
  1766. if !empty(name)
  1767. return name
  1768. endif
  1769. endfor
  1770. return ''
  1771. endfunction
  1772. function! s:preview_commit()
  1773. if b:plug_preview < 0
  1774. let b:plug_preview = !s:is_preview_window_open()
  1775. endif
  1776. let sha = matchstr(getline('.'), '\(^ \)\@<=[0-9a-z]\{7}')
  1777. if empty(sha)
  1778. return
  1779. endif
  1780. let name = s:find_name(line('.'))
  1781. if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
  1782. return
  1783. endif
  1784. execute 'pedit' sha
  1785. wincmd P
  1786. setlocal filetype=git buftype=nofile nobuflisted modifiable
  1787. execute 'silent read !cd' s:shellesc(g:plugs[name].dir) '&& git show --pretty=medium' sha
  1788. normal! gg"_dd
  1789. setlocal nomodifiable
  1790. nnoremap <silent> <buffer> q :q<cr>
  1791. wincmd p
  1792. endfunction
  1793. function! s:section(flags)
  1794. call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
  1795. endfunction
  1796. function! s:format_git_log(line)
  1797. let [sha, refs, subject, date] = split(a:line, nr2char(1))
  1798. let tag = matchstr(refs, 'tag: [^,)]\+')
  1799. let tag = empty(tag) ? ' ' : ' ('.tag.') '
  1800. return printf(' %s%s%s (%s)', sha, tag, subject, date)
  1801. endfunction
  1802. function! s:append_ul(lnum, text)
  1803. call append(a:lnum, ['', a:text, repeat('-', len(a:text))])
  1804. endfunction
  1805. function! s:diff()
  1806. call s:prepare()
  1807. call append(0, ['Collecting changes ...', ''])
  1808. let cnts = [0, 0]
  1809. let bar = ''
  1810. let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)')
  1811. call s:progress_bar(2, bar, len(total))
  1812. for origin in [1, 0]
  1813. call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:')
  1814. for [k, v] in reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))'))))
  1815. let range = origin ? '..origin/'.v.branch : 'HEAD@{1}..'
  1816. let diff = s:system_chomp('git log --pretty=format:"%h%x01%d%x01%s%x01%cr" '.s:shellesc(range), v.dir)
  1817. if !empty(diff)
  1818. let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : ''
  1819. call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)')))
  1820. let cnts[origin] += 1
  1821. endif
  1822. let bar .= '='
  1823. call s:progress_bar(2, bar, len(total))
  1824. normal! 2G
  1825. redraw
  1826. endfor
  1827. if !cnts[origin]
  1828. call append(5, ['', 'N/A'])
  1829. endif
  1830. endfor
  1831. call setline(1, printf('%d plugin(s) updated.', cnts[0])
  1832. \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : ''))
  1833. if cnts[0] || cnts[1]
  1834. nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
  1835. nnoremap <silent> <buffer> o :silent! call <SID>preview_commit()<cr>
  1836. endif
  1837. if cnts[0]
  1838. nnoremap <silent> <buffer> X :call <SID>revert()<cr>
  1839. echo "Press 'X' on each block to revert the update"
  1840. endif
  1841. normal! gg
  1842. setlocal nomodifiable
  1843. endfunction
  1844. function! s:revert()
  1845. if search('^Pending updates', 'bnW')
  1846. return
  1847. endif
  1848. let name = s:find_name(line('.'))
  1849. if empty(name) || !has_key(g:plugs, name) ||
  1850. \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
  1851. return
  1852. endif
  1853. call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir)
  1854. setlocal modifiable
  1855. normal! "_dap
  1856. setlocal nomodifiable
  1857. echo 'Reverted.'
  1858. endfunction
  1859. function! s:snapshot(force, ...) abort
  1860. call s:prepare()
  1861. setf vim
  1862. call append(0, ['" Generated by vim-plug',
  1863. \ '" '.strftime("%c"),
  1864. \ '" :source this file in vim to restore the snapshot',
  1865. \ '" or execute: vim -S snapshot.vim',
  1866. \ '', '', 'PlugUpdate!'])
  1867. 1
  1868. let anchor = line('$') - 3
  1869. let names = sort(keys(filter(copy(g:plugs),
  1870. \'has_key(v:val, "uri") && !has_key(v:val, "commit") && isdirectory(v:val.dir)')))
  1871. for name in reverse(names)
  1872. let sha = s:system_chomp('git rev-parse --short HEAD', g:plugs[name].dir)
  1873. if !empty(sha)
  1874. call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha))
  1875. redraw
  1876. endif
  1877. endfor
  1878. if a:0 > 0
  1879. let fn = expand(a:1)
  1880. if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?'))
  1881. return
  1882. endif
  1883. call writefile(getline(1, '$'), fn)
  1884. echo 'Saved as '.a:1
  1885. silent execute 'e' s:esc(fn)
  1886. setf vim
  1887. endif
  1888. endfunction
  1889. function! s:split_rtp()
  1890. return split(&rtp, '\\\@<!,')
  1891. endfunction
  1892. let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
  1893. let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
  1894. if exists('g:plugs')
  1895. let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
  1896. call s:upgrade_specs()
  1897. call s:define_commands()
  1898. endif
  1899. let &cpo = s:cpo_save
  1900. unlet s:cpo_save