plug.vim 57 KB

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