plug.vim 70 KB

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