plug.vim 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523
  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. setf vim-plug
  690. if exists('g:syntax_on')
  691. call s:syntax()
  692. endif
  693. endfunction
  694. function! s:assign_name()
  695. " Assign buffer name
  696. let prefix = '[Plugins]'
  697. let name = prefix
  698. let idx = 2
  699. while bufexists(name)
  700. let name = printf('%s (%s)', prefix, idx)
  701. let idx = idx + 1
  702. endwhile
  703. silent! execute 'f' fnameescape(name)
  704. endfunction
  705. function! s:chsh(swap)
  706. let prev = [&shell, &shellcmdflag, &shellredir]
  707. if s:is_win
  708. set shell=cmd.exe shellcmdflag=/c shellredir=>%s\ 2>&1
  709. elseif a:swap
  710. set shell=sh shellredir=>%s\ 2>&1
  711. endif
  712. return prev
  713. endfunction
  714. function! s:bang(cmd, ...)
  715. try
  716. let [sh, shellcmdflag, shrd] = s:chsh(a:0)
  717. " FIXME: Escaping is incomplete. We could use shellescape with eval,
  718. " but it won't work on Windows.
  719. let cmd = a:0 ? s:with_cd(a:cmd, a:1) : a:cmd
  720. if s:is_win
  721. let batchfile = tempname().'.bat'
  722. call writefile(["@echo off\r", cmd . "\r"], batchfile)
  723. let cmd = batchfile
  724. endif
  725. let g:_plug_bang = (s:is_win && has('gui_running') ? 'silent ' : '').'!'.escape(cmd, '#!%')
  726. execute "normal! :execute g:_plug_bang\<cr>\<cr>"
  727. finally
  728. unlet g:_plug_bang
  729. let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd]
  730. if s:is_win
  731. call delete(batchfile)
  732. endif
  733. endtry
  734. return v:shell_error ? 'Exit status: ' . v:shell_error : ''
  735. endfunction
  736. function! s:regress_bar()
  737. let bar = substitute(getline(2)[1:-2], '.*\zs=', 'x', '')
  738. call s:progress_bar(2, bar, len(bar))
  739. endfunction
  740. function! s:is_updated(dir)
  741. return !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', a:dir))
  742. endfunction
  743. function! s:do(pull, force, todo)
  744. for [name, spec] in items(a:todo)
  745. if !isdirectory(spec.dir)
  746. continue
  747. endif
  748. let installed = has_key(s:update.new, name)
  749. let updated = installed ? 0 :
  750. \ (a:pull && index(s:update.errors, name) < 0 && s:is_updated(spec.dir))
  751. if a:force || installed || updated
  752. execute 'cd' s:esc(spec.dir)
  753. call append(3, '- Post-update hook for '. name .' ... ')
  754. let error = ''
  755. let type = type(spec.do)
  756. if type == s:TYPE.string
  757. if spec.do[0] == ':'
  758. if !get(s:loaded, name, 0)
  759. let s:loaded[name] = 1
  760. call s:reorg_rtp()
  761. endif
  762. call s:load_plugin(spec)
  763. try
  764. execute spec.do[1:]
  765. catch
  766. let error = v:exception
  767. endtry
  768. if !s:plug_window_exists()
  769. cd -
  770. throw 'Warning: vim-plug was terminated by the post-update hook of '.name
  771. endif
  772. else
  773. let error = s:bang(spec.do)
  774. endif
  775. elseif type == s:TYPE.funcref
  776. try
  777. let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
  778. call spec.do({ 'name': name, 'status': status, 'force': a:force })
  779. catch
  780. let error = v:exception
  781. endtry
  782. else
  783. let error = 'Invalid hook type'
  784. endif
  785. call s:switch_in()
  786. call setline(4, empty(error) ? (getline(4) . 'OK')
  787. \ : ('x' . getline(4)[1:] . error))
  788. if !empty(error)
  789. call add(s:update.errors, name)
  790. call s:regress_bar()
  791. endif
  792. cd -
  793. endif
  794. endfor
  795. endfunction
  796. function! s:hash_match(a, b)
  797. return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0
  798. endfunction
  799. function! s:checkout(spec)
  800. let sha = a:spec.commit
  801. let output = s:system('git rev-parse HEAD', a:spec.dir)
  802. if !v:shell_error && !s:hash_match(sha, s:lines(output)[0])
  803. let output = s:system(
  804. \ 'git fetch --depth 999999 && git checkout '.s:esc(sha).' --', a:spec.dir)
  805. endif
  806. return output
  807. endfunction
  808. function! s:finish(pull)
  809. let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
  810. if new_frozen
  811. let s = new_frozen > 1 ? 's' : ''
  812. call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
  813. endif
  814. call append(3, '- Finishing ... ') | 4
  815. redraw
  816. call plug#helptags()
  817. call plug#end()
  818. call setline(4, getline(4) . 'Done!')
  819. redraw
  820. let msgs = []
  821. if !empty(s:update.errors)
  822. call add(msgs, "Press 'R' to retry.")
  823. endif
  824. if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
  825. \ "v:val =~ '^- ' && v:val !~# 'Already up.to.date'"))
  826. call add(msgs, "Press 'D' to see the updated changes.")
  827. endif
  828. echo join(msgs, ' ')
  829. call s:finish_bindings()
  830. endfunction
  831. function! s:retry()
  832. if empty(s:update.errors)
  833. return
  834. endif
  835. echo
  836. call s:update_impl(s:update.pull, s:update.force,
  837. \ extend(copy(s:update.errors), [s:update.threads]))
  838. endfunction
  839. function! s:is_managed(name)
  840. return has_key(g:plugs[a:name], 'uri')
  841. endfunction
  842. function! s:names(...)
  843. return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
  844. endfunction
  845. function! s:check_ruby()
  846. silent! ruby require 'thread'; VIM::command("let g:plug_ruby = '#{RUBY_VERSION}'")
  847. if !exists('g:plug_ruby')
  848. redraw!
  849. return s:warn('echom', 'Warning: Ruby interface is broken')
  850. endif
  851. let ruby_version = split(g:plug_ruby, '\.')
  852. unlet g:plug_ruby
  853. return s:version_requirement(ruby_version, [1, 8, 7])
  854. endfunction
  855. function! s:update_impl(pull, force, args) abort
  856. let sync = index(a:args, '--sync') >= 0 || has('vim_starting')
  857. let args = filter(copy(a:args), 'v:val != "--sync"')
  858. let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
  859. \ remove(args, -1) : get(g:, 'plug_threads', 16)
  860. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  861. let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
  862. \ filter(managed, 'index(args, v:key) >= 0')
  863. if empty(todo)
  864. return s:warn('echo', 'No plugin to '. (a:pull ? 'update' : 'install'))
  865. endif
  866. if !s:is_win && s:git_version_requirement(2, 3)
  867. let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : ''
  868. let $GIT_TERMINAL_PROMPT = 0
  869. for plug in values(todo)
  870. let plug.uri = substitute(plug.uri,
  871. \ '^https://git::@github\.com', 'https://github.com', '')
  872. endfor
  873. endif
  874. if !isdirectory(g:plug_home)
  875. try
  876. call mkdir(g:plug_home, 'p')
  877. catch
  878. return s:err(printf('Invalid plug directory: %s. '.
  879. \ 'Try to call plug#begin with a valid directory', g:plug_home))
  880. endtry
  881. endif
  882. if has('nvim') && !exists('*jobwait') && threads > 1
  883. call s:warn('echom', '[vim-plug] Update Neovim for parallel installer')
  884. endif
  885. let use_job = s:nvim || s:vim8
  886. let python = (has('python') || has('python3')) && !use_job
  887. 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()
  888. let s:update = {
  889. \ 'start': reltime(),
  890. \ 'all': todo,
  891. \ 'todo': copy(todo),
  892. \ 'errors': [],
  893. \ 'pull': a:pull,
  894. \ 'force': a:force,
  895. \ 'new': {},
  896. \ 'threads': (python || ruby || use_job) ? min([len(todo), threads]) : 1,
  897. \ 'bar': '',
  898. \ 'fin': 0
  899. \ }
  900. call s:prepare(1)
  901. call append(0, ['', ''])
  902. normal! 2G
  903. silent! redraw
  904. let s:clone_opt = get(g:, 'plug_shallow', 1) ?
  905. \ '--depth 1' . (s:git_version_requirement(1, 7, 10) ? ' --no-single-branch' : '') : ''
  906. if has('win32unix')
  907. let s:clone_opt .= ' -c core.eol=lf -c core.autocrlf=input'
  908. endif
  909. let s:submodule_opt = s:git_version_requirement(2, 8) ? ' --jobs='.threads : ''
  910. " Python version requirement (>= 2.7)
  911. if python && !has('python3') && !ruby && !use_job && s:update.threads > 1
  912. redir => pyv
  913. silent python import platform; print platform.python_version()
  914. redir END
  915. let python = s:version_requirement(
  916. \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6])
  917. endif
  918. if (python || ruby) && s:update.threads > 1
  919. try
  920. let imd = &imd
  921. if s:mac_gui
  922. set noimd
  923. endif
  924. if ruby
  925. call s:update_ruby()
  926. else
  927. call s:update_python()
  928. endif
  929. catch
  930. let lines = getline(4, '$')
  931. let printed = {}
  932. silent! 4,$d _
  933. for line in lines
  934. let name = s:extract_name(line, '.', '')
  935. if empty(name) || !has_key(printed, name)
  936. call append('$', line)
  937. if !empty(name)
  938. let printed[name] = 1
  939. if line[0] == 'x' && index(s:update.errors, name) < 0
  940. call add(s:update.errors, name)
  941. end
  942. endif
  943. endif
  944. endfor
  945. finally
  946. let &imd = imd
  947. call s:update_finish()
  948. endtry
  949. else
  950. call s:update_vim()
  951. while use_job && sync
  952. sleep 100m
  953. if s:update.fin
  954. break
  955. endif
  956. endwhile
  957. endif
  958. endfunction
  959. function! s:log4(name, msg)
  960. call setline(4, printf('- %s (%s)', a:msg, a:name))
  961. redraw
  962. endfunction
  963. function! s:update_finish()
  964. if exists('s:git_terminal_prompt')
  965. let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt
  966. endif
  967. if s:switch_in()
  968. call append(3, '- Updating ...') | 4
  969. 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))'))
  970. let [pos, _] = s:logpos(name)
  971. if !pos
  972. continue
  973. endif
  974. if has_key(spec, 'commit')
  975. call s:log4(name, 'Checking out '.spec.commit)
  976. let out = s:checkout(spec)
  977. elseif has_key(spec, 'tag')
  978. let tag = spec.tag
  979. if tag =~ '\*'
  980. let tags = s:lines(s:system('git tag --list '.s:shellesc(tag).' --sort -version:refname 2>&1', spec.dir))
  981. if !v:shell_error && !empty(tags)
  982. let tag = tags[0]
  983. call s:log4(name, printf('Latest tag for %s -> %s', spec.tag, tag))
  984. call append(3, '')
  985. endif
  986. endif
  987. call s:log4(name, 'Checking out '.tag)
  988. let out = s:system('git checkout -q '.s:esc(tag).' -- 2>&1', spec.dir)
  989. else
  990. let branch = s:esc(get(spec, 'branch', 'master'))
  991. call s:log4(name, 'Merging origin/'.branch)
  992. let out = s:system('git checkout -q '.branch.' -- 2>&1'
  993. \. (has_key(s:update.new, name) ? '' : ('&& git merge --ff-only origin/'.branch.' 2>&1')), spec.dir)
  994. endif
  995. if !v:shell_error && filereadable(spec.dir.'/.gitmodules') &&
  996. \ (s:update.force || has_key(s:update.new, name) || s:is_updated(spec.dir))
  997. call s:log4(name, 'Updating submodules. This may take a while.')
  998. let out .= s:bang('git submodule update --init --recursive'.s:submodule_opt.' 2>&1', spec.dir)
  999. endif
  1000. let msg = s:format_message(v:shell_error ? 'x': '-', name, out)
  1001. if v:shell_error
  1002. call add(s:update.errors, name)
  1003. call s:regress_bar()
  1004. silent execute pos 'd _'
  1005. call append(4, msg) | 4
  1006. elseif !empty(out)
  1007. call setline(pos, msg[0])
  1008. endif
  1009. redraw
  1010. endfor
  1011. silent 4 d _
  1012. try
  1013. 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")'))
  1014. catch
  1015. call s:warn('echom', v:exception)
  1016. call s:warn('echo', '')
  1017. return
  1018. endtry
  1019. call s:finish(s:update.pull)
  1020. call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
  1021. call s:switch_out('normal! gg')
  1022. endif
  1023. endfunction
  1024. function! s:job_abort()
  1025. if (!s:nvim && !s:vim8) || !exists('s:jobs')
  1026. return
  1027. endif
  1028. for [name, j] in items(s:jobs)
  1029. if s:nvim
  1030. silent! call jobstop(j.jobid)
  1031. elseif s:vim8
  1032. silent! call job_stop(j.jobid)
  1033. endif
  1034. if j.new
  1035. call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir))
  1036. endif
  1037. endfor
  1038. let s:jobs = {}
  1039. endfunction
  1040. function! s:last_non_empty_line(lines)
  1041. let len = len(a:lines)
  1042. for idx in range(len)
  1043. let line = a:lines[len-idx-1]
  1044. if !empty(line)
  1045. return line
  1046. endif
  1047. endfor
  1048. return ''
  1049. endfunction
  1050. function! s:job_out_cb(self, data) abort
  1051. let self = a:self
  1052. let data = remove(self.lines, -1) . a:data
  1053. let lines = map(split(data, "\n", 1), 'split(v:val, "\r", 1)[-1]')
  1054. call extend(self.lines, lines)
  1055. " To reduce the number of buffer updates
  1056. let self.tick = get(self, 'tick', -1) + 1
  1057. if !self.running || self.tick % len(s:jobs) == 0
  1058. let bullet = self.running ? (self.new ? '+' : '*') : (self.error ? 'x' : '-')
  1059. let result = self.error ? join(self.lines, "\n") : s:last_non_empty_line(self.lines)
  1060. call s:log(bullet, self.name, result)
  1061. endif
  1062. endfunction
  1063. function! s:job_exit_cb(self, data) abort
  1064. let a:self.running = 0
  1065. let a:self.error = a:data != 0
  1066. call s:reap(a:self.name)
  1067. call s:tick()
  1068. endfunction
  1069. function! s:job_cb(fn, job, ch, data)
  1070. if !s:plug_window_exists() " plug window closed
  1071. return s:job_abort()
  1072. endif
  1073. call call(a:fn, [a:job, a:data])
  1074. endfunction
  1075. function! s:nvim_cb(job_id, data, event) dict abort
  1076. return a:event == 'stdout' ?
  1077. \ s:job_cb('s:job_out_cb', self, 0, join(a:data, "\n")) :
  1078. \ s:job_cb('s:job_exit_cb', self, 0, a:data)
  1079. endfunction
  1080. function! s:spawn(name, cmd, opts)
  1081. let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [''],
  1082. \ 'batchfile': (s:is_win && (s:nvim || s:vim8)) ? tempname().'.bat' : '',
  1083. \ 'new': get(a:opts, 'new', 0) }
  1084. let s:jobs[a:name] = job
  1085. let cmd = has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd
  1086. if !empty(job.batchfile)
  1087. call writefile(["@echo off\r", cmd . "\r"], job.batchfile)
  1088. let cmd = job.batchfile
  1089. endif
  1090. let argv = add(s:is_win ? ['cmd', '/c'] : ['sh', '-c'], cmd)
  1091. if s:nvim
  1092. call extend(job, {
  1093. \ 'on_stdout': function('s:nvim_cb'),
  1094. \ 'on_exit': function('s:nvim_cb'),
  1095. \ })
  1096. let jid = jobstart(argv, job)
  1097. if jid > 0
  1098. let job.jobid = jid
  1099. else
  1100. let job.running = 0
  1101. let job.error = 1
  1102. let job.lines = [jid < 0 ? argv[0].' is not executable' :
  1103. \ 'Invalid arguments (or job table is full)']
  1104. endif
  1105. elseif s:vim8
  1106. let jid = job_start(s:is_win ? join(argv, ' ') : argv, {
  1107. \ 'out_cb': function('s:job_cb', ['s:job_out_cb', job]),
  1108. \ 'exit_cb': function('s:job_cb', ['s:job_exit_cb', job]),
  1109. \ 'out_mode': 'raw'
  1110. \})
  1111. if job_status(jid) == 'run'
  1112. let job.jobid = jid
  1113. else
  1114. let job.running = 0
  1115. let job.error = 1
  1116. let job.lines = ['Failed to start job']
  1117. endif
  1118. else
  1119. let job.lines = s:lines(call('s:system', [cmd]))
  1120. let job.error = v:shell_error != 0
  1121. let job.running = 0
  1122. endif
  1123. endfunction
  1124. function! s:reap(name)
  1125. let job = s:jobs[a:name]
  1126. if job.error
  1127. call add(s:update.errors, a:name)
  1128. elseif get(job, 'new', 0)
  1129. let s:update.new[a:name] = 1
  1130. endif
  1131. let s:update.bar .= job.error ? 'x' : '='
  1132. let bullet = job.error ? 'x' : '-'
  1133. let result = job.error ? join(job.lines, "\n") : s:last_non_empty_line(job.lines)
  1134. call s:log(bullet, a:name, empty(result) ? 'OK' : result)
  1135. call s:bar()
  1136. if has_key(job, 'batchfile') && !empty(job.batchfile)
  1137. call delete(job.batchfile)
  1138. endif
  1139. call remove(s:jobs, a:name)
  1140. endfunction
  1141. function! s:bar()
  1142. if s:switch_in()
  1143. let total = len(s:update.all)
  1144. call setline(1, (s:update.pull ? 'Updating' : 'Installing').
  1145. \ ' plugins ('.len(s:update.bar).'/'.total.')')
  1146. call s:progress_bar(2, s:update.bar, total)
  1147. call s:switch_out()
  1148. endif
  1149. endfunction
  1150. function! s:logpos(name)
  1151. for i in range(4, line('$'))
  1152. if getline(i) =~# '^[-+x*] '.a:name.':'
  1153. for j in range(i + 1, line('$'))
  1154. if getline(j) !~ '^ '
  1155. return [i, j - 1]
  1156. endif
  1157. endfor
  1158. return [i, i]
  1159. endif
  1160. endfor
  1161. return [0, 0]
  1162. endfunction
  1163. function! s:log(bullet, name, lines)
  1164. if s:switch_in()
  1165. let [b, e] = s:logpos(a:name)
  1166. if b > 0
  1167. silent execute printf('%d,%d d _', b, e)
  1168. if b > winheight('.')
  1169. let b = 4
  1170. endif
  1171. else
  1172. let b = 4
  1173. endif
  1174. " FIXME For some reason, nomodifiable is set after :d in vim8
  1175. setlocal modifiable
  1176. call append(b - 1, s:format_message(a:bullet, a:name, a:lines))
  1177. call s:switch_out()
  1178. endif
  1179. endfunction
  1180. function! s:update_vim()
  1181. let s:jobs = {}
  1182. call s:bar()
  1183. call s:tick()
  1184. endfunction
  1185. function! s:tick()
  1186. let pull = s:update.pull
  1187. let prog = s:progress_opt(s:nvim || s:vim8)
  1188. while 1 " Without TCO, Vim stack is bound to explode
  1189. if empty(s:update.todo)
  1190. if empty(s:jobs) && !s:update.fin
  1191. call s:update_finish()
  1192. let s:update.fin = 1
  1193. endif
  1194. return
  1195. endif
  1196. let name = keys(s:update.todo)[0]
  1197. let spec = remove(s:update.todo, name)
  1198. let new = empty(globpath(spec.dir, '.git', 1))
  1199. call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
  1200. redraw
  1201. let has_tag = has_key(spec, 'tag')
  1202. if !new
  1203. let [error, _] = s:git_validate(spec, 0)
  1204. if empty(error)
  1205. if pull
  1206. let fetch_opt = (has_tag && !empty(globpath(spec.dir, '.git/shallow'))) ? '--depth 99999999' : ''
  1207. call s:spawn(name, printf('git fetch %s %s 2>&1', fetch_opt, prog), { 'dir': spec.dir })
  1208. else
  1209. let s:jobs[name] = { 'running': 0, 'lines': ['Already installed'], 'error': 0 }
  1210. endif
  1211. else
  1212. let s:jobs[name] = { 'running': 0, 'lines': s:lines(error), 'error': 1 }
  1213. endif
  1214. else
  1215. call s:spawn(name,
  1216. \ printf('git clone %s %s %s %s 2>&1',
  1217. \ has_tag ? '' : s:clone_opt,
  1218. \ prog,
  1219. \ s:shellesc(spec.uri),
  1220. \ s:shellesc(s:trim(spec.dir))), { 'new': 1 })
  1221. endif
  1222. if !s:jobs[name].running
  1223. call s:reap(name)
  1224. endif
  1225. if len(s:jobs) >= s:update.threads
  1226. break
  1227. endif
  1228. endwhile
  1229. endfunction
  1230. function! s:update_python()
  1231. let py_exe = has('python') ? 'python' : 'python3'
  1232. execute py_exe "<< EOF"
  1233. import datetime
  1234. import functools
  1235. import os
  1236. try:
  1237. import queue
  1238. except ImportError:
  1239. import Queue as queue
  1240. import random
  1241. import re
  1242. import shutil
  1243. import signal
  1244. import subprocess
  1245. import tempfile
  1246. import threading as thr
  1247. import time
  1248. import traceback
  1249. import vim
  1250. G_NVIM = vim.eval("has('nvim')") == '1'
  1251. G_PULL = vim.eval('s:update.pull') == '1'
  1252. G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1
  1253. G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)'))
  1254. G_CLONE_OPT = vim.eval('s:clone_opt')
  1255. G_PROGRESS = vim.eval('s:progress_opt(1)')
  1256. G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads'))
  1257. G_STOP = thr.Event()
  1258. G_IS_WIN = vim.eval('s:is_win') == '1'
  1259. class PlugError(Exception):
  1260. def __init__(self, msg):
  1261. self.msg = msg
  1262. class CmdTimedOut(PlugError):
  1263. pass
  1264. class CmdFailed(PlugError):
  1265. pass
  1266. class InvalidURI(PlugError):
  1267. pass
  1268. class Action(object):
  1269. INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-']
  1270. class Buffer(object):
  1271. def __init__(self, lock, num_plugs, is_pull):
  1272. self.bar = ''
  1273. self.event = 'Updating' if is_pull else 'Installing'
  1274. self.lock = lock
  1275. self.maxy = int(vim.eval('winheight(".")'))
  1276. self.num_plugs = num_plugs
  1277. def __where(self, name):
  1278. """ Find first line with name in current buffer. Return line num. """
  1279. found, lnum = False, 0
  1280. matcher = re.compile('^[-+x*] {0}:'.format(name))
  1281. for line in vim.current.buffer:
  1282. if matcher.search(line) is not None:
  1283. found = True
  1284. break
  1285. lnum += 1
  1286. if not found:
  1287. lnum = -1
  1288. return lnum
  1289. def header(self):
  1290. curbuf = vim.current.buffer
  1291. curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs)
  1292. num_spaces = self.num_plugs - len(self.bar)
  1293. curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ')
  1294. with self.lock:
  1295. vim.command('normal! 2G')
  1296. vim.command('redraw')
  1297. def write(self, action, name, lines):
  1298. first, rest = lines[0], lines[1:]
  1299. msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)]
  1300. msg.extend([' ' + line for line in rest])
  1301. try:
  1302. if action == Action.ERROR:
  1303. self.bar += 'x'
  1304. vim.command("call add(s:update.errors, '{0}')".format(name))
  1305. elif action == Action.DONE:
  1306. self.bar += '='
  1307. curbuf = vim.current.buffer
  1308. lnum = self.__where(name)
  1309. if lnum != -1: # Found matching line num
  1310. del curbuf[lnum]
  1311. if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]):
  1312. lnum = 3
  1313. else:
  1314. lnum = 3
  1315. curbuf.append(msg, lnum)
  1316. self.header()
  1317. except vim.error:
  1318. pass
  1319. class Command(object):
  1320. CD = 'cd /d' if G_IS_WIN else 'cd'
  1321. def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None):
  1322. self.cmd = cmd
  1323. if cmd_dir:
  1324. self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd)
  1325. self.timeout = timeout
  1326. self.callback = cb if cb else (lambda msg: None)
  1327. self.clean = clean if clean else (lambda: None)
  1328. self.proc = None
  1329. @property
  1330. def alive(self):
  1331. """ Returns true only if command still running. """
  1332. return self.proc and self.proc.poll() is None
  1333. def execute(self, ntries=3):
  1334. """ Execute the command with ntries if CmdTimedOut.
  1335. Returns the output of the command if no Exception.
  1336. """
  1337. attempt, finished, limit = 0, False, self.timeout
  1338. while not finished:
  1339. try:
  1340. attempt += 1
  1341. result = self.try_command()
  1342. finished = True
  1343. return result
  1344. except CmdTimedOut:
  1345. if attempt != ntries:
  1346. self.notify_retry()
  1347. self.timeout += limit
  1348. else:
  1349. raise
  1350. def notify_retry(self):
  1351. """ Retry required for command, notify user. """
  1352. for count in range(3, 0, -1):
  1353. if G_STOP.is_set():
  1354. raise KeyboardInterrupt
  1355. msg = 'Timeout. Will retry in {0} second{1} ...'.format(
  1356. count, 's' if count != 1 else '')
  1357. self.callback([msg])
  1358. time.sleep(1)
  1359. self.callback(['Retrying ...'])
  1360. def try_command(self):
  1361. """ Execute a cmd & poll for callback. Returns list of output.
  1362. Raises CmdFailed -> return code for Popen isn't 0
  1363. Raises CmdTimedOut -> command exceeded timeout without new output
  1364. """
  1365. first_line = True
  1366. try:
  1367. tfile = tempfile.NamedTemporaryFile(mode='w+b')
  1368. preexec_fn = not G_IS_WIN and os.setsid or None
  1369. self.proc = subprocess.Popen(self.cmd, stdout=tfile,
  1370. stderr=subprocess.STDOUT,
  1371. stdin=subprocess.PIPE, shell=True,
  1372. preexec_fn=preexec_fn)
  1373. thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,))
  1374. thrd.start()
  1375. thread_not_started = True
  1376. while thread_not_started:
  1377. try:
  1378. thrd.join(0.1)
  1379. thread_not_started = False
  1380. except RuntimeError:
  1381. pass
  1382. while self.alive:
  1383. if G_STOP.is_set():
  1384. raise KeyboardInterrupt
  1385. if first_line or random.random() < G_LOG_PROB:
  1386. first_line = False
  1387. line = '' if G_IS_WIN else nonblock_read(tfile.name)
  1388. if line:
  1389. self.callback([line])
  1390. time_diff = time.time() - os.path.getmtime(tfile.name)
  1391. if time_diff > self.timeout:
  1392. raise CmdTimedOut(['Timeout!'])
  1393. thrd.join(0.5)
  1394. tfile.seek(0)
  1395. result = [line.decode('utf-8', 'replace').rstrip() for line in tfile]
  1396. if self.proc.returncode != 0:
  1397. raise CmdFailed([''] + result)
  1398. return result
  1399. except:
  1400. self.terminate()
  1401. raise
  1402. def terminate(self):
  1403. """ Terminate process and cleanup. """
  1404. if self.alive:
  1405. if G_IS_WIN:
  1406. os.kill(self.proc.pid, signal.SIGINT)
  1407. else:
  1408. os.killpg(self.proc.pid, signal.SIGTERM)
  1409. self.clean()
  1410. class Plugin(object):
  1411. def __init__(self, name, args, buf_q, lock):
  1412. self.name = name
  1413. self.args = args
  1414. self.buf_q = buf_q
  1415. self.lock = lock
  1416. self.tag = args.get('tag', 0)
  1417. def manage(self):
  1418. try:
  1419. if os.path.exists(self.args['dir']):
  1420. self.update()
  1421. else:
  1422. self.install()
  1423. with self.lock:
  1424. thread_vim_command("let s:update.new['{0}'] = 1".format(self.name))
  1425. except PlugError as exc:
  1426. self.write(Action.ERROR, self.name, exc.msg)
  1427. except KeyboardInterrupt:
  1428. G_STOP.set()
  1429. self.write(Action.ERROR, self.name, ['Interrupted!'])
  1430. except:
  1431. # Any exception except those above print stack trace
  1432. msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip())
  1433. self.write(Action.ERROR, self.name, msg.split('\n'))
  1434. raise
  1435. def install(self):
  1436. target = self.args['dir']
  1437. if target[-1] == '\\':
  1438. target = target[0:-1]
  1439. def clean(target):
  1440. def _clean():
  1441. try:
  1442. shutil.rmtree(target)
  1443. except OSError:
  1444. pass
  1445. return _clean
  1446. self.write(Action.INSTALL, self.name, ['Installing ...'])
  1447. callback = functools.partial(self.write, Action.INSTALL, self.name)
  1448. cmd = 'git clone {0} {1} {2} {3} 2>&1'.format(
  1449. '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'],
  1450. esc(target))
  1451. com = Command(cmd, None, G_TIMEOUT, callback, clean(target))
  1452. result = com.execute(G_RETRIES)
  1453. self.write(Action.DONE, self.name, result[-1:])
  1454. def repo_uri(self):
  1455. cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url'
  1456. command = Command(cmd, self.args['dir'], G_TIMEOUT,)
  1457. result = command.execute(G_RETRIES)
  1458. return result[-1]
  1459. def update(self):
  1460. actual_uri = self.repo_uri()
  1461. expect_uri = self.args['uri']
  1462. regex = re.compile(r'^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$')
  1463. ma = regex.match(actual_uri)
  1464. mb = regex.match(expect_uri)
  1465. if ma is None or mb is None or ma.groups() != mb.groups():
  1466. msg = ['',
  1467. 'Invalid URI: {0}'.format(actual_uri),
  1468. 'Expected {0}'.format(expect_uri),
  1469. 'PlugClean required.']
  1470. raise InvalidURI(msg)
  1471. if G_PULL:
  1472. self.write(Action.UPDATE, self.name, ['Updating ...'])
  1473. callback = functools.partial(self.write, Action.UPDATE, self.name)
  1474. fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else ''
  1475. cmd = 'git fetch {0} {1} 2>&1'.format(fetch_opt, G_PROGRESS)
  1476. com = Command(cmd, self.args['dir'], G_TIMEOUT, callback)
  1477. result = com.execute(G_RETRIES)
  1478. self.write(Action.DONE, self.name, result[-1:])
  1479. else:
  1480. self.write(Action.DONE, self.name, ['Already installed'])
  1481. def write(self, action, name, msg):
  1482. self.buf_q.put((action, name, msg))
  1483. class PlugThread(thr.Thread):
  1484. def __init__(self, tname, args):
  1485. super(PlugThread, self).__init__()
  1486. self.tname = tname
  1487. self.args = args
  1488. def run(self):
  1489. thr.current_thread().name = self.tname
  1490. buf_q, work_q, lock = self.args
  1491. try:
  1492. while not G_STOP.is_set():
  1493. name, args = work_q.get_nowait()
  1494. plug = Plugin(name, args, buf_q, lock)
  1495. plug.manage()
  1496. work_q.task_done()
  1497. except queue.Empty:
  1498. pass
  1499. class RefreshThread(thr.Thread):
  1500. def __init__(self, lock):
  1501. super(RefreshThread, self).__init__()
  1502. self.lock = lock
  1503. self.running = True
  1504. def run(self):
  1505. while self.running:
  1506. with self.lock:
  1507. thread_vim_command('noautocmd normal! a')
  1508. time.sleep(0.33)
  1509. def stop(self):
  1510. self.running = False
  1511. if G_NVIM:
  1512. def thread_vim_command(cmd):
  1513. vim.session.threadsafe_call(lambda: vim.command(cmd))
  1514. else:
  1515. def thread_vim_command(cmd):
  1516. vim.command(cmd)
  1517. def esc(name):
  1518. return '"' + name.replace('"', '\"') + '"'
  1519. def nonblock_read(fname):
  1520. """ Read a file with nonblock flag. Return the last line. """
  1521. fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK)
  1522. buf = os.read(fread, 100000).decode('utf-8', 'replace')
  1523. os.close(fread)
  1524. line = buf.rstrip('\r\n')
  1525. left = max(line.rfind('\r'), line.rfind('\n'))
  1526. if left != -1:
  1527. left += 1
  1528. line = line[left:]
  1529. return line
  1530. def main():
  1531. thr.current_thread().name = 'main'
  1532. nthreads = int(vim.eval('s:update.threads'))
  1533. plugs = vim.eval('s:update.todo')
  1534. mac_gui = vim.eval('s:mac_gui') == '1'
  1535. lock = thr.Lock()
  1536. buf = Buffer(lock, len(plugs), G_PULL)
  1537. buf_q, work_q = queue.Queue(), queue.Queue()
  1538. for work in plugs.items():
  1539. work_q.put(work)
  1540. start_cnt = thr.active_count()
  1541. for num in range(nthreads):
  1542. tname = 'PlugT-{0:02}'.format(num)
  1543. thread = PlugThread(tname, (buf_q, work_q, lock))
  1544. thread.start()
  1545. if mac_gui:
  1546. rthread = RefreshThread(lock)
  1547. rthread.start()
  1548. while not buf_q.empty() or thr.active_count() != start_cnt:
  1549. try:
  1550. action, name, msg = buf_q.get(True, 0.25)
  1551. buf.write(action, name, ['OK'] if not msg else msg)
  1552. buf_q.task_done()
  1553. except queue.Empty:
  1554. pass
  1555. except KeyboardInterrupt:
  1556. G_STOP.set()
  1557. if mac_gui:
  1558. rthread.stop()
  1559. rthread.join()
  1560. main()
  1561. EOF
  1562. endfunction
  1563. function! s:update_ruby()
  1564. ruby << EOF
  1565. module PlugStream
  1566. SEP = ["\r", "\n", nil]
  1567. def get_line
  1568. buffer = ''
  1569. loop do
  1570. char = readchar rescue return
  1571. if SEP.include? char.chr
  1572. buffer << $/
  1573. break
  1574. else
  1575. buffer << char
  1576. end
  1577. end
  1578. buffer
  1579. end
  1580. end unless defined?(PlugStream)
  1581. def esc arg
  1582. %["#{arg.gsub('"', '\"')}"]
  1583. end
  1584. def killall pid
  1585. pids = [pid]
  1586. if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM
  1587. pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil }
  1588. else
  1589. unless `which pgrep 2> /dev/null`.empty?
  1590. children = pids
  1591. until children.empty?
  1592. children = children.map { |pid|
  1593. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  1594. }.flatten
  1595. pids += children
  1596. end
  1597. end
  1598. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  1599. end
  1600. end
  1601. def compare_git_uri a, b
  1602. regex = %r{^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$}
  1603. regex.match(a).to_a.drop(1) == regex.match(b).to_a.drop(1)
  1604. end
  1605. require 'thread'
  1606. require 'fileutils'
  1607. require 'timeout'
  1608. running = true
  1609. iswin = VIM::evaluate('s:is_win').to_i == 1
  1610. pull = VIM::evaluate('s:update.pull').to_i == 1
  1611. base = VIM::evaluate('g:plug_home')
  1612. all = VIM::evaluate('s:update.todo')
  1613. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  1614. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  1615. nthr = VIM::evaluate('s:update.threads').to_i
  1616. maxy = VIM::evaluate('winheight(".")').to_i
  1617. vim7 = VIM::evaluate('v:version').to_i <= 703 && RUBY_PLATFORM =~ /darwin/
  1618. cd = iswin ? 'cd /d' : 'cd'
  1619. tot = VIM::evaluate('len(s:update.todo)') || 0
  1620. bar = ''
  1621. skip = 'Already installed'
  1622. mtx = Mutex.new
  1623. take1 = proc { mtx.synchronize { running && all.shift } }
  1624. logh = proc {
  1625. cnt = bar.length
  1626. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  1627. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  1628. VIM::command('normal! 2G')
  1629. VIM::command('redraw')
  1630. }
  1631. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  1632. log = proc { |name, result, type|
  1633. mtx.synchronize do
  1634. ing = ![true, false].include?(type)
  1635. bar += type ? '=' : 'x' unless ing
  1636. b = case type
  1637. when :install then '+' when :update then '*'
  1638. when true, nil then '-' else
  1639. VIM::command("call add(s:update.errors, '#{name}')")
  1640. 'x'
  1641. end
  1642. result =
  1643. if type || type.nil?
  1644. ["#{b} #{name}: #{result.lines.to_a.last || 'OK'}"]
  1645. elsif result =~ /^Interrupted|^Timeout/
  1646. ["#{b} #{name}: #{result}"]
  1647. else
  1648. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  1649. end
  1650. if lnum = where.call(name)
  1651. $curbuf.delete lnum
  1652. lnum = 4 if ing && lnum > maxy
  1653. end
  1654. result.each_with_index do |line, offset|
  1655. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  1656. end
  1657. logh.call
  1658. end
  1659. }
  1660. bt = proc { |cmd, name, type, cleanup|
  1661. tried = timeout = 0
  1662. begin
  1663. tried += 1
  1664. timeout += limit
  1665. fd = nil
  1666. data = ''
  1667. if iswin
  1668. Timeout::timeout(timeout) do
  1669. tmp = VIM::evaluate('tempname()')
  1670. system("(#{cmd}) > #{tmp}")
  1671. data = File.read(tmp).chomp
  1672. File.unlink tmp rescue nil
  1673. end
  1674. else
  1675. fd = IO.popen(cmd).extend(PlugStream)
  1676. first_line = true
  1677. log_prob = 1.0 / nthr
  1678. while line = Timeout::timeout(timeout) { fd.get_line }
  1679. data << line
  1680. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  1681. first_line = false
  1682. end
  1683. fd.close
  1684. end
  1685. [$? == 0, data.chomp]
  1686. rescue Timeout::Error, Interrupt => e
  1687. if fd && !fd.closed?
  1688. killall fd.pid
  1689. fd.close
  1690. end
  1691. cleanup.call if cleanup
  1692. if e.is_a?(Timeout::Error) && tried < tries
  1693. 3.downto(1) do |countdown|
  1694. s = countdown > 1 ? 's' : ''
  1695. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  1696. sleep 1
  1697. end
  1698. log.call name, 'Retrying ...', type
  1699. retry
  1700. end
  1701. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  1702. end
  1703. }
  1704. main = Thread.current
  1705. threads = []
  1706. watcher = Thread.new {
  1707. if vim7
  1708. while VIM::evaluate('getchar(1)')
  1709. sleep 0.1
  1710. end
  1711. else
  1712. require 'io/console' # >= Ruby 1.9
  1713. nil until IO.console.getch == 3.chr
  1714. end
  1715. mtx.synchronize do
  1716. running = false
  1717. threads.each { |t| t.raise Interrupt } unless vim7
  1718. end
  1719. threads.each { |t| t.join rescue nil }
  1720. main.kill
  1721. }
  1722. refresh = Thread.new {
  1723. while true
  1724. mtx.synchronize do
  1725. break unless running
  1726. VIM::command('noautocmd normal! a')
  1727. end
  1728. sleep 0.2
  1729. end
  1730. } if VIM::evaluate('s:mac_gui') == 1
  1731. clone_opt = VIM::evaluate('s:clone_opt')
  1732. progress = VIM::evaluate('s:progress_opt(1)')
  1733. nthr.times do
  1734. mtx.synchronize do
  1735. threads << Thread.new {
  1736. while pair = take1.call
  1737. name = pair.first
  1738. dir, uri, tag = pair.last.values_at *%w[dir uri tag]
  1739. exists = File.directory? dir
  1740. ok, result =
  1741. if exists
  1742. chdir = "#{cd} #{iswin ? dir : esc(dir)}"
  1743. ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url", nil, nil, nil
  1744. current_uri = data.lines.to_a.last
  1745. if !ret
  1746. if data =~ /^Interrupted|^Timeout/
  1747. [false, data]
  1748. else
  1749. [false, [data.chomp, "PlugClean required."].join($/)]
  1750. end
  1751. elsif !compare_git_uri(current_uri, uri)
  1752. [false, ["Invalid URI: #{current_uri}",
  1753. "Expected: #{uri}",
  1754. "PlugClean required."].join($/)]
  1755. else
  1756. if pull
  1757. log.call name, 'Updating ...', :update
  1758. fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : ''
  1759. bt.call "#{chdir} && git fetch #{fetch_opt} #{progress} 2>&1", name, :update, nil
  1760. else
  1761. [true, skip]
  1762. end
  1763. end
  1764. else
  1765. d = esc dir.sub(%r{[\\/]+$}, '')
  1766. log.call name, 'Installing ...', :install
  1767. bt.call "git clone #{clone_opt unless tag} #{progress} #{uri} #{d} 2>&1", name, :install, proc {
  1768. FileUtils.rm_rf dir
  1769. }
  1770. end
  1771. mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
  1772. log.call name, result, ok
  1773. end
  1774. } if running
  1775. end
  1776. end
  1777. threads.each { |t| t.join rescue nil }
  1778. logh.call
  1779. refresh.kill if refresh
  1780. watcher.kill
  1781. EOF
  1782. endfunction
  1783. function! s:shellesc_cmd(arg)
  1784. let escaped = substitute(a:arg, '[&|<>()@^]', '^&', 'g')
  1785. let escaped = substitute(escaped, '%', '%%', 'g')
  1786. let escaped = substitute(escaped, '"', '\\^&', 'g')
  1787. let escaped = substitute(escaped, '\(\\\+\)\(\\^\)', '\1\1\2', 'g')
  1788. return '^"'.substitute(escaped, '\(\\\+\)$', '\1\1', '').'^"'
  1789. endfunction
  1790. function! s:shellesc(arg)
  1791. if &shell =~# 'cmd.exe$'
  1792. return s:shellesc_cmd(a:arg)
  1793. endif
  1794. return shellescape(a:arg)
  1795. endfunction
  1796. function! s:glob_dir(path)
  1797. return map(filter(s:glob(a:path, '**'), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  1798. endfunction
  1799. function! s:progress_bar(line, bar, total)
  1800. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  1801. endfunction
  1802. function! s:compare_git_uri(a, b)
  1803. " See `git help clone'
  1804. " https:// [user@] github.com[:port] / junegunn/vim-plug [.git]
  1805. " [git@] github.com[:port] : junegunn/vim-plug [.git]
  1806. " file:// / junegunn/vim-plug [/]
  1807. " / junegunn/vim-plug [/]
  1808. let pat = '^\%(\w\+://\)\='.'\%([^@/]*@\)\='.'\([^:/]*\%(:[0-9]*\)\=\)'.'[:/]'.'\(.\{-}\)'.'\%(\.git\)\=/\?$'
  1809. let ma = matchlist(a:a, pat)
  1810. let mb = matchlist(a:b, pat)
  1811. return ma[1:2] ==# mb[1:2]
  1812. endfunction
  1813. function! s:format_message(bullet, name, message)
  1814. if a:bullet != 'x'
  1815. return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
  1816. else
  1817. let lines = map(s:lines(a:message), '" ".v:val')
  1818. return extend([printf('x %s:', a:name)], lines)
  1819. endif
  1820. endfunction
  1821. function! s:with_cd(cmd, dir)
  1822. return printf('cd%s %s && %s', s:is_win ? ' /d' : '', s:shellesc(a:dir), a:cmd)
  1823. endfunction
  1824. function! s:system(cmd, ...)
  1825. try
  1826. let [sh, shellcmdflag, shrd] = s:chsh(1)
  1827. let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
  1828. if s:is_win
  1829. let batchfile = tempname().'.bat'
  1830. call writefile(["@echo off\r", cmd . "\r"], batchfile)
  1831. let cmd = batchfile
  1832. endif
  1833. return system(s:is_win ? '('.cmd.')' : cmd)
  1834. finally
  1835. let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd]
  1836. if s:is_win
  1837. call delete(batchfile)
  1838. endif
  1839. endtry
  1840. endfunction
  1841. function! s:system_chomp(...)
  1842. let ret = call('s:system', a:000)
  1843. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  1844. endfunction
  1845. function! s:git_validate(spec, check_branch)
  1846. let err = ''
  1847. if isdirectory(a:spec.dir)
  1848. 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))
  1849. let remote = result[-1]
  1850. if v:shell_error
  1851. let err = join([remote, 'PlugClean required.'], "\n")
  1852. elseif !s:compare_git_uri(remote, a:spec.uri)
  1853. let err = join(['Invalid URI: '.remote,
  1854. \ 'Expected: '.a:spec.uri,
  1855. \ 'PlugClean required.'], "\n")
  1856. elseif a:check_branch && has_key(a:spec, 'commit')
  1857. let result = s:lines(s:system('git rev-parse HEAD 2>&1', a:spec.dir))
  1858. let sha = result[-1]
  1859. if v:shell_error
  1860. let err = join(add(result, 'PlugClean required.'), "\n")
  1861. elseif !s:hash_match(sha, a:spec.commit)
  1862. let err = join([printf('Invalid HEAD (expected: %s, actual: %s)',
  1863. \ a:spec.commit[:6], sha[:6]),
  1864. \ 'PlugUpdate required.'], "\n")
  1865. endif
  1866. elseif a:check_branch
  1867. let branch = result[0]
  1868. " Check tag
  1869. if has_key(a:spec, 'tag')
  1870. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
  1871. if a:spec.tag !=# tag && a:spec.tag !~ '\*'
  1872. let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.',
  1873. \ (empty(tag) ? 'N/A' : tag), a:spec.tag)
  1874. endif
  1875. " Check branch
  1876. elseif a:spec.branch !=# branch
  1877. let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.',
  1878. \ branch, a:spec.branch)
  1879. endif
  1880. if empty(err)
  1881. let [ahead, behind] = split(s:lastline(s:system(printf(
  1882. \ 'git rev-list --count --left-right HEAD...origin/%s',
  1883. \ a:spec.branch), a:spec.dir)), '\t')
  1884. if !v:shell_error && ahead
  1885. if behind
  1886. " Only mention PlugClean if diverged, otherwise it's likely to be
  1887. " pushable (and probably not that messed up).
  1888. let err = printf(
  1889. \ "Diverged from origin/%s (%d commit(s) ahead and %d commit(s) behind!\n"
  1890. \ .'Backup local changes and run PlugClean and PlugUpdate to reinstall it.', a:spec.branch, ahead, behind)
  1891. else
  1892. let err = printf("Ahead of origin/%s by %d commit(s).\n"
  1893. \ .'Cannot update until local changes are pushed.',
  1894. \ a:spec.branch, ahead)
  1895. endif
  1896. endif
  1897. endif
  1898. endif
  1899. else
  1900. let err = 'Not found'
  1901. endif
  1902. return [err, err =~# 'PlugClean']
  1903. endfunction
  1904. function! s:rm_rf(dir)
  1905. if isdirectory(a:dir)
  1906. call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(a:dir))
  1907. endif
  1908. endfunction
  1909. function! s:clean(force)
  1910. call s:prepare()
  1911. call append(0, 'Searching for invalid plugins in '.g:plug_home)
  1912. call append(1, '')
  1913. " List of valid directories
  1914. let dirs = []
  1915. let errs = {}
  1916. let [cnt, total] = [0, len(g:plugs)]
  1917. for [name, spec] in items(g:plugs)
  1918. if !s:is_managed(name)
  1919. call add(dirs, spec.dir)
  1920. else
  1921. let [err, clean] = s:git_validate(spec, 1)
  1922. if clean
  1923. let errs[spec.dir] = s:lines(err)[0]
  1924. else
  1925. call add(dirs, spec.dir)
  1926. endif
  1927. endif
  1928. let cnt += 1
  1929. call s:progress_bar(2, repeat('=', cnt), total)
  1930. normal! 2G
  1931. redraw
  1932. endfor
  1933. let allowed = {}
  1934. for dir in dirs
  1935. let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
  1936. let allowed[dir] = 1
  1937. for child in s:glob_dir(dir)
  1938. let allowed[child] = 1
  1939. endfor
  1940. endfor
  1941. let todo = []
  1942. let found = sort(s:glob_dir(g:plug_home))
  1943. while !empty(found)
  1944. let f = remove(found, 0)
  1945. if !has_key(allowed, f) && isdirectory(f)
  1946. call add(todo, f)
  1947. call append(line('$'), '- ' . f)
  1948. if has_key(errs, f)
  1949. call append(line('$'), ' ' . errs[f])
  1950. endif
  1951. let found = filter(found, 'stridx(v:val, f) != 0')
  1952. end
  1953. endwhile
  1954. 4
  1955. redraw
  1956. if empty(todo)
  1957. call append(line('$'), 'Already clean.')
  1958. else
  1959. let s:clean_count = 0
  1960. call append(3, ['Directories to delete:', ''])
  1961. redraw!
  1962. if a:force || s:ask_no_interrupt('Delete all directories?')
  1963. call s:delete([6, line('$')], 1)
  1964. else
  1965. call setline(4, 'Cancelled.')
  1966. nnoremap <silent> <buffer> d :set opfunc=<sid>delete_op<cr>g@
  1967. nmap <silent> <buffer> dd d_
  1968. xnoremap <silent> <buffer> d :<c-u>call <sid>delete_op(visualmode(), 1)<cr>
  1969. echo 'Delete the lines (d{motion}) to delete the corresponding directories'
  1970. endif
  1971. endif
  1972. 4
  1973. setlocal nomodifiable
  1974. endfunction
  1975. function! s:delete_op(type, ...)
  1976. call s:delete(a:0 ? [line("'<"), line("'>")] : [line("'["), line("']")], 0)
  1977. endfunction
  1978. function! s:delete(range, force)
  1979. let [l1, l2] = a:range
  1980. let force = a:force
  1981. while l1 <= l2
  1982. let line = getline(l1)
  1983. if line =~ '^- ' && isdirectory(line[2:])
  1984. execute l1
  1985. redraw!
  1986. let answer = force ? 1 : s:ask('Delete '.line[2:].'?', 1)
  1987. let force = force || answer > 1
  1988. if answer
  1989. call s:rm_rf(line[2:])
  1990. setlocal modifiable
  1991. call setline(l1, '~'.line[1:])
  1992. let s:clean_count += 1
  1993. call setline(4, printf('Removed %d directories.', s:clean_count))
  1994. setlocal nomodifiable
  1995. endif
  1996. endif
  1997. let l1 += 1
  1998. endwhile
  1999. endfunction
  2000. function! s:upgrade()
  2001. echo 'Downloading the latest version of vim-plug'
  2002. redraw
  2003. let tmp = tempname()
  2004. let new = tmp . '/plug.vim'
  2005. try
  2006. let out = s:system(printf('git clone --depth 1 %s %s', s:plug_src, tmp))
  2007. if v:shell_error
  2008. return s:err('Error upgrading vim-plug: '. out)
  2009. endif
  2010. if readfile(s:me) ==# readfile(new)
  2011. echo 'vim-plug is already up-to-date'
  2012. return 0
  2013. else
  2014. call rename(s:me, s:me . '.old')
  2015. call rename(new, s:me)
  2016. unlet g:loaded_plug
  2017. echo 'vim-plug has been upgraded'
  2018. return 1
  2019. endif
  2020. finally
  2021. silent! call s:rm_rf(tmp)
  2022. endtry
  2023. endfunction
  2024. function! s:upgrade_specs()
  2025. for spec in values(g:plugs)
  2026. let spec.frozen = get(spec, 'frozen', 0)
  2027. endfor
  2028. endfunction
  2029. function! s:status()
  2030. call s:prepare()
  2031. call append(0, 'Checking plugins')
  2032. call append(1, '')
  2033. let ecnt = 0
  2034. let unloaded = 0
  2035. let [cnt, total] = [0, len(g:plugs)]
  2036. for [name, spec] in items(g:plugs)
  2037. let is_dir = isdirectory(spec.dir)
  2038. if has_key(spec, 'uri')
  2039. if is_dir
  2040. let [err, _] = s:git_validate(spec, 1)
  2041. let [valid, msg] = [empty(err), empty(err) ? 'OK' : err]
  2042. else
  2043. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  2044. endif
  2045. else
  2046. if is_dir
  2047. let [valid, msg] = [1, 'OK']
  2048. else
  2049. let [valid, msg] = [0, 'Not found.']
  2050. endif
  2051. endif
  2052. let cnt += 1
  2053. let ecnt += !valid
  2054. " `s:loaded` entry can be missing if PlugUpgraded
  2055. if is_dir && get(s:loaded, name, -1) == 0
  2056. let unloaded = 1
  2057. let msg .= ' (not loaded)'
  2058. endif
  2059. call s:progress_bar(2, repeat('=', cnt), total)
  2060. call append(3, s:format_message(valid ? '-' : 'x', name, msg))
  2061. normal! 2G
  2062. redraw
  2063. endfor
  2064. call setline(1, 'Finished. '.ecnt.' error(s).')
  2065. normal! gg
  2066. setlocal nomodifiable
  2067. if unloaded
  2068. echo "Press 'L' on each line to load plugin, or 'U' to update"
  2069. nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  2070. xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  2071. end
  2072. endfunction
  2073. function! s:extract_name(str, prefix, suffix)
  2074. return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
  2075. endfunction
  2076. function! s:status_load(lnum)
  2077. let line = getline(a:lnum)
  2078. let name = s:extract_name(line, '-', '(not loaded)')
  2079. if !empty(name)
  2080. call plug#load(name)
  2081. setlocal modifiable
  2082. call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
  2083. setlocal nomodifiable
  2084. endif
  2085. endfunction
  2086. function! s:status_update() range
  2087. let lines = getline(a:firstline, a:lastline)
  2088. let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
  2089. if !empty(names)
  2090. echo
  2091. execute 'PlugUpdate' join(names)
  2092. endif
  2093. endfunction
  2094. function! s:is_preview_window_open()
  2095. silent! wincmd P
  2096. if &previewwindow
  2097. wincmd p
  2098. return 1
  2099. endif
  2100. endfunction
  2101. function! s:find_name(lnum)
  2102. for lnum in reverse(range(1, a:lnum))
  2103. let line = getline(lnum)
  2104. if empty(line)
  2105. return ''
  2106. endif
  2107. let name = s:extract_name(line, '-', '')
  2108. if !empty(name)
  2109. return name
  2110. endif
  2111. endfor
  2112. return ''
  2113. endfunction
  2114. function! s:preview_commit()
  2115. if b:plug_preview < 0
  2116. let b:plug_preview = !s:is_preview_window_open()
  2117. endif
  2118. let sha = matchstr(getline('.'), '^ \X*\zs[0-9a-f]\{7,9}')
  2119. if empty(sha)
  2120. return
  2121. endif
  2122. let name = s:find_name(line('.'))
  2123. if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
  2124. return
  2125. endif
  2126. if exists('g:plug_pwindow') && !s:is_preview_window_open()
  2127. execute g:plug_pwindow
  2128. execute 'e' sha
  2129. else
  2130. execute 'pedit' sha
  2131. wincmd P
  2132. endif
  2133. setlocal previewwindow filetype=git buftype=nofile nobuflisted modifiable
  2134. try
  2135. let [sh, shellcmdflag, shrd] = s:chsh(1)
  2136. let cmd = 'cd '.s:shellesc(g:plugs[name].dir).' && git show --no-color --pretty=medium '.sha
  2137. if s:is_win
  2138. let batchfile = tempname().'.bat'
  2139. call writefile(["@echo off\r", cmd . "\r"], batchfile)
  2140. let cmd = batchfile
  2141. endif
  2142. execute 'silent %!' cmd
  2143. finally
  2144. let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd]
  2145. if s:is_win
  2146. call delete(batchfile)
  2147. endif
  2148. endtry
  2149. setlocal nomodifiable
  2150. nnoremap <silent> <buffer> q :q<cr>
  2151. wincmd p
  2152. endfunction
  2153. function! s:section(flags)
  2154. call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
  2155. endfunction
  2156. function! s:format_git_log(line)
  2157. let indent = ' '
  2158. let tokens = split(a:line, nr2char(1))
  2159. if len(tokens) != 5
  2160. return indent.substitute(a:line, '\s*$', '', '')
  2161. endif
  2162. let [graph, sha, refs, subject, date] = tokens
  2163. let tag = matchstr(refs, 'tag: [^,)]\+')
  2164. let tag = empty(tag) ? ' ' : ' ('.tag.') '
  2165. return printf('%s%s%s%s%s (%s)', indent, graph, sha, tag, subject, date)
  2166. endfunction
  2167. function! s:append_ul(lnum, text)
  2168. call append(a:lnum, ['', a:text, repeat('-', len(a:text))])
  2169. endfunction
  2170. function! s:diff()
  2171. call s:prepare()
  2172. call append(0, ['Collecting changes ...', ''])
  2173. let cnts = [0, 0]
  2174. let bar = ''
  2175. let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)')
  2176. call s:progress_bar(2, bar, len(total))
  2177. for origin in [1, 0]
  2178. let plugs = reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))'))))
  2179. if empty(plugs)
  2180. continue
  2181. endif
  2182. call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:')
  2183. for [k, v] in plugs
  2184. let range = origin ? '..origin/'.v.branch : 'HEAD@{1}..'
  2185. let cmd = 'git log --graph --color=never '.join(map(['--pretty=format:%x01%h%x01%d%x01%s%x01%cr', range], 's:shellesc(v:val)'))
  2186. if has_key(v, 'rtp')
  2187. let cmd .= ' -- '.s:shellesc(v.rtp)
  2188. endif
  2189. let diff = s:system_chomp(cmd, v.dir)
  2190. if !empty(diff)
  2191. let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : ''
  2192. call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)')))
  2193. let cnts[origin] += 1
  2194. endif
  2195. let bar .= '='
  2196. call s:progress_bar(2, bar, len(total))
  2197. normal! 2G
  2198. redraw
  2199. endfor
  2200. if !cnts[origin]
  2201. call append(5, ['', 'N/A'])
  2202. endif
  2203. endfor
  2204. call setline(1, printf('%d plugin(s) updated.', cnts[0])
  2205. \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : ''))
  2206. if cnts[0] || cnts[1]
  2207. nnoremap <silent> <buffer> <plug>(plug-preview) :silent! call <SID>preview_commit()<cr>
  2208. if empty(maparg("\<cr>", 'n'))
  2209. nmap <buffer> <cr> <plug>(plug-preview)
  2210. endif
  2211. if empty(maparg('o', 'n'))
  2212. nmap <buffer> o <plug>(plug-preview)
  2213. endif
  2214. endif
  2215. if cnts[0]
  2216. nnoremap <silent> <buffer> X :call <SID>revert()<cr>
  2217. echo "Press 'X' on each block to revert the update"
  2218. endif
  2219. normal! gg
  2220. setlocal nomodifiable
  2221. endfunction
  2222. function! s:revert()
  2223. if search('^Pending updates', 'bnW')
  2224. return
  2225. endif
  2226. let name = s:find_name(line('.'))
  2227. if empty(name) || !has_key(g:plugs, name) ||
  2228. \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
  2229. return
  2230. endif
  2231. call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch).' --', g:plugs[name].dir)
  2232. setlocal modifiable
  2233. normal! "_dap
  2234. setlocal nomodifiable
  2235. echo 'Reverted'
  2236. endfunction
  2237. function! s:snapshot(force, ...) abort
  2238. call s:prepare()
  2239. setf vim
  2240. call append(0, ['" Generated by vim-plug',
  2241. \ '" '.strftime("%c"),
  2242. \ '" :source this file in vim to restore the snapshot',
  2243. \ '" or execute: vim -S snapshot.vim',
  2244. \ '', '', 'PlugUpdate!'])
  2245. 1
  2246. let anchor = line('$') - 3
  2247. let names = sort(keys(filter(copy(g:plugs),
  2248. \'has_key(v:val, "uri") && !has_key(v:val, "commit") && isdirectory(v:val.dir)')))
  2249. for name in reverse(names)
  2250. let sha = s:system_chomp('git rev-parse --short HEAD', g:plugs[name].dir)
  2251. if !empty(sha)
  2252. call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha))
  2253. redraw
  2254. endif
  2255. endfor
  2256. if a:0 > 0
  2257. let fn = expand(a:1)
  2258. if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?'))
  2259. return
  2260. endif
  2261. call writefile(getline(1, '$'), fn)
  2262. echo 'Saved as '.a:1
  2263. silent execute 'e' s:esc(fn)
  2264. setf vim
  2265. endif
  2266. endfunction
  2267. function! s:split_rtp()
  2268. return split(&rtp, '\\\@<!,')
  2269. endfunction
  2270. let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
  2271. let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
  2272. if exists('g:plugs')
  2273. let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
  2274. call s:upgrade_specs()
  2275. call s:define_commands()
  2276. endif
  2277. let &cpo = s:cpo_save
  2278. unlet s:cpo_save