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