plug.vim 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176
  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: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-z]\{4,}$/
  509. syn match plugTag /(tag: [^)]\+)/
  510. syn match plugInstall /\(^+ \)\@<=[^:]*/
  511. syn match plugUpdate /\(^* \)\@<=[^:]*/
  512. syn match plugCommit /^ \X*[0-9a-z]\{7} .*/ contains=plugRelDate,plugEdge,plugTag
  513. syn match plugEdge /^ \X\+$/
  514. syn match plugEdge /^ \X*/ contained nextgroup=plugSha
  515. syn match plugSha /[0-9a-z]\{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:do(pull, force, todo)
  633. for [name, spec] in items(a:todo)
  634. if !isdirectory(spec.dir)
  635. continue
  636. endif
  637. let installed = has_key(s:update.new, name)
  638. let updated = installed ? 0 :
  639. \ (a:pull && index(s:update.errors, name) < 0 && !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', spec.dir)))
  640. if a:force || installed || updated
  641. execute 'cd' s:esc(spec.dir)
  642. call append(3, '- Post-update hook for '. name .' ... ')
  643. let error = ''
  644. let type = type(spec.do)
  645. if type == s:TYPE.string
  646. try
  647. " FIXME: Escaping is incomplete. We could use shellescape with eval,
  648. " but it won't work on Windows.
  649. let g:_plug_do = '!'.escape(spec.do, '#!%')
  650. execute "normal! :execute g:_plug_do\<cr>\<cr>"
  651. finally
  652. if v:shell_error
  653. let error = 'Exit status: ' . v:shell_error
  654. endif
  655. unlet g:_plug_do
  656. endtry
  657. elseif type == s:TYPE.funcref
  658. try
  659. let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
  660. call spec.do({ 'name': name, 'status': status, 'force': a:force })
  661. catch
  662. let error = v:exception
  663. endtry
  664. else
  665. let error = 'Invalid hook type'
  666. endif
  667. call setline(4, empty(error) ? (getline(4) . 'OK')
  668. \ : ('x' . getline(4)[1:] . error))
  669. cd -
  670. endif
  671. endfor
  672. endfunction
  673. function! s:hash_match(a, b)
  674. return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0
  675. endfunction
  676. function! s:checkout(plugs)
  677. for [name, spec] in items(a:plugs)
  678. let sha = spec.commit
  679. call append(3, '- Checking out '.sha[:6].' of '.name.' ... ')
  680. redraw
  681. let error = []
  682. let output = s:lines(s:system('git rev-parse HEAD', spec.dir))
  683. if v:shell_error
  684. let error = output
  685. elseif !s:hash_match(sha, output[0])
  686. let output = s:lines(s:system(
  687. \ 'git fetch --depth 999999 && git checkout '.sha, spec.dir))
  688. if v:shell_error
  689. let error = output
  690. endif
  691. endif
  692. if empty(error)
  693. call setline(4, getline(4) . 'OK')
  694. else
  695. call setline(4, 'x'.getline(4)[1:] . 'Error')
  696. for line in reverse(error)
  697. call append(4, ' '.line)
  698. endfor
  699. endif
  700. endfor
  701. endfunction
  702. function! s:finish(pull)
  703. let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
  704. if new_frozen
  705. let s = new_frozen > 1 ? 's' : ''
  706. call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
  707. endif
  708. call append(3, '- Finishing ... ')
  709. redraw
  710. call plug#helptags()
  711. call plug#end()
  712. call setline(4, getline(4) . 'Done!')
  713. redraw
  714. let msgs = []
  715. if !empty(s:update.errors)
  716. call add(msgs, "Press 'R' to retry.")
  717. endif
  718. if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
  719. \ "v:val =~ '^- ' && stridx(v:val, 'Already up-to-date') < 0"))
  720. call add(msgs, "Press 'D' to see the updated changes.")
  721. endif
  722. echo join(msgs, ' ')
  723. call s:finish_bindings()
  724. endfunction
  725. function! s:retry()
  726. if empty(s:update.errors)
  727. return
  728. endif
  729. call s:update_impl(s:update.pull, s:update.force,
  730. \ extend(copy(s:update.errors), [s:update.threads]))
  731. endfunction
  732. function! s:is_managed(name)
  733. return has_key(g:plugs[a:name], 'uri')
  734. endfunction
  735. function! s:names(...)
  736. return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
  737. endfunction
  738. function! s:update_impl(pull, force, args) abort
  739. let args = copy(a:args)
  740. let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
  741. \ remove(args, -1) : get(g:, 'plug_threads', 16)
  742. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  743. let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
  744. \ filter(managed, 'index(args, v:key) >= 0')
  745. if empty(todo)
  746. echohl WarningMsg
  747. echo 'No plugin to '. (a:pull ? 'update' : 'install') . '.'
  748. echohl None
  749. return
  750. endif
  751. if !s:is_win && s:git_version_requirement(2, 3)
  752. let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : ''
  753. let $GIT_TERMINAL_PROMPT = 0
  754. for plug in values(todo)
  755. let plug.uri = substitute(plug.uri,
  756. \ '^https://git::@github\.com', 'https://github.com', '')
  757. endfor
  758. endif
  759. if !isdirectory(g:plug_home)
  760. try
  761. call mkdir(g:plug_home, 'p')
  762. catch
  763. return s:err(printf('Invalid plug directory: %s. '.
  764. \ 'Try to call plug#begin with a valid directory', g:plug_home))
  765. endtry
  766. endif
  767. if has('nvim') && !exists('*jobwait') && threads > 1
  768. echohl WarningMsg
  769. echomsg 'vim-plug: update Neovim for parallel installer'
  770. echohl None
  771. endif
  772. let python = (has('python') || has('python3')) && (!s:nvim || has('vim_starting'))
  773. let ruby = has('ruby') && !s:nvim && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running'))
  774. let s:update = {
  775. \ 'start': reltime(),
  776. \ 'all': todo,
  777. \ 'todo': copy(todo),
  778. \ 'errors': [],
  779. \ 'pull': a:pull,
  780. \ 'force': a:force,
  781. \ 'new': {},
  782. \ 'threads': (python || ruby || s:nvim) ? min([len(todo), threads]) : 1,
  783. \ 'bar': '',
  784. \ 'fin': 0
  785. \ }
  786. call s:prepare(1)
  787. call append(0, ['', ''])
  788. normal! 2G
  789. silent! redraw
  790. let s:clone_opt = get(g:, 'plug_shallow', 1) ?
  791. \ '--depth 1' . (s:git_version_requirement(1, 7, 10) ? ' --no-single-branch' : '') : ''
  792. " Python version requirement (>= 2.7)
  793. if python && !has('python3') && !ruby && !s:nvim && s:update.threads > 1
  794. redir => pyv
  795. silent python import platform; print platform.python_version()
  796. redir END
  797. let python = s:version_requirement(
  798. \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6])
  799. endif
  800. if (python || ruby) && s:update.threads > 1
  801. try
  802. let imd = &imd
  803. if s:mac_gui
  804. set noimd
  805. endif
  806. if ruby
  807. call s:update_ruby()
  808. else
  809. call s:update_python()
  810. endif
  811. catch
  812. let lines = getline(4, '$')
  813. let printed = {}
  814. silent! 4,$d _
  815. for line in lines
  816. let name = s:extract_name(line, '.', '')
  817. if empty(name) || !has_key(printed, name)
  818. call append('$', line)
  819. if !empty(name)
  820. let printed[name] = 1
  821. if line[0] == 'x' && index(s:update.errors, name) < 0
  822. call add(s:update.errors, name)
  823. end
  824. endif
  825. endif
  826. endfor
  827. finally
  828. let &imd = imd
  829. call s:update_finish()
  830. endtry
  831. else
  832. call s:update_vim()
  833. endif
  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 s:checkout(filter(copy(s:update.all), 'has_key(v:val, "commit")'))
  841. call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'has_key(v:val, "do")'))
  842. call s:finish(s:update.pull)
  843. call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
  844. call s:switch_out('normal! gg')
  845. endif
  846. endfunction
  847. function! s:job_abort()
  848. if !s:nvim || !exists('s:jobs')
  849. return
  850. endif
  851. for [name, j] in items(s:jobs)
  852. silent! call jobstop(j.jobid)
  853. if j.new
  854. call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir))
  855. endif
  856. endfor
  857. let s:jobs = {}
  858. endfunction
  859. " When a:event == 'stdout', data = list of strings
  860. " When a:event == 'exit', data = returncode
  861. function! s:job_handler(job_id, data, event) abort
  862. if !s:plug_window_exists() " plug window closed
  863. return s:job_abort()
  864. endif
  865. if a:event == 'stdout'
  866. let complete = empty(a:data[-1])
  867. let lines = map(filter(a:data, 'len(v:val) > 0'), 'split(v:val, "[\r\n]")[-1]')
  868. call extend(self.lines, lines)
  869. let self.result = join(self.lines, "\n")
  870. if !complete
  871. call remove(self.lines, -1)
  872. endif
  873. " To reduce the number of buffer updates
  874. let self.tick = get(self, 'tick', -1) + 1
  875. if self.tick % len(s:jobs) == 0
  876. call s:log(self.new ? '+' : '*', self.name, self.result)
  877. endif
  878. elseif a:event == 'exit'
  879. let self.running = 0
  880. if a:data != 0
  881. let self.error = 1
  882. endif
  883. call s:reap(self.name)
  884. call s:tick()
  885. endif
  886. endfunction
  887. function! s:spawn(name, cmd, opts)
  888. let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [], 'result': '',
  889. \ 'new': get(a:opts, 'new', 0),
  890. \ 'on_stdout': function('s:job_handler'),
  891. \ 'on_exit' : function('s:job_handler'),
  892. \ }
  893. let s:jobs[a:name] = job
  894. if s:nvim
  895. let argv = [ 'sh', '-c',
  896. \ (has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd) ]
  897. let jid = jobstart(argv, job)
  898. if jid > 0
  899. let job.jobid = jid
  900. else
  901. let job.running = 0
  902. let job.error = 1
  903. let job.result = jid < 0 ? 'sh is not executable' :
  904. \ 'Invalid arguments (or job table is full)'
  905. endif
  906. else
  907. let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd]
  908. let job.result = call('s:system', params)
  909. let job.error = v:shell_error != 0
  910. let job.running = 0
  911. endif
  912. endfunction
  913. function! s:reap(name)
  914. let job = s:jobs[a:name]
  915. if job.error
  916. call add(s:update.errors, a:name)
  917. elseif get(job, 'new', 0)
  918. let s:update.new[a:name] = 1
  919. endif
  920. let s:update.bar .= job.error ? 'x' : '='
  921. call s:log(job.error ? 'x' : '-', a:name, job.result)
  922. call s:bar()
  923. call remove(s:jobs, a:name)
  924. endfunction
  925. function! s:bar()
  926. if s:switch_in()
  927. let total = len(s:update.all)
  928. call setline(1, (s:update.pull ? 'Updating' : 'Installing').
  929. \ ' plugins ('.len(s:update.bar).'/'.total.')')
  930. call s:progress_bar(2, s:update.bar, total)
  931. call s:switch_out()
  932. endif
  933. endfunction
  934. function! s:logpos(name)
  935. for i in range(1, line('$'))
  936. if getline(i) =~# '^[-+x*] '.a:name.':'
  937. return i
  938. endif
  939. endfor
  940. return 0
  941. endfunction
  942. function! s:log(bullet, name, lines)
  943. if s:switch_in()
  944. let pos = s:logpos(a:name)
  945. if pos > 0
  946. execute pos 'd _'
  947. if pos > winheight('.')
  948. let pos = 4
  949. endif
  950. else
  951. let pos = 4
  952. endif
  953. call append(pos - 1, s:format_message(a:bullet, a:name, a:lines))
  954. call s:switch_out()
  955. endif
  956. endfunction
  957. function! s:update_vim()
  958. let s:jobs = {}
  959. call s:bar()
  960. call s:tick()
  961. endfunction
  962. function! s:tick()
  963. let pull = s:update.pull
  964. let prog = s:progress_opt(s:nvim)
  965. while 1 " Without TCO, Vim stack is bound to explode
  966. if empty(s:update.todo)
  967. if empty(s:jobs) && !s:update.fin
  968. let s:update.fin = 1
  969. call s:update_finish()
  970. endif
  971. return
  972. endif
  973. let name = keys(s:update.todo)[0]
  974. let spec = remove(s:update.todo, name)
  975. let new = !isdirectory(spec.dir)
  976. call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
  977. redraw
  978. let has_tag = has_key(spec, 'tag')
  979. let checkout = s:shellesc(has_tag ? spec.tag : spec.branch)
  980. let merge = s:shellesc(has_tag ? spec.tag : 'origin/'.spec.branch)
  981. if !new
  982. let error = s:git_validate(spec, 0)
  983. if empty(error)
  984. if pull
  985. let fetch_opt = (has_tag && !empty(globpath(spec.dir, '.git/shallow'))) ? '--depth 99999999' : ''
  986. call s:spawn(name,
  987. \ 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)',
  988. \ fetch_opt, prog, checkout, merge), { 'dir': spec.dir })
  989. else
  990. let s:jobs[name] = { 'running': 0, 'result': 'Already installed', 'error': 0 }
  991. endif
  992. else
  993. let s:jobs[name] = { 'running': 0, 'result': error, 'error': 1 }
  994. endif
  995. else
  996. call s:spawn(name,
  997. \ printf('git clone %s %s --recursive %s -b %s %s 2>&1',
  998. \ has_tag ? '' : s:clone_opt,
  999. \ prog,
  1000. \ s:shellesc(spec.uri),
  1001. \ checkout,
  1002. \ s:shellesc(s:trim(spec.dir))), { 'new': 1 })
  1003. endif
  1004. if !s:jobs[name].running
  1005. call s:reap(name)
  1006. endif
  1007. if len(s:jobs) >= s:update.threads
  1008. break
  1009. endif
  1010. endwhile
  1011. endfunction
  1012. function! s:update_python()
  1013. let py_exe = has('python') ? 'python' : 'python3'
  1014. execute py_exe "<< EOF"
  1015. import datetime
  1016. import functools
  1017. import os
  1018. try:
  1019. import queue
  1020. except ImportError:
  1021. import Queue as queue
  1022. import random
  1023. import re
  1024. import shutil
  1025. import signal
  1026. import subprocess
  1027. import tempfile
  1028. import threading as thr
  1029. import time
  1030. import traceback
  1031. import vim
  1032. G_NVIM = vim.eval("has('nvim')") == '1'
  1033. G_PULL = vim.eval('s:update.pull') == '1'
  1034. G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1
  1035. G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)'))
  1036. G_CLONE_OPT = vim.eval('s:clone_opt')
  1037. G_PROGRESS = vim.eval('s:progress_opt(1)')
  1038. G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads'))
  1039. G_STOP = thr.Event()
  1040. G_IS_WIN = vim.eval('s:is_win') == '1'
  1041. class PlugError(Exception):
  1042. def __init__(self, msg):
  1043. self.msg = msg
  1044. class CmdTimedOut(PlugError):
  1045. pass
  1046. class CmdFailed(PlugError):
  1047. pass
  1048. class InvalidURI(PlugError):
  1049. pass
  1050. class Action(object):
  1051. INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-']
  1052. class Buffer(object):
  1053. def __init__(self, lock, num_plugs, is_pull):
  1054. self.bar = ''
  1055. self.event = 'Updating' if is_pull else 'Installing'
  1056. self.lock = lock
  1057. self.maxy = int(vim.eval('winheight(".")'))
  1058. self.num_plugs = num_plugs
  1059. def __where(self, name):
  1060. """ Find first line with name in current buffer. Return line num. """
  1061. found, lnum = False, 0
  1062. matcher = re.compile('^[-+x*] {0}:'.format(name))
  1063. for line in vim.current.buffer:
  1064. if matcher.search(line) is not None:
  1065. found = True
  1066. break
  1067. lnum += 1
  1068. if not found:
  1069. lnum = -1
  1070. return lnum
  1071. def header(self):
  1072. curbuf = vim.current.buffer
  1073. curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs)
  1074. num_spaces = self.num_plugs - len(self.bar)
  1075. curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ')
  1076. with self.lock:
  1077. vim.command('normal! 2G')
  1078. vim.command('redraw')
  1079. def write(self, action, name, lines):
  1080. first, rest = lines[0], lines[1:]
  1081. msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)]
  1082. msg.extend([' ' + line for line in rest])
  1083. try:
  1084. if action == Action.ERROR:
  1085. self.bar += 'x'
  1086. vim.command("call add(s:update.errors, '{0}')".format(name))
  1087. elif action == Action.DONE:
  1088. self.bar += '='
  1089. curbuf = vim.current.buffer
  1090. lnum = self.__where(name)
  1091. if lnum != -1: # Found matching line num
  1092. del curbuf[lnum]
  1093. if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]):
  1094. lnum = 3
  1095. else:
  1096. lnum = 3
  1097. curbuf.append(msg, lnum)
  1098. self.header()
  1099. except vim.error:
  1100. pass
  1101. class Command(object):
  1102. CD = 'cd /d' if G_IS_WIN else 'cd'
  1103. def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None):
  1104. self.cmd = cmd
  1105. if cmd_dir:
  1106. self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd)
  1107. self.timeout = timeout
  1108. self.callback = cb if cb else (lambda msg: None)
  1109. self.clean = clean if clean else (lambda: None)
  1110. self.proc = None
  1111. @property
  1112. def alive(self):
  1113. """ Returns true only if command still running. """
  1114. return self.proc and self.proc.poll() is None
  1115. def execute(self, ntries=3):
  1116. """ Execute the command with ntries if CmdTimedOut.
  1117. Returns the output of the command if no Exception.
  1118. """
  1119. attempt, finished, limit = 0, False, self.timeout
  1120. while not finished:
  1121. try:
  1122. attempt += 1
  1123. result = self.try_command()
  1124. finished = True
  1125. return result
  1126. except CmdTimedOut:
  1127. if attempt != ntries:
  1128. self.notify_retry()
  1129. self.timeout += limit
  1130. else:
  1131. raise
  1132. def notify_retry(self):
  1133. """ Retry required for command, notify user. """
  1134. for count in range(3, 0, -1):
  1135. if G_STOP.is_set():
  1136. raise KeyboardInterrupt
  1137. msg = 'Timeout. Will retry in {0} second{1} ...'.format(
  1138. count, 's' if count != 1 else '')
  1139. self.callback([msg])
  1140. time.sleep(1)
  1141. self.callback(['Retrying ...'])
  1142. def try_command(self):
  1143. """ Execute a cmd & poll for callback. Returns list of output.
  1144. Raises CmdFailed -> return code for Popen isn't 0
  1145. Raises CmdTimedOut -> command exceeded timeout without new output
  1146. """
  1147. first_line = True
  1148. try:
  1149. tfile = tempfile.NamedTemporaryFile(mode='w+b')
  1150. preexec_fn = not G_IS_WIN and os.setsid or None
  1151. self.proc = subprocess.Popen(self.cmd, stdout=tfile,
  1152. stderr=subprocess.STDOUT,
  1153. stdin=subprocess.PIPE, shell=True,
  1154. preexec_fn=preexec_fn)
  1155. thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,))
  1156. thrd.start()
  1157. thread_not_started = True
  1158. while thread_not_started:
  1159. try:
  1160. thrd.join(0.1)
  1161. thread_not_started = False
  1162. except RuntimeError:
  1163. pass
  1164. while self.alive:
  1165. if G_STOP.is_set():
  1166. raise KeyboardInterrupt
  1167. if first_line or random.random() < G_LOG_PROB:
  1168. first_line = False
  1169. line = '' if G_IS_WIN else nonblock_read(tfile.name)
  1170. if line:
  1171. self.callback([line])
  1172. time_diff = time.time() - os.path.getmtime(tfile.name)
  1173. if time_diff > self.timeout:
  1174. raise CmdTimedOut(['Timeout!'])
  1175. thrd.join(0.5)
  1176. tfile.seek(0)
  1177. result = [line.decode('utf-8', 'replace').rstrip() for line in tfile]
  1178. if self.proc.returncode != 0:
  1179. raise CmdFailed([''] + result)
  1180. return result
  1181. except:
  1182. self.terminate()
  1183. raise
  1184. def terminate(self):
  1185. """ Terminate process and cleanup. """
  1186. if self.alive:
  1187. if G_IS_WIN:
  1188. os.kill(self.proc.pid, signal.SIGINT)
  1189. else:
  1190. os.killpg(self.proc.pid, signal.SIGTERM)
  1191. self.clean()
  1192. class Plugin(object):
  1193. def __init__(self, name, args, buf_q, lock):
  1194. self.name = name
  1195. self.args = args
  1196. self.buf_q = buf_q
  1197. self.lock = lock
  1198. tag = args.get('tag', 0)
  1199. self.checkout = esc(tag if tag else args['branch'])
  1200. self.merge = esc(tag if tag else 'origin/' + args['branch'])
  1201. self.tag = tag
  1202. def manage(self):
  1203. try:
  1204. if os.path.exists(self.args['dir']):
  1205. self.update()
  1206. else:
  1207. self.install()
  1208. with self.lock:
  1209. thread_vim_command("let s:update.new['{0}'] = 1".format(self.name))
  1210. except PlugError as exc:
  1211. self.write(Action.ERROR, self.name, exc.msg)
  1212. except KeyboardInterrupt:
  1213. G_STOP.set()
  1214. self.write(Action.ERROR, self.name, ['Interrupted!'])
  1215. except:
  1216. # Any exception except those above print stack trace
  1217. msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip())
  1218. self.write(Action.ERROR, self.name, msg.split('\n'))
  1219. raise
  1220. def install(self):
  1221. target = self.args['dir']
  1222. if target[-1] == '\\':
  1223. target = target[0:-1]
  1224. def clean(target):
  1225. def _clean():
  1226. try:
  1227. shutil.rmtree(target)
  1228. except OSError:
  1229. pass
  1230. return _clean
  1231. self.write(Action.INSTALL, self.name, ['Installing ...'])
  1232. callback = functools.partial(self.write, Action.INSTALL, self.name)
  1233. cmd = 'git clone {0} {1} --recursive {2} -b {3} {4} 2>&1'.format(
  1234. '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'],
  1235. self.checkout, esc(target))
  1236. com = Command(cmd, None, G_TIMEOUT, callback, clean(target))
  1237. result = com.execute(G_RETRIES)
  1238. self.write(Action.DONE, self.name, result[-1:])
  1239. def repo_uri(self):
  1240. cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url'
  1241. command = Command(cmd, self.args['dir'], G_TIMEOUT,)
  1242. result = command.execute(G_RETRIES)
  1243. return result[-1]
  1244. def update(self):
  1245. match = re.compile(r'git::?@')
  1246. actual_uri = re.sub(match, '', self.repo_uri())
  1247. expect_uri = re.sub(match, '', self.args['uri'])
  1248. if actual_uri != expect_uri:
  1249. msg = ['',
  1250. 'Invalid URI: {0}'.format(actual_uri),
  1251. 'Expected {0}'.format(expect_uri),
  1252. 'PlugClean required.']
  1253. raise InvalidURI(msg)
  1254. if G_PULL:
  1255. self.write(Action.UPDATE, self.name, ['Updating ...'])
  1256. callback = functools.partial(self.write, Action.UPDATE, self.name)
  1257. fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else ''
  1258. cmds = ['git fetch {0} {1}'.format(fetch_opt, G_PROGRESS),
  1259. 'git checkout -q {0}'.format(self.checkout),
  1260. 'git merge --ff-only {0}'.format(self.merge),
  1261. 'git submodule update --init --recursive']
  1262. cmd = ' 2>&1 && '.join(cmds)
  1263. com = Command(cmd, self.args['dir'], G_TIMEOUT, callback)
  1264. result = com.execute(G_RETRIES)
  1265. self.write(Action.DONE, self.name, result[-1:])
  1266. else:
  1267. self.write(Action.DONE, self.name, ['Already installed'])
  1268. def write(self, action, name, msg):
  1269. self.buf_q.put((action, name, msg))
  1270. class PlugThread(thr.Thread):
  1271. def __init__(self, tname, args):
  1272. super(PlugThread, self).__init__()
  1273. self.tname = tname
  1274. self.args = args
  1275. def run(self):
  1276. thr.current_thread().name = self.tname
  1277. buf_q, work_q, lock = self.args
  1278. try:
  1279. while not G_STOP.is_set():
  1280. name, args = work_q.get_nowait()
  1281. plug = Plugin(name, args, buf_q, lock)
  1282. plug.manage()
  1283. work_q.task_done()
  1284. except queue.Empty:
  1285. pass
  1286. class RefreshThread(thr.Thread):
  1287. def __init__(self, lock):
  1288. super(RefreshThread, self).__init__()
  1289. self.lock = lock
  1290. self.running = True
  1291. def run(self):
  1292. while self.running:
  1293. with self.lock:
  1294. thread_vim_command('noautocmd normal! a')
  1295. time.sleep(0.33)
  1296. def stop(self):
  1297. self.running = False
  1298. if G_NVIM:
  1299. def thread_vim_command(cmd):
  1300. vim.session.threadsafe_call(lambda: vim.command(cmd))
  1301. else:
  1302. def thread_vim_command(cmd):
  1303. vim.command(cmd)
  1304. def esc(name):
  1305. return '"' + name.replace('"', '\"') + '"'
  1306. def nonblock_read(fname):
  1307. """ Read a file with nonblock flag. Return the last line. """
  1308. fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK)
  1309. buf = os.read(fread, 100000).decode('utf-8', 'replace')
  1310. os.close(fread)
  1311. line = buf.rstrip('\r\n')
  1312. left = max(line.rfind('\r'), line.rfind('\n'))
  1313. if left != -1:
  1314. left += 1
  1315. line = line[left:]
  1316. return line
  1317. def main():
  1318. thr.current_thread().name = 'main'
  1319. nthreads = int(vim.eval('s:update.threads'))
  1320. plugs = vim.eval('s:update.todo')
  1321. mac_gui = vim.eval('s:mac_gui') == '1'
  1322. lock = thr.Lock()
  1323. buf = Buffer(lock, len(plugs), G_PULL)
  1324. buf_q, work_q = queue.Queue(), queue.Queue()
  1325. for work in plugs.items():
  1326. work_q.put(work)
  1327. start_cnt = thr.active_count()
  1328. for num in range(nthreads):
  1329. tname = 'PlugT-{0:02}'.format(num)
  1330. thread = PlugThread(tname, (buf_q, work_q, lock))
  1331. thread.start()
  1332. if mac_gui:
  1333. rthread = RefreshThread(lock)
  1334. rthread.start()
  1335. while not buf_q.empty() or thr.active_count() != start_cnt:
  1336. try:
  1337. action, name, msg = buf_q.get(True, 0.25)
  1338. buf.write(action, name, msg)
  1339. buf_q.task_done()
  1340. except queue.Empty:
  1341. pass
  1342. except KeyboardInterrupt:
  1343. G_STOP.set()
  1344. if mac_gui:
  1345. rthread.stop()
  1346. rthread.join()
  1347. main()
  1348. EOF
  1349. endfunction
  1350. function! s:update_ruby()
  1351. ruby << EOF
  1352. module PlugStream
  1353. SEP = ["\r", "\n", nil]
  1354. def get_line
  1355. buffer = ''
  1356. loop do
  1357. char = readchar rescue return
  1358. if SEP.include? char.chr
  1359. buffer << $/
  1360. break
  1361. else
  1362. buffer << char
  1363. end
  1364. end
  1365. buffer
  1366. end
  1367. end unless defined?(PlugStream)
  1368. def esc arg
  1369. %["#{arg.gsub('"', '\"')}"]
  1370. end
  1371. def killall pid
  1372. pids = [pid]
  1373. if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM
  1374. pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil }
  1375. else
  1376. unless `which pgrep 2> /dev/null`.empty?
  1377. children = pids
  1378. until children.empty?
  1379. children = children.map { |pid|
  1380. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  1381. }.flatten
  1382. pids += children
  1383. end
  1384. end
  1385. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  1386. end
  1387. end
  1388. require 'thread'
  1389. require 'fileutils'
  1390. require 'timeout'
  1391. running = true
  1392. iswin = VIM::evaluate('s:is_win').to_i == 1
  1393. pull = VIM::evaluate('s:update.pull').to_i == 1
  1394. base = VIM::evaluate('g:plug_home')
  1395. all = VIM::evaluate('s:update.todo')
  1396. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  1397. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  1398. nthr = VIM::evaluate('s:update.threads').to_i
  1399. maxy = VIM::evaluate('winheight(".")').to_i
  1400. cd = iswin ? 'cd /d' : 'cd'
  1401. tot = VIM::evaluate('len(s:update.todo)') || 0
  1402. bar = ''
  1403. skip = 'Already installed'
  1404. mtx = Mutex.new
  1405. take1 = proc { mtx.synchronize { running && all.shift } }
  1406. logh = proc {
  1407. cnt = bar.length
  1408. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  1409. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  1410. VIM::command('normal! 2G')
  1411. VIM::command('redraw')
  1412. }
  1413. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  1414. log = proc { |name, result, type|
  1415. mtx.synchronize do
  1416. ing = ![true, false].include?(type)
  1417. bar += type ? '=' : 'x' unless ing
  1418. b = case type
  1419. when :install then '+' when :update then '*'
  1420. when true, nil then '-' else
  1421. VIM::command("call add(s:update.errors, '#{name}')")
  1422. 'x'
  1423. end
  1424. result =
  1425. if type || type.nil?
  1426. ["#{b} #{name}: #{result.lines.to_a.last}"]
  1427. elsif result =~ /^Interrupted|^Timeout/
  1428. ["#{b} #{name}: #{result}"]
  1429. else
  1430. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  1431. end
  1432. if lnum = where.call(name)
  1433. $curbuf.delete lnum
  1434. lnum = 4 if ing && lnum > maxy
  1435. end
  1436. result.each_with_index do |line, offset|
  1437. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  1438. end
  1439. logh.call
  1440. end
  1441. }
  1442. bt = proc { |cmd, name, type, cleanup|
  1443. tried = timeout = 0
  1444. begin
  1445. tried += 1
  1446. timeout += limit
  1447. fd = nil
  1448. data = ''
  1449. if iswin
  1450. Timeout::timeout(timeout) do
  1451. tmp = VIM::evaluate('tempname()')
  1452. system("(#{cmd}) > #{tmp}")
  1453. data = File.read(tmp).chomp
  1454. File.unlink tmp rescue nil
  1455. end
  1456. else
  1457. fd = IO.popen(cmd).extend(PlugStream)
  1458. first_line = true
  1459. log_prob = 1.0 / nthr
  1460. while line = Timeout::timeout(timeout) { fd.get_line }
  1461. data << line
  1462. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  1463. first_line = false
  1464. end
  1465. fd.close
  1466. end
  1467. [$? == 0, data.chomp]
  1468. rescue Timeout::Error, Interrupt => e
  1469. if fd && !fd.closed?
  1470. killall fd.pid
  1471. fd.close
  1472. end
  1473. cleanup.call if cleanup
  1474. if e.is_a?(Timeout::Error) && tried < tries
  1475. 3.downto(1) do |countdown|
  1476. s = countdown > 1 ? 's' : ''
  1477. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  1478. sleep 1
  1479. end
  1480. log.call name, 'Retrying ...', type
  1481. retry
  1482. end
  1483. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  1484. end
  1485. }
  1486. main = Thread.current
  1487. threads = []
  1488. watcher = Thread.new {
  1489. while VIM::evaluate('getchar(1)')
  1490. sleep 0.1
  1491. end
  1492. mtx.synchronize do
  1493. running = false
  1494. threads.each { |t| t.raise Interrupt }
  1495. end
  1496. threads.each { |t| t.join rescue nil }
  1497. main.kill
  1498. }
  1499. refresh = Thread.new {
  1500. while true
  1501. mtx.synchronize do
  1502. break unless running
  1503. VIM::command('noautocmd normal! a')
  1504. end
  1505. sleep 0.2
  1506. end
  1507. } if VIM::evaluate('s:mac_gui') == 1
  1508. clone_opt = VIM::evaluate('s:clone_opt')
  1509. progress = VIM::evaluate('s:progress_opt(1)')
  1510. nthr.times do
  1511. mtx.synchronize do
  1512. threads << Thread.new {
  1513. while pair = take1.call
  1514. name = pair.first
  1515. dir, uri, branch, tag = pair.last.values_at *%w[dir uri branch tag]
  1516. checkout = esc(tag ? tag : branch)
  1517. merge = esc(tag ? tag : "origin/#{branch}")
  1518. subm = "git submodule update --init --recursive 2>&1"
  1519. exists = File.directory? dir
  1520. ok, result =
  1521. if exists
  1522. chdir = "#{cd} #{iswin ? dir : esc(dir)}"
  1523. ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil, nil
  1524. current_uri = data.lines.to_a.last
  1525. if !ret
  1526. if data =~ /^Interrupted|^Timeout/
  1527. [false, data]
  1528. else
  1529. [false, [data.chomp, "PlugClean required."].join($/)]
  1530. end
  1531. elsif current_uri.sub(/git::?@/, '') != uri.sub(/git::?@/, '')
  1532. [false, ["Invalid URI: #{current_uri}",
  1533. "Expected: #{uri}",
  1534. "PlugClean required."].join($/)]
  1535. else
  1536. if pull
  1537. log.call name, 'Updating ...', :update
  1538. fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : ''
  1539. 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
  1540. else
  1541. [true, skip]
  1542. end
  1543. end
  1544. else
  1545. d = esc dir.sub(%r{[\\/]+$}, '')
  1546. log.call name, 'Installing ...', :install
  1547. bt.call "git clone #{clone_opt unless tag} #{progress} --recursive #{uri} -b #{checkout} #{d} 2>&1", name, :install, proc {
  1548. FileUtils.rm_rf dir
  1549. }
  1550. end
  1551. mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
  1552. log.call name, result, ok
  1553. end
  1554. } if running
  1555. end
  1556. end
  1557. threads.each { |t| t.join rescue nil }
  1558. logh.call
  1559. refresh.kill if refresh
  1560. watcher.kill
  1561. EOF
  1562. endfunction
  1563. function! s:shellesc(arg)
  1564. return '"'.escape(a:arg, '"').'"'
  1565. endfunction
  1566. function! s:glob_dir(path)
  1567. return map(filter(s:glob(a:path, '**'), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  1568. endfunction
  1569. function! s:progress_bar(line, bar, total)
  1570. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  1571. endfunction
  1572. function! s:compare_git_uri(a, b)
  1573. let a = substitute(a:a, 'git:\{1,2}@', '', '')
  1574. let b = substitute(a:b, 'git:\{1,2}@', '', '')
  1575. return a ==# b
  1576. endfunction
  1577. function! s:format_message(bullet, name, message)
  1578. if a:bullet != 'x'
  1579. return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
  1580. else
  1581. let lines = map(s:lines(a:message), '" ".v:val')
  1582. return extend([printf('x %s:', a:name)], lines)
  1583. endif
  1584. endfunction
  1585. function! s:with_cd(cmd, dir)
  1586. return printf('cd%s %s && %s', s:is_win ? ' /d' : '', s:shellesc(a:dir), a:cmd)
  1587. endfunction
  1588. function! s:system(cmd, ...)
  1589. try
  1590. let [sh, shrd] = [&shell, &shellredir]
  1591. if !s:is_win
  1592. set shell=sh shellredir=>%s\ 2>&1
  1593. endif
  1594. let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
  1595. return system(s:is_win ? '('.cmd.')' : cmd)
  1596. finally
  1597. let [&shell, &shellredir] = [sh, shrd]
  1598. endtry
  1599. endfunction
  1600. function! s:system_chomp(...)
  1601. let ret = call('s:system', a:000)
  1602. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  1603. endfunction
  1604. function! s:git_validate(spec, check_branch)
  1605. let err = ''
  1606. if isdirectory(a:spec.dir)
  1607. let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url', a:spec.dir))
  1608. let remote = result[-1]
  1609. if v:shell_error
  1610. let err = join([remote, 'PlugClean required.'], "\n")
  1611. elseif !s:compare_git_uri(remote, a:spec.uri)
  1612. let err = join(['Invalid URI: '.remote,
  1613. \ 'Expected: '.a:spec.uri,
  1614. \ 'PlugClean required.'], "\n")
  1615. elseif a:check_branch && has_key(a:spec, 'commit')
  1616. let result = s:lines(s:system('git rev-parse HEAD 2>&1', a:spec.dir))
  1617. let sha = result[-1]
  1618. if v:shell_error
  1619. let err = join(add(result, 'PlugClean required.'), "\n")
  1620. elseif !s:hash_match(sha, a:spec.commit)
  1621. let err = join([printf('Invalid HEAD (expected: %s, actual: %s)',
  1622. \ a:spec.commit[:6], sha[:6]),
  1623. \ 'PlugUpdate required.'], "\n")
  1624. endif
  1625. elseif a:check_branch
  1626. let branch = result[0]
  1627. " Check tag
  1628. if has_key(a:spec, 'tag')
  1629. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
  1630. if a:spec.tag !=# tag
  1631. let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.',
  1632. \ (empty(tag) ? 'N/A' : tag), a:spec.tag)
  1633. endif
  1634. " Check branch
  1635. elseif a:spec.branch !=# branch
  1636. let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.',
  1637. \ branch, a:spec.branch)
  1638. endif
  1639. endif
  1640. else
  1641. let err = 'Not found'
  1642. endif
  1643. return err
  1644. endfunction
  1645. function! s:rm_rf(dir)
  1646. if isdirectory(a:dir)
  1647. call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(a:dir))
  1648. endif
  1649. endfunction
  1650. function! s:clean(force)
  1651. call s:prepare()
  1652. call append(0, 'Searching for unused plugins in '.g:plug_home)
  1653. call append(1, '')
  1654. " List of valid directories
  1655. let dirs = []
  1656. let [cnt, total] = [0, len(g:plugs)]
  1657. for [name, spec] in items(g:plugs)
  1658. if !s:is_managed(name) || empty(s:git_validate(spec, 0))
  1659. call add(dirs, spec.dir)
  1660. endif
  1661. let cnt += 1
  1662. call s:progress_bar(2, repeat('=', cnt), total)
  1663. normal! 2G
  1664. redraw
  1665. endfor
  1666. let allowed = {}
  1667. for dir in dirs
  1668. let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
  1669. let allowed[dir] = 1
  1670. for child in s:glob_dir(dir)
  1671. let allowed[child] = 1
  1672. endfor
  1673. endfor
  1674. let todo = []
  1675. let found = sort(s:glob_dir(g:plug_home))
  1676. while !empty(found)
  1677. let f = remove(found, 0)
  1678. if !has_key(allowed, f) && isdirectory(f)
  1679. call add(todo, f)
  1680. call append(line('$'), '- ' . f)
  1681. let found = filter(found, 'stridx(v:val, f) != 0')
  1682. end
  1683. endwhile
  1684. normal! G
  1685. redraw
  1686. if empty(todo)
  1687. call append(line('$'), 'Already clean.')
  1688. else
  1689. if a:force || s:ask('Proceed?')
  1690. for dir in todo
  1691. call s:rm_rf(dir)
  1692. endfor
  1693. call append(line('$'), 'Removed.')
  1694. else
  1695. call append(line('$'), 'Cancelled.')
  1696. endif
  1697. endif
  1698. normal! G
  1699. endfunction
  1700. function! s:upgrade()
  1701. echo 'Downloading the latest version of vim-plug'
  1702. redraw
  1703. let tmp = tempname()
  1704. let new = tmp . '/plug.vim'
  1705. try
  1706. let out = s:system(printf('git clone --depth 1 %s %s', s:plug_src, tmp))
  1707. if v:shell_error
  1708. return s:err('Error upgrading vim-plug: '. out)
  1709. endif
  1710. if readfile(s:me) ==# readfile(new)
  1711. echo 'vim-plug is already up-to-date'
  1712. return 0
  1713. else
  1714. call rename(s:me, s:me . '.old')
  1715. call rename(new, s:me)
  1716. unlet g:loaded_plug
  1717. echo 'vim-plug has been upgraded'
  1718. return 1
  1719. endif
  1720. finally
  1721. silent! call s:rm_rf(tmp)
  1722. endtry
  1723. endfunction
  1724. function! s:upgrade_specs()
  1725. for spec in values(g:plugs)
  1726. let spec.frozen = get(spec, 'frozen', 0)
  1727. endfor
  1728. endfunction
  1729. function! s:status()
  1730. call s:prepare()
  1731. call append(0, 'Checking plugins')
  1732. call append(1, '')
  1733. let ecnt = 0
  1734. let unloaded = 0
  1735. let [cnt, total] = [0, len(g:plugs)]
  1736. for [name, spec] in items(g:plugs)
  1737. if has_key(spec, 'uri')
  1738. if isdirectory(spec.dir)
  1739. let err = s:git_validate(spec, 1)
  1740. let [valid, msg] = [empty(err), empty(err) ? 'OK' : err]
  1741. else
  1742. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  1743. endif
  1744. else
  1745. if isdirectory(spec.dir)
  1746. let [valid, msg] = [1, 'OK']
  1747. else
  1748. let [valid, msg] = [0, 'Not found.']
  1749. endif
  1750. endif
  1751. let cnt += 1
  1752. let ecnt += !valid
  1753. " `s:loaded` entry can be missing if PlugUpgraded
  1754. if valid && get(s:loaded, name, -1) == 0
  1755. let unloaded = 1
  1756. let msg .= ' (not loaded)'
  1757. endif
  1758. call s:progress_bar(2, repeat('=', cnt), total)
  1759. call append(3, s:format_message(valid ? '-' : 'x', name, msg))
  1760. normal! 2G
  1761. redraw
  1762. endfor
  1763. call setline(1, 'Finished. '.ecnt.' error(s).')
  1764. normal! gg
  1765. setlocal nomodifiable
  1766. if unloaded
  1767. echo "Press 'L' on each line to load plugin, or 'U' to update"
  1768. nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1769. xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1770. end
  1771. endfunction
  1772. function! s:extract_name(str, prefix, suffix)
  1773. return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
  1774. endfunction
  1775. function! s:status_load(lnum)
  1776. let line = getline(a:lnum)
  1777. let name = s:extract_name(line, '-', '(not loaded)')
  1778. if !empty(name)
  1779. call plug#load(name)
  1780. setlocal modifiable
  1781. call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
  1782. setlocal nomodifiable
  1783. endif
  1784. endfunction
  1785. function! s:status_update() range
  1786. let lines = getline(a:firstline, a:lastline)
  1787. let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
  1788. if !empty(names)
  1789. echo
  1790. execute 'PlugUpdate' join(names)
  1791. endif
  1792. endfunction
  1793. function! s:is_preview_window_open()
  1794. silent! wincmd P
  1795. if &previewwindow
  1796. wincmd p
  1797. return 1
  1798. endif
  1799. return 0
  1800. endfunction
  1801. function! s:find_name(lnum)
  1802. for lnum in reverse(range(1, a:lnum))
  1803. let line = getline(lnum)
  1804. if empty(line)
  1805. return ''
  1806. endif
  1807. let name = s:extract_name(line, '-', '')
  1808. if !empty(name)
  1809. return name
  1810. endif
  1811. endfor
  1812. return ''
  1813. endfunction
  1814. function! s:preview_commit()
  1815. if b:plug_preview < 0
  1816. let b:plug_preview = !s:is_preview_window_open()
  1817. endif
  1818. let sha = matchstr(getline('.'), '^ \X*\zs[0-9a-z]\{7}')
  1819. if empty(sha)
  1820. return
  1821. endif
  1822. let name = s:find_name(line('.'))
  1823. if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
  1824. return
  1825. endif
  1826. execute 'pedit' sha
  1827. wincmd P
  1828. setlocal filetype=git buftype=nofile nobuflisted modifiable
  1829. execute 'silent read !cd' s:shellesc(g:plugs[name].dir) '&& git show --pretty=medium' sha
  1830. normal! gg"_dd
  1831. setlocal nomodifiable
  1832. nnoremap <silent> <buffer> q :q<cr>
  1833. wincmd p
  1834. endfunction
  1835. function! s:section(flags)
  1836. call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
  1837. endfunction
  1838. function! s:format_git_log(line)
  1839. let indent = ' '
  1840. let tokens = split(a:line, nr2char(1))
  1841. if len(tokens) != 5
  1842. return indent.substitute(a:line, '\s*$', '', '')
  1843. endif
  1844. let [graph, sha, refs, subject, date] = tokens
  1845. let tag = matchstr(refs, 'tag: [^,)]\+')
  1846. let tag = empty(tag) ? ' ' : ' ('.tag.') '
  1847. return printf('%s%s%s%s%s (%s)', indent, graph, sha, tag, subject, date)
  1848. endfunction
  1849. function! s:append_ul(lnum, text)
  1850. call append(a:lnum, ['', a:text, repeat('-', len(a:text))])
  1851. endfunction
  1852. function! s:diff()
  1853. call s:prepare()
  1854. call append(0, ['Collecting changes ...', ''])
  1855. let cnts = [0, 0]
  1856. let bar = ''
  1857. let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)')
  1858. call s:progress_bar(2, bar, len(total))
  1859. for origin in [1, 0]
  1860. let plugs = reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))'))))
  1861. if empty(plugs)
  1862. continue
  1863. endif
  1864. call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:')
  1865. for [k, v] in plugs
  1866. let range = origin ? '..origin/'.v.branch : 'HEAD@{1}..'
  1867. 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)
  1868. if !empty(diff)
  1869. let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : ''
  1870. call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)')))
  1871. let cnts[origin] += 1
  1872. endif
  1873. let bar .= '='
  1874. call s:progress_bar(2, bar, len(total))
  1875. normal! 2G
  1876. redraw
  1877. endfor
  1878. if !cnts[origin]
  1879. call append(5, ['', 'N/A'])
  1880. endif
  1881. endfor
  1882. call setline(1, printf('%d plugin(s) updated.', cnts[0])
  1883. \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : ''))
  1884. if cnts[0] || cnts[1]
  1885. nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
  1886. nnoremap <silent> <buffer> o :silent! call <SID>preview_commit()<cr>
  1887. endif
  1888. if cnts[0]
  1889. nnoremap <silent> <buffer> X :call <SID>revert()<cr>
  1890. echo "Press 'X' on each block to revert the update"
  1891. endif
  1892. normal! gg
  1893. setlocal nomodifiable
  1894. endfunction
  1895. function! s:revert()
  1896. if search('^Pending updates', 'bnW')
  1897. return
  1898. endif
  1899. let name = s:find_name(line('.'))
  1900. if empty(name) || !has_key(g:plugs, name) ||
  1901. \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
  1902. return
  1903. endif
  1904. call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir)
  1905. setlocal modifiable
  1906. normal! "_dap
  1907. setlocal nomodifiable
  1908. echo 'Reverted.'
  1909. endfunction
  1910. function! s:snapshot(force, ...) abort
  1911. call s:prepare()
  1912. setf vim
  1913. call append(0, ['" Generated by vim-plug',
  1914. \ '" '.strftime("%c"),
  1915. \ '" :source this file in vim to restore the snapshot',
  1916. \ '" or execute: vim -S snapshot.vim',
  1917. \ '', '', 'PlugUpdate!'])
  1918. 1
  1919. let anchor = line('$') - 3
  1920. let names = sort(keys(filter(copy(g:plugs),
  1921. \'has_key(v:val, "uri") && !has_key(v:val, "commit") && isdirectory(v:val.dir)')))
  1922. for name in reverse(names)
  1923. let sha = s:system_chomp('git rev-parse --short HEAD', g:plugs[name].dir)
  1924. if !empty(sha)
  1925. call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha))
  1926. redraw
  1927. endif
  1928. endfor
  1929. if a:0 > 0
  1930. let fn = expand(a:1)
  1931. if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?'))
  1932. return
  1933. endif
  1934. call writefile(getline(1, '$'), fn)
  1935. echo 'Saved as '.a:1
  1936. silent execute 'e' s:esc(fn)
  1937. setf vim
  1938. endif
  1939. endfunction
  1940. function! s:split_rtp()
  1941. return split(&rtp, '\\\@<!,')
  1942. endfunction
  1943. let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
  1944. let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
  1945. if exists('g:plugs')
  1946. let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
  1947. call s:upgrade_specs()
  1948. call s:define_commands()
  1949. endif
  1950. let &cpo = s:cpo_save
  1951. unlet s:cpo_save