plug.vim 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037
  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 && index(s:update.errors, name) < 0 && !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 PlugError(Exception):
  941. def __init__(self, msg):
  942. self._msg = msg
  943. @property
  944. def msg(self):
  945. return self._msg
  946. class CmdTimedOut(PlugError):
  947. pass
  948. class CmdFailed(PlugError):
  949. pass
  950. class InvalidURI(PlugError):
  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. msg.extend([' ' + line for line in rest])
  987. try:
  988. if action == Action.ERROR:
  989. self.bar += 'x'
  990. vim.command("call add(s:update.errors, '{0}')".format(name))
  991. elif action == Action.DONE:
  992. self.bar += '='
  993. curbuf = vim.current.buffer
  994. lnum = self.__where(name)
  995. if lnum != -1: # Found matching line num
  996. del curbuf[lnum]
  997. if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]):
  998. lnum = 3
  999. else:
  1000. lnum = 3
  1001. curbuf.append(msg, lnum)
  1002. self.header()
  1003. except vim.error:
  1004. pass
  1005. class Command(object):
  1006. def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None):
  1007. self.cmd = cmd
  1008. self.cmd_dir = cmd_dir
  1009. self.timeout = timeout
  1010. self.callback = cb if cb else (lambda msg: None)
  1011. self.clean = clean if clean else (lambda: None)
  1012. self.proc = None
  1013. @property
  1014. def alive(self):
  1015. """ Returns true only if command still running. """
  1016. return self.proc and self.proc.poll() is None
  1017. def execute(self, ntries=3):
  1018. """ Execute the command with ntries if CmdTimedOut.
  1019. Returns the output of the command if no Exception.
  1020. """
  1021. attempt, finished, limit = 0, False, self.timeout
  1022. while not finished:
  1023. try:
  1024. attempt += 1
  1025. result = self.try_command()
  1026. finished = True
  1027. return result
  1028. except CmdTimedOut:
  1029. if attempt != ntries:
  1030. self.notify_retry()
  1031. self.timeout += limit
  1032. else:
  1033. raise
  1034. def notify_retry(self):
  1035. """ Retry required for command, notify user. """
  1036. for count in range(3, 0, -1):
  1037. if G_STOP.is_set():
  1038. raise KeyboardInterrupt
  1039. msg = 'Timeout. Will retry in {0} second{1} ...'.format(
  1040. count, 's' if count != 1 else '')
  1041. self.callback([msg])
  1042. time.sleep(1)
  1043. self.callback(['Retrying ...'])
  1044. def try_command(self):
  1045. """ Execute a cmd & poll for callback. Returns list of output.
  1046. Raises CmdFailed -> return code for Popen isn't 0
  1047. Raises CmdTimedOut -> command exceeded timeout without new output
  1048. """
  1049. first_line = True
  1050. try:
  1051. tfile = tempfile.NamedTemporaryFile(mode='w+b')
  1052. self.proc = subprocess.Popen(self.cmd, cwd=self.cmd_dir, stdout=tfile,
  1053. stderr=subprocess.STDOUT, shell=True,
  1054. preexec_fn=os.setsid)
  1055. thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,))
  1056. thrd.start()
  1057. thread_not_started = True
  1058. while thread_not_started:
  1059. try:
  1060. thrd.join(0.1)
  1061. thread_not_started = False
  1062. except RuntimeError:
  1063. pass
  1064. while self.alive:
  1065. if G_STOP.is_set():
  1066. raise KeyboardInterrupt
  1067. if first_line or random.random() < G_LOG_PROB:
  1068. first_line = False
  1069. line = nonblock_read(tfile.name)
  1070. if line:
  1071. self.callback([line])
  1072. time_diff = time.time() - os.path.getmtime(tfile.name)
  1073. if time_diff > self.timeout:
  1074. raise CmdTimedOut(['Timeout!'])
  1075. thrd.join(0.5)
  1076. tfile.seek(0)
  1077. result = [line.decode('utf-8', 'replace').rstrip() for line in tfile]
  1078. if self.proc.returncode != 0:
  1079. raise CmdFailed([''] + result)
  1080. return result
  1081. except:
  1082. self.terminate()
  1083. raise
  1084. def terminate(self):
  1085. """ Terminate process and cleanup. """
  1086. if self.alive:
  1087. os.killpg(self.proc.pid, signal.SIGTERM)
  1088. self.clean()
  1089. class Plugin(object):
  1090. def __init__(self, name, args, buf_q, lock):
  1091. self.name = name
  1092. self.args = args
  1093. self.buf_q = buf_q
  1094. self.lock = lock
  1095. tag = args.get('tag', 0)
  1096. self.checkout = esc(tag if tag else args['branch'])
  1097. self.merge = esc(tag if tag else 'origin/' + args['branch'])
  1098. self.tag = tag
  1099. def manage(self):
  1100. try:
  1101. if os.path.exists(self.args['dir']):
  1102. self.update()
  1103. else:
  1104. self.install()
  1105. with self.lock:
  1106. thread_vim_command("let s:update.new['{0}'] = 1".format(self.name))
  1107. except PlugError as exc:
  1108. self.write(Action.ERROR, self.name, exc.msg)
  1109. except KeyboardInterrupt:
  1110. G_STOP.set()
  1111. self.write(Action.ERROR, self.name, ['Interrupted!'])
  1112. except:
  1113. # Any exception except those above print stack trace
  1114. msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip())
  1115. self.write(Action.ERROR, self.name, msg.split('\n'))
  1116. raise
  1117. def install(self):
  1118. target = self.args['dir']
  1119. def clean(target):
  1120. def _clean():
  1121. try:
  1122. shutil.rmtree(target)
  1123. except OSError:
  1124. pass
  1125. return _clean
  1126. self.write(Action.INSTALL, self.name, ['Installing ...'])
  1127. callback = functools.partial(self.write, Action.INSTALL, self.name)
  1128. cmd = 'git clone {0} {1} --recursive {2} -b {3} {4} 2>&1'.format(
  1129. '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'],
  1130. self.checkout, esc(target))
  1131. com = Command(cmd, None, G_TIMEOUT, callback, clean(target))
  1132. result = com.execute(G_RETRIES)
  1133. self.write(Action.DONE, self.name, result[-1:])
  1134. def repo_uri(self):
  1135. cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url'
  1136. command = Command(cmd, self.args['dir'], G_TIMEOUT,)
  1137. result = command.execute(G_RETRIES)
  1138. return result[-1]
  1139. def update(self):
  1140. match = re.compile(r'git::?@')
  1141. actual_uri = re.sub(match, '', self.repo_uri())
  1142. expect_uri = re.sub(match, '', self.args['uri'])
  1143. if actual_uri != expect_uri:
  1144. msg = ['',
  1145. 'Invalid URI: {0}'.format(actual_uri),
  1146. 'Expected {0}'.format(expect_uri),
  1147. 'PlugClean required.']
  1148. raise InvalidURI(msg)
  1149. if G_PULL:
  1150. self.write(Action.UPDATE, self.name, ['Updating ...'])
  1151. callback = functools.partial(self.write, Action.UPDATE, self.name)
  1152. fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else ''
  1153. cmds = ['git fetch {0} {1}'.format(fetch_opt, G_PROGRESS),
  1154. 'git checkout -q {0}'.format(self.checkout),
  1155. 'git merge --ff-only {0}'.format(self.merge),
  1156. 'git submodule update --init --recursive']
  1157. cmd = ' 2>&1 && '.join(cmds)
  1158. com = Command(cmd, self.args['dir'], G_TIMEOUT, callback)
  1159. result = com.execute(G_RETRIES)
  1160. self.write(Action.DONE, self.name, result[-1:])
  1161. else:
  1162. self.write(Action.DONE, self.name, ['Already installed'])
  1163. def write(self, action, name, msg):
  1164. self.buf_q.put((action, name, msg))
  1165. class PlugThread(thr.Thread):
  1166. def __init__(self, tname, args):
  1167. super(PlugThread, self).__init__()
  1168. self.tname = tname
  1169. self.args = args
  1170. def run(self):
  1171. thr.current_thread().name = self.tname
  1172. buf_q, work_q, lock = self.args
  1173. try:
  1174. while not G_STOP.is_set():
  1175. name, args = work_q.get_nowait()
  1176. plug = Plugin(name, args, buf_q, lock)
  1177. plug.manage()
  1178. work_q.task_done()
  1179. except queue.Empty:
  1180. pass
  1181. finally:
  1182. global G_THREADS
  1183. with lock:
  1184. del G_THREADS[thr.current_thread().name]
  1185. class RefreshThread(thr.Thread):
  1186. def __init__(self, lock):
  1187. super(RefreshThread, self).__init__()
  1188. self.lock = lock
  1189. self.running = True
  1190. def run(self):
  1191. while self.running:
  1192. with self.lock:
  1193. thread_vim_command('noautocmd normal! a')
  1194. time.sleep(0.33)
  1195. def stop(self):
  1196. self.running = False
  1197. if G_NVIM:
  1198. def thread_vim_command(cmd):
  1199. vim.session.threadsafe_call(lambda: vim.command(cmd))
  1200. else:
  1201. def thread_vim_command(cmd):
  1202. vim.command(cmd)
  1203. def esc(name):
  1204. return '"' + name.replace('"', '\"') + '"'
  1205. def nonblock_read(fname):
  1206. """ Read a file with nonblock flag. Return the last line. """
  1207. fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK)
  1208. buf = os.read(fread, 100000).decode('utf-8', 'replace')
  1209. os.close(fread)
  1210. line = buf.rstrip('\r\n')
  1211. left = max(line.rfind('\r'), line.rfind('\n'))
  1212. if left != -1:
  1213. left += 1
  1214. line = line[left:]
  1215. return line
  1216. def main():
  1217. thr.current_thread().name = 'main'
  1218. nthreads = int(vim.eval('s:update.threads'))
  1219. plugs = vim.eval('s:update.todo')
  1220. mac_gui = vim.eval('s:mac_gui') == '1'
  1221. is_win = vim.eval('s:is_win') == '1'
  1222. lock = thr.Lock()
  1223. buf = Buffer(lock, len(plugs), G_PULL, is_win)
  1224. buf_q, work_q = queue.Queue(), queue.Queue()
  1225. for work in plugs.items():
  1226. work_q.put(work)
  1227. global G_THREADS
  1228. for num in range(nthreads):
  1229. tname = 'PlugT-{0:02}'.format(num)
  1230. thread = PlugThread(tname, (buf_q, work_q, lock))
  1231. thread.start()
  1232. G_THREADS[tname] = thread
  1233. if mac_gui:
  1234. rthread = RefreshThread(lock)
  1235. rthread.start()
  1236. while not buf_q.empty() or len(G_THREADS) != 0:
  1237. try:
  1238. action, name, msg = buf_q.get(True, 0.25)
  1239. buf.write(action, name, msg)
  1240. buf_q.task_done()
  1241. except queue.Empty:
  1242. pass
  1243. except KeyboardInterrupt:
  1244. G_STOP.set()
  1245. if mac_gui:
  1246. rthread.stop()
  1247. rthread.join()
  1248. main()
  1249. EOF
  1250. endfunction
  1251. function! s:update_ruby()
  1252. ruby << EOF
  1253. module PlugStream
  1254. SEP = ["\r", "\n", nil]
  1255. def get_line
  1256. buffer = ''
  1257. loop do
  1258. char = readchar rescue return
  1259. if SEP.include? char.chr
  1260. buffer << $/
  1261. break
  1262. else
  1263. buffer << char
  1264. end
  1265. end
  1266. buffer
  1267. end
  1268. end unless defined?(PlugStream)
  1269. def esc arg
  1270. %["#{arg.gsub('"', '\"')}"]
  1271. end
  1272. def killall pid
  1273. pids = [pid]
  1274. unless `which pgrep 2> /dev/null`.empty?
  1275. children = pids
  1276. until children.empty?
  1277. children = children.map { |pid|
  1278. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  1279. }.flatten
  1280. pids += children
  1281. end
  1282. end
  1283. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  1284. end
  1285. require 'thread'
  1286. require 'fileutils'
  1287. require 'timeout'
  1288. running = true
  1289. iswin = VIM::evaluate('s:is_win').to_i == 1
  1290. pull = VIM::evaluate('s:update.pull').to_i == 1
  1291. base = VIM::evaluate('g:plug_home')
  1292. all = VIM::evaluate('s:update.todo')
  1293. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  1294. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  1295. nthr = VIM::evaluate('s:update.threads').to_i
  1296. maxy = VIM::evaluate('winheight(".")').to_i
  1297. cd = iswin ? 'cd /d' : 'cd'
  1298. tot = VIM::evaluate('len(s:update.todo)') || 0
  1299. bar = ''
  1300. skip = 'Already installed'
  1301. mtx = Mutex.new
  1302. take1 = proc { mtx.synchronize { running && all.shift } }
  1303. logh = proc {
  1304. cnt = bar.length
  1305. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  1306. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  1307. VIM::command('normal! 2G')
  1308. VIM::command('redraw') unless iswin
  1309. }
  1310. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  1311. log = proc { |name, result, type|
  1312. mtx.synchronize do
  1313. ing = ![true, false].include?(type)
  1314. bar += type ? '=' : 'x' unless ing
  1315. b = case type
  1316. when :install then '+' when :update then '*'
  1317. when true, nil then '-' else
  1318. VIM::command("call add(s:update.errors, '#{name}')")
  1319. 'x'
  1320. end
  1321. result =
  1322. if type || type.nil?
  1323. ["#{b} #{name}: #{result.lines.to_a.last}"]
  1324. elsif result =~ /^Interrupted|^Timeout/
  1325. ["#{b} #{name}: #{result}"]
  1326. else
  1327. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  1328. end
  1329. if lnum = where.call(name)
  1330. $curbuf.delete lnum
  1331. lnum = 4 if ing && lnum > maxy
  1332. end
  1333. result.each_with_index do |line, offset|
  1334. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  1335. end
  1336. logh.call
  1337. end
  1338. }
  1339. bt = proc { |cmd, name, type, cleanup|
  1340. tried = timeout = 0
  1341. begin
  1342. tried += 1
  1343. timeout += limit
  1344. fd = nil
  1345. data = ''
  1346. if iswin
  1347. Timeout::timeout(timeout) do
  1348. tmp = VIM::evaluate('tempname()')
  1349. system("(#{cmd}) > #{tmp}")
  1350. data = File.read(tmp).chomp
  1351. File.unlink tmp rescue nil
  1352. end
  1353. else
  1354. fd = IO.popen(cmd).extend(PlugStream)
  1355. first_line = true
  1356. log_prob = 1.0 / nthr
  1357. while line = Timeout::timeout(timeout) { fd.get_line }
  1358. data << line
  1359. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  1360. first_line = false
  1361. end
  1362. fd.close
  1363. end
  1364. [$? == 0, data.chomp]
  1365. rescue Timeout::Error, Interrupt => e
  1366. if fd && !fd.closed?
  1367. killall fd.pid
  1368. fd.close
  1369. end
  1370. cleanup.call if cleanup
  1371. if e.is_a?(Timeout::Error) && tried < tries
  1372. 3.downto(1) do |countdown|
  1373. s = countdown > 1 ? 's' : ''
  1374. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  1375. sleep 1
  1376. end
  1377. log.call name, 'Retrying ...', type
  1378. retry
  1379. end
  1380. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  1381. end
  1382. }
  1383. main = Thread.current
  1384. threads = []
  1385. watcher = Thread.new {
  1386. while VIM::evaluate('getchar(1)')
  1387. sleep 0.1
  1388. end
  1389. mtx.synchronize do
  1390. running = false
  1391. threads.each { |t| t.raise Interrupt }
  1392. end
  1393. threads.each { |t| t.join rescue nil }
  1394. main.kill
  1395. }
  1396. refresh = Thread.new {
  1397. while true
  1398. mtx.synchronize do
  1399. break unless running
  1400. VIM::command('noautocmd normal! a')
  1401. end
  1402. sleep 0.2
  1403. end
  1404. } if VIM::evaluate('s:mac_gui') == 1
  1405. clone_opt = VIM::evaluate('s:clone_opt')
  1406. progress = VIM::evaluate('s:progress_opt(1)')
  1407. nthr.times do
  1408. mtx.synchronize do
  1409. threads << Thread.new {
  1410. while pair = take1.call
  1411. name = pair.first
  1412. dir, uri, branch, tag = pair.last.values_at *%w[dir uri branch tag]
  1413. checkout = esc(tag ? tag : branch)
  1414. merge = esc(tag ? tag : "origin/#{branch}")
  1415. subm = "git submodule update --init --recursive 2>&1"
  1416. exists = File.directory? dir
  1417. ok, result =
  1418. if exists
  1419. dir = iswin ? dir : esc(dir)
  1420. ret, data = bt.call "#{cd} #{dir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil, nil
  1421. current_uri = data.lines.to_a.last
  1422. if !ret
  1423. if data =~ /^Interrupted|^Timeout/
  1424. [false, data]
  1425. else
  1426. [false, [data.chomp, "PlugClean required."].join($/)]
  1427. end
  1428. elsif current_uri.sub(/git::?@/, '') != uri.sub(/git::?@/, '')
  1429. [false, ["Invalid URI: #{current_uri}",
  1430. "Expected: #{uri}",
  1431. "PlugClean required."].join($/)]
  1432. else
  1433. if pull
  1434. log.call name, 'Updating ...', :update
  1435. fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : ''
  1436. 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
  1437. else
  1438. [true, skip]
  1439. end
  1440. end
  1441. else
  1442. d = esc dir.sub(%r{[\\/]+$}, '')
  1443. log.call name, 'Installing ...', :install
  1444. bt.call "git clone #{clone_opt unless tag} #{progress} --recursive #{uri} -b #{checkout} #{d} 2>&1", name, :install, proc {
  1445. FileUtils.rm_rf dir
  1446. }
  1447. end
  1448. mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
  1449. log.call name, result, ok
  1450. end
  1451. } if running
  1452. end
  1453. end
  1454. threads.each { |t| t.join rescue nil }
  1455. logh.call
  1456. refresh.kill if refresh
  1457. watcher.kill
  1458. EOF
  1459. endfunction
  1460. function! s:shellesc(arg)
  1461. return '"'.escape(a:arg, '"').'"'
  1462. endfunction
  1463. function! s:glob_dir(path)
  1464. return map(filter(s:lines(globpath(a:path, '**')), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  1465. endfunction
  1466. function! s:progress_bar(line, bar, total)
  1467. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  1468. endfunction
  1469. function! s:compare_git_uri(a, b)
  1470. let a = substitute(a:a, 'git:\{1,2}@', '', '')
  1471. let b = substitute(a:b, 'git:\{1,2}@', '', '')
  1472. return a ==# b
  1473. endfunction
  1474. function! s:format_message(bullet, name, message)
  1475. if a:bullet != 'x'
  1476. return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
  1477. else
  1478. let lines = map(s:lines(a:message), '" ".v:val')
  1479. return extend([printf('x %s:', a:name)], lines)
  1480. endif
  1481. endfunction
  1482. function! s:with_cd(cmd, dir)
  1483. return printf('cd%s %s && %s', s:is_win ? ' /d' : '', s:shellesc(a:dir), a:cmd)
  1484. endfunction
  1485. function! s:system(cmd, ...)
  1486. try
  1487. let [sh, shrd] = [&shell, &shellredir]
  1488. if !s:is_win
  1489. set shell=sh shellredir=>%s\ 2>&1
  1490. endif
  1491. let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
  1492. return system(s:is_win ? '('.cmd.')' : cmd)
  1493. finally
  1494. let [&shell, &shellredir] = [sh, shrd]
  1495. endtry
  1496. endfunction
  1497. function! s:system_chomp(...)
  1498. let ret = call('s:system', a:000)
  1499. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  1500. endfunction
  1501. function! s:git_valid(spec, check_branch)
  1502. let ret = 1
  1503. let msg = 'OK'
  1504. if isdirectory(a:spec.dir)
  1505. let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url', a:spec.dir))
  1506. let remote = result[-1]
  1507. if v:shell_error
  1508. let msg = join([remote, 'PlugClean required.'], "\n")
  1509. let ret = 0
  1510. elseif !s:compare_git_uri(remote, a:spec.uri)
  1511. let msg = join(['Invalid URI: '.remote,
  1512. \ 'Expected: '.a:spec.uri,
  1513. \ 'PlugClean required.'], "\n")
  1514. let ret = 0
  1515. elseif a:check_branch
  1516. let branch = result[0]
  1517. " Check tag
  1518. if has_key(a:spec, 'tag')
  1519. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
  1520. if a:spec.tag !=# tag
  1521. let msg = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.',
  1522. \ (empty(tag) ? 'N/A' : tag), a:spec.tag)
  1523. let ret = 0
  1524. endif
  1525. " Check branch
  1526. elseif a:spec.branch !=# branch
  1527. let msg = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.',
  1528. \ branch, a:spec.branch)
  1529. let ret = 0
  1530. endif
  1531. endif
  1532. else
  1533. let msg = 'Not found'
  1534. let ret = 0
  1535. endif
  1536. return [ret, msg]
  1537. endfunction
  1538. function! s:rm_rf(dir)
  1539. if isdirectory(a:dir)
  1540. call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(a:dir))
  1541. endif
  1542. endfunction
  1543. function! s:clean(force)
  1544. call s:prepare()
  1545. call append(0, 'Searching for unused plugins in '.g:plug_home)
  1546. call append(1, '')
  1547. " List of valid directories
  1548. let dirs = []
  1549. let [cnt, total] = [0, len(g:plugs)]
  1550. for [name, spec] in items(g:plugs)
  1551. if !s:is_managed(name) || s:git_valid(spec, 0)[0]
  1552. call add(dirs, spec.dir)
  1553. endif
  1554. let cnt += 1
  1555. call s:progress_bar(2, repeat('=', cnt), total)
  1556. normal! 2G
  1557. redraw
  1558. endfor
  1559. let allowed = {}
  1560. for dir in dirs
  1561. let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
  1562. let allowed[dir] = 1
  1563. for child in s:glob_dir(dir)
  1564. let allowed[child] = 1
  1565. endfor
  1566. endfor
  1567. let todo = []
  1568. let found = sort(s:glob_dir(g:plug_home))
  1569. while !empty(found)
  1570. let f = remove(found, 0)
  1571. if !has_key(allowed, f) && isdirectory(f)
  1572. call add(todo, f)
  1573. call append(line('$'), '- ' . f)
  1574. let found = filter(found, 'stridx(v:val, f) != 0')
  1575. end
  1576. endwhile
  1577. normal! G
  1578. redraw
  1579. if empty(todo)
  1580. call append(line('$'), 'Already clean.')
  1581. else
  1582. call inputsave()
  1583. let yes = a:force || (input('Proceed? (y/N) ') =~? '^y')
  1584. call inputrestore()
  1585. if yes
  1586. for dir in todo
  1587. call s:rm_rf(dir)
  1588. endfor
  1589. call append(line('$'), 'Removed.')
  1590. else
  1591. call append(line('$'), 'Cancelled.')
  1592. endif
  1593. endif
  1594. normal! G
  1595. endfunction
  1596. function! s:upgrade()
  1597. echo 'Downloading the latest version of vim-plug'
  1598. redraw
  1599. let tmp = tempname()
  1600. let new = tmp . '/plug.vim'
  1601. try
  1602. let out = s:system(printf('git clone --depth 1 %s %s', s:plug_src, tmp))
  1603. if v:shell_error
  1604. return s:err('Error upgrading vim-plug: '. out)
  1605. endif
  1606. if readfile(s:me) ==# readfile(new)
  1607. echo 'vim-plug is already up-to-date'
  1608. return 0
  1609. else
  1610. call rename(s:me, s:me . '.old')
  1611. call rename(new, s:me)
  1612. unlet g:loaded_plug
  1613. echo 'vim-plug has been upgraded'
  1614. return 1
  1615. endif
  1616. finally
  1617. silent! call s:rm_rf(tmp)
  1618. endtry
  1619. endfunction
  1620. function! s:upgrade_specs()
  1621. for spec in values(g:plugs)
  1622. let spec.frozen = get(spec, 'frozen', 0)
  1623. endfor
  1624. endfunction
  1625. function! s:status()
  1626. call s:prepare()
  1627. call append(0, 'Checking plugins')
  1628. call append(1, '')
  1629. let ecnt = 0
  1630. let unloaded = 0
  1631. let [cnt, total] = [0, len(g:plugs)]
  1632. for [name, spec] in items(g:plugs)
  1633. if has_key(spec, 'uri')
  1634. if isdirectory(spec.dir)
  1635. let [valid, msg] = s:git_valid(spec, 1)
  1636. else
  1637. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  1638. endif
  1639. else
  1640. if isdirectory(spec.dir)
  1641. let [valid, msg] = [1, 'OK']
  1642. else
  1643. let [valid, msg] = [0, 'Not found.']
  1644. endif
  1645. endif
  1646. let cnt += 1
  1647. let ecnt += !valid
  1648. " `s:loaded` entry can be missing if PlugUpgraded
  1649. if valid && get(s:loaded, name, -1) == 0
  1650. let unloaded = 1
  1651. let msg .= ' (not loaded)'
  1652. endif
  1653. call s:progress_bar(2, repeat('=', cnt), total)
  1654. call append(3, s:format_message(valid ? '-' : 'x', name, msg))
  1655. normal! 2G
  1656. redraw
  1657. endfor
  1658. call setline(1, 'Finished. '.ecnt.' error(s).')
  1659. normal! gg
  1660. setlocal nomodifiable
  1661. if unloaded
  1662. echo "Press 'L' on each line to load plugin, or 'U' to update"
  1663. nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1664. xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1665. end
  1666. endfunction
  1667. function! s:extract_name(str, prefix, suffix)
  1668. return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
  1669. endfunction
  1670. function! s:status_load(lnum)
  1671. let line = getline(a:lnum)
  1672. let name = s:extract_name(line, '-', '(not loaded)')
  1673. if !empty(name)
  1674. call plug#load(name)
  1675. setlocal modifiable
  1676. call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
  1677. setlocal nomodifiable
  1678. endif
  1679. endfunction
  1680. function! s:status_update() range
  1681. let lines = getline(a:firstline, a:lastline)
  1682. let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
  1683. if !empty(names)
  1684. echo
  1685. execute 'PlugUpdate' join(names)
  1686. endif
  1687. endfunction
  1688. function! s:is_preview_window_open()
  1689. silent! wincmd P
  1690. if &previewwindow
  1691. wincmd p
  1692. return 1
  1693. endif
  1694. return 0
  1695. endfunction
  1696. function! s:find_name(lnum)
  1697. for lnum in reverse(range(1, a:lnum))
  1698. let line = getline(lnum)
  1699. if empty(line)
  1700. return ''
  1701. endif
  1702. let name = s:extract_name(line, '-', '')
  1703. if !empty(name)
  1704. return name
  1705. endif
  1706. endfor
  1707. return ''
  1708. endfunction
  1709. function! s:preview_commit()
  1710. if b:plug_preview < 0
  1711. let b:plug_preview = !s:is_preview_window_open()
  1712. endif
  1713. let sha = matchstr(getline('.'), '\(^ \)\@<=[0-9a-z]\{7}')
  1714. if empty(sha)
  1715. return
  1716. endif
  1717. let name = s:find_name(line('.'))
  1718. if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
  1719. return
  1720. endif
  1721. execute 'pedit' sha
  1722. wincmd P
  1723. setlocal filetype=git buftype=nofile nobuflisted modifiable
  1724. execute 'silent read !cd' s:shellesc(g:plugs[name].dir) '&& git show --pretty=medium' sha
  1725. normal! gg"_dd
  1726. setlocal nomodifiable
  1727. nnoremap <silent> <buffer> q :q<cr>
  1728. wincmd p
  1729. endfunction
  1730. function! s:section(flags)
  1731. call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
  1732. endfunction
  1733. function! s:diff()
  1734. call s:prepare()
  1735. call append(0, 'Collecting updated changes ...')
  1736. normal! gg
  1737. redraw
  1738. let cnt = 0
  1739. for [k, v] in items(g:plugs)
  1740. if !isdirectory(v.dir) || !s:is_managed(k)
  1741. continue
  1742. endif
  1743. let diff = s:system_chomp('git log --pretty=format:"%h %s (%cr)" "HEAD...HEAD@{1}"', v.dir)
  1744. if !empty(diff)
  1745. call append(1, '')
  1746. call append(2, '- '.k.':')
  1747. call append(3, map(s:lines(diff), '" ". v:val'))
  1748. let cnt += 1
  1749. normal! gg
  1750. redraw
  1751. endif
  1752. endfor
  1753. call setline(1, cnt == 0 ? 'No updates.' : 'Last update:')
  1754. nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
  1755. nnoremap <silent> <buffer> o :silent! call <SID>preview_commit()<cr>
  1756. nnoremap <silent> <buffer> X :call <SID>revert()<cr>
  1757. normal! gg
  1758. setlocal nomodifiable
  1759. if cnt > 0
  1760. echo "Press 'X' on each block to revert the update"
  1761. endif
  1762. endfunction
  1763. function! s:revert()
  1764. let name = s:find_name(line('.'))
  1765. if empty(name) || !has_key(g:plugs, name) ||
  1766. \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
  1767. return
  1768. endif
  1769. call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir)
  1770. setlocal modifiable
  1771. normal! "_dap
  1772. setlocal nomodifiable
  1773. echo 'Reverted.'
  1774. endfunction
  1775. function! s:snapshot(...) abort
  1776. let home = get(s:, 'plug_home_org', g:plug_home)
  1777. let [type, var, header] = s:is_win ?
  1778. \ ['dosbatch', '%PLUG_HOME%',
  1779. \ ['@echo off', ':: Generated by vim-plug', ':: '.strftime("%c"), '',
  1780. \ ':: Make sure to PlugUpdate first', '', 'set PLUG_HOME='.home]] :
  1781. \ ['sh', '$PLUG_HOME',
  1782. \ ['#!/bin/sh', '# Generated by vim-plug', '# '.strftime("%c"), '',
  1783. \ 'vim +PlugUpdate +qa', '', 'PLUG_HOME='.s:esc(home)]]
  1784. call s:prepare()
  1785. execute 'setf' type
  1786. call append(0, header)
  1787. call append('$', '')
  1788. 1
  1789. redraw
  1790. let dirs = sort(map(values(filter(copy(g:plugs),
  1791. \'has_key(v:val, "uri") && isdirectory(v:val.dir)')), 'v:val.dir'))
  1792. let anchor = line('$') - 1
  1793. for dir in reverse(dirs)
  1794. let sha = s:system_chomp('git rev-parse --short HEAD', dir)
  1795. if !empty(sha)
  1796. call append(anchor, printf('cd %s && git reset --hard %s',
  1797. \ substitute(dir, '^\V'.escape(g:plug_home, '\'), var, ''), sha))
  1798. redraw
  1799. endif
  1800. endfor
  1801. if a:0 > 0
  1802. let fn = expand(a:1)
  1803. let fne = s:esc(fn)
  1804. call writefile(getline(1, '$'), fn)
  1805. if !s:is_win | call s:system('chmod +x ' . fne) | endif
  1806. echo 'Saved to '.a:1
  1807. silent execute 'e' fne
  1808. endif
  1809. endfunction
  1810. function! s:split_rtp()
  1811. return split(&rtp, '\\\@<!,')
  1812. endfunction
  1813. let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
  1814. let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
  1815. if exists('g:plugs')
  1816. let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
  1817. call s:upgrade_specs()
  1818. call s:define_commands()
  1819. endif
  1820. let &cpo = s:cpo_save
  1821. unlet s:cpo_save