plug.vim 61 KB

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