plug.vim 61 KB

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