plug.vim 55 KB

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