plug.vim 73 KB

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