plug.vim 58 KB

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