plug.vim 62 KB

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