plug.vim 58 KB

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