plug.vim 61 KB

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