plug.vim 57 KB

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