plug.vim 62 KB

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