plug.vim 56 KB

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