plug.vim 61 KB

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