plug.vim 57 KB

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