plug.vim 58 KB

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