plug.vim 56 KB

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