plug.vim 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. " vim-plug: Vim plugin manager
  2. " ============================
  3. "
  4. " Download plug.vim and put it in ~/.vim/autoload
  5. "
  6. " mkdir -p ~/.vim/autoload
  7. " curl -fLo ~/.vim/autoload/plug.vim \
  8. " https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
  9. "
  10. " Edit your .vimrc
  11. "
  12. " call plug#begin('~/.vim/plugged')
  13. "
  14. " " Make sure you use single quotes
  15. " Plug 'junegunn/seoul256.vim'
  16. " Plug 'junegunn/vim-easy-align'
  17. "
  18. " " On-demand loading
  19. " Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
  20. " Plug 'tpope/vim-fireplace', { 'for': 'clojure' }
  21. "
  22. " " Using git URL
  23. " Plug 'https://github.com/junegunn/vim-github-dashboard.git'
  24. "
  25. " " Plugin options
  26. " Plug 'nsf/gocode', { 'tag': 'go.weekly.2012-03-13', 'rtp': 'vim' }
  27. "
  28. " " Plugin outside ~/.vim/plugged with post-update hook
  29. " Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': 'yes \| ./install' }
  30. "
  31. " " Unmanaged plugin (manually installed and updated)
  32. " Plug '~/my-prototype-plugin'
  33. "
  34. " call plug#end()
  35. "
  36. " Then reload .vimrc and :PlugInstall to install plugins.
  37. " Visit https://github.com/junegunn/vim-plug for more information.
  38. "
  39. "
  40. " Copyright (c) 2014 Junegunn Choi
  41. "
  42. " MIT License
  43. "
  44. " Permission is hereby granted, free of charge, to any person obtaining
  45. " a copy of this software and associated documentation files (the
  46. " "Software"), to deal in the Software without restriction, including
  47. " without limitation the rights to use, copy, modify, merge, publish,
  48. " distribute, sublicense, and/or sell copies of the Software, and to
  49. " permit persons to whom the Software is furnished to do so, subject to
  50. " the following conditions:
  51. "
  52. " The above copyright notice and this permission notice shall be
  53. " included in all copies or substantial portions of the Software.
  54. "
  55. " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  56. " EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  57. " MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  58. " NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  59. " LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  60. " OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  61. " WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  62. if exists('g:loaded_plug')
  63. finish
  64. endif
  65. let g:loaded_plug = 1
  66. let s:cpo_save = &cpo
  67. set cpo&vim
  68. let s:plug_src = 'https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
  69. let s:plug_tab = get(s:, 'plug_tab', -1)
  70. let s:plug_buf = get(s:, 'plug_buf', -1)
  71. let s:mac_gui = has('gui_macvim') && has('gui_running')
  72. let s:is_win = has('win32') || has('win64')
  73. let s:ruby = has('ruby') && (v:version >= 703 || v:version == 702 && has('patch374'))
  74. let s:nvim = has('nvim') && !s:is_win
  75. let s:me = resolve(expand('<sfile>:p'))
  76. let s:base_spec = { 'branch': 'master', 'frozen': 0 }
  77. let s:TYPE = {
  78. \ 'string': type(''),
  79. \ 'list': type([]),
  80. \ 'dict': type({}),
  81. \ 'funcref': type(function('call'))
  82. \ }
  83. let s:loaded = get(s:, 'loaded', {})
  84. let s:triggers = get(s:, 'triggers', {})
  85. function! plug#begin(...)
  86. if a:0 > 0
  87. let s:plug_home_org = a:1
  88. let home = s:path(fnamemodify(expand(a:1), ':p'))
  89. elseif exists('g:plug_home')
  90. let home = s:path(g:plug_home)
  91. elseif !empty(&rtp)
  92. let home = s:path(split(&rtp, ',')[0]) . '/plugged'
  93. else
  94. return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.')
  95. endif
  96. let g:plug_home = home
  97. let g:plugs = {}
  98. let g:plugs_order = []
  99. let s:triggers = {}
  100. call s:define_commands()
  101. return 1
  102. endfunction
  103. function! s:define_commands()
  104. command! -nargs=+ -bar Plug call s:add(<args>)
  105. if !executable('git')
  106. return s:err('`git` executable not found. vim-plug requires git.')
  107. endif
  108. command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install('<bang>' == '!', [<f-args>])
  109. command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update('<bang>' == '!', [<f-args>])
  110. command! -nargs=0 -bar -bang PlugClean call s:clean('<bang>' == '!')
  111. command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:esc(s:me) | endif
  112. command! -nargs=0 -bar PlugStatus call s:status()
  113. command! -nargs=0 -bar PlugDiff call s:diff()
  114. command! -nargs=? -bar PlugSnapshot call s:snapshot(<f-args>)
  115. endfunction
  116. function! s:to_a(v)
  117. return type(a:v) == s:TYPE.list ? a:v : [a:v]
  118. endfunction
  119. function! s:to_s(v)
  120. return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n"
  121. endfunction
  122. function! s:source(from, ...)
  123. for pattern in a:000
  124. for vim in s:lines(globpath(a:from, pattern))
  125. execute 'source' s:esc(vim)
  126. endfor
  127. endfor
  128. endfunction
  129. function! s:assoc(dict, key, val)
  130. let a:dict[a:key] = add(get(a:dict, a:key, []), a:val)
  131. endfunction
  132. function! plug#end()
  133. if !exists('g:plugs')
  134. return s:err('Call plug#begin() first')
  135. endif
  136. if exists('#PlugLOD')
  137. augroup PlugLOD
  138. autocmd!
  139. augroup END
  140. augroup! PlugLOD
  141. endif
  142. let lod = { 'ft': {}, 'map': {}, 'cmd': {} }
  143. filetype off
  144. for name in g:plugs_order
  145. let plug = g:plugs[name]
  146. if get(s:loaded, name, 0) || !has_key(plug, 'on') && !has_key(plug, 'for')
  147. let s:loaded[name] = 1
  148. continue
  149. endif
  150. if has_key(plug, 'on')
  151. let s:triggers[name] = { 'map': [], 'cmd': [] }
  152. for cmd in s:to_a(plug.on)
  153. if cmd =~ '^<Plug>.\+'
  154. if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i'))
  155. call s:assoc(lod.map, cmd, name)
  156. endif
  157. call add(s:triggers[name].map, cmd)
  158. elseif cmd =~ '^[A-Z]'
  159. if exists(':'.cmd) != 2
  160. call s:assoc(lod.cmd, cmd, name)
  161. endif
  162. call add(s:triggers[name].cmd, cmd)
  163. endif
  164. endfor
  165. endif
  166. if has_key(plug, 'for')
  167. let types = s:to_a(plug.for)
  168. if !empty(types)
  169. call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim')
  170. endif
  171. for type in types
  172. call s:assoc(lod.ft, type, name)
  173. endfor
  174. endif
  175. endfor
  176. for [cmd, names] in items(lod.cmd)
  177. execute printf(
  178. \ 'command! -nargs=* -range -bang %s call s:lod_cmd(%s, "<bang>", <line1>, <line2>, <q-args>, %s)',
  179. \ cmd, string(cmd), string(names))
  180. endfor
  181. for [map, names] in items(lod.map)
  182. for [mode, map_prefix, key_prefix] in
  183. \ [['i', '<C-O>', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']]
  184. execute printf(
  185. \ '%snoremap <silent> %s %s:<C-U>call <SID>lod_map(%s, %s, "%s")<CR>',
  186. \ mode, map, map_prefix, string(map), string(names), key_prefix)
  187. endfor
  188. endfor
  189. for [ft, names] in items(lod.ft)
  190. augroup PlugLOD
  191. execute printf('autocmd FileType %s call <SID>lod_ft(%s, %s)',
  192. \ ft, string(ft), string(names))
  193. augroup END
  194. endfor
  195. call s:reorg_rtp()
  196. filetype plugin indent on
  197. if has('vim_starting')
  198. syntax enable
  199. else
  200. call s:reload()
  201. endif
  202. endfunction
  203. function! s:loaded_names()
  204. return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)')
  205. endfunction
  206. function! s:reload()
  207. for name in s:loaded_names()
  208. call s:source(s:rtp(g:plugs[name]), 'plugin/**/*.vim', 'after/plugin/**/*.vim')
  209. endfor
  210. endfunction
  211. function! s:trim(str)
  212. return substitute(a:str, '[\/]\+$', '', '')
  213. endfunction
  214. function! s:git_version_requirement(...)
  215. let s:git_version = get(s:, 'git_version',
  216. \ map(split(split(s:system('git --version'))[-1], '\.'), 'str2nr(v:val)'))
  217. for idx in range(0, a:0 - 1)
  218. let v = get(s:git_version, idx, 0)
  219. if v < a:000[idx] | return 0
  220. elseif v > a:000[idx] | return 1
  221. endif
  222. endfor
  223. return 1
  224. endfunction
  225. function! s:progress_opt(base)
  226. return a:base && !s:is_win &&
  227. \ s:git_version_requirement(1, 7, 1) ? '--progress' : ''
  228. endfunction
  229. if s:is_win
  230. function! s:rtp(spec)
  231. return s:path(a:spec.dir . get(a:spec, 'rtp', ''))
  232. endfunction
  233. function! s:path(path)
  234. return s:trim(substitute(a:path, '/', '\', 'g'))
  235. endfunction
  236. function! s:dirpath(path)
  237. return s:path(a:path) . '\'
  238. endfunction
  239. function! s:is_local_plug(repo)
  240. return a:repo =~? '^[a-z]:'
  241. endfunction
  242. else
  243. function! s:rtp(spec)
  244. return s:dirpath(a:spec.dir . get(a:spec, 'rtp', ''))
  245. endfunction
  246. function! s:path(path)
  247. return s:trim(a:path)
  248. endfunction
  249. function! s:dirpath(path)
  250. return substitute(a:path, '[/\\]*$', '/', '')
  251. endfunction
  252. function! s:is_local_plug(repo)
  253. return a:repo[0] =~ '[/$~]'
  254. endfunction
  255. endif
  256. function! s:err(msg)
  257. echohl ErrorMsg
  258. echom a:msg
  259. echohl None
  260. return 0
  261. endfunction
  262. function! s:esc(path)
  263. return escape(a:path, ' ')
  264. endfunction
  265. function! s:escrtp(path)
  266. return escape(a:path, ' ,')
  267. endfunction
  268. function! s:remove_rtp()
  269. for name in s:loaded_names()
  270. let rtp = s:rtp(g:plugs[name])
  271. execute 'set rtp-='.s:escrtp(rtp)
  272. let after = globpath(rtp, 'after')
  273. if isdirectory(after)
  274. execute 'set rtp-='.s:escrtp(after)
  275. endif
  276. endfor
  277. endfunction
  278. function! s:reorg_rtp()
  279. if !empty(s:first_rtp)
  280. execute 'set rtp-='.s:first_rtp
  281. execute 'set rtp-='.s:last_rtp
  282. endif
  283. " &rtp is modified from outside
  284. if exists('s:prtp') && s:prtp !=# &rtp
  285. call s:remove_rtp()
  286. unlet! s:middle
  287. endif
  288. let s:middle = get(s:, 'middle', &rtp)
  289. let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])')
  290. let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), 'isdirectory(v:val)')
  291. let rtp = join(map(rtps, 'escape(v:val, ",")'), ',')
  292. \ . ','.s:middle.','
  293. \ . join(map(afters, 'escape(v:val, ",")'), ',')
  294. let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g')
  295. let s:prtp = &rtp
  296. if !empty(s:first_rtp)
  297. execute 'set rtp^='.s:first_rtp
  298. execute 'set rtp+='.s:last_rtp
  299. endif
  300. endfunction
  301. function! plug#load(...)
  302. if a:0 == 0
  303. return s:err('Argument missing: plugin name(s) required')
  304. endif
  305. if !exists('g:plugs')
  306. return s:err('plug#begin was not called')
  307. endif
  308. let unknowns = filter(copy(a:000), '!has_key(g:plugs, v:val)')
  309. if !empty(unknowns)
  310. let s = len(unknowns) > 1 ? 's' : ''
  311. return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', ')))
  312. end
  313. for name in a:000
  314. call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  315. endfor
  316. doautocmd BufRead
  317. return 1
  318. endfunction
  319. function! s:remove_triggers(name)
  320. if !has_key(s:triggers, a:name)
  321. return
  322. endif
  323. for cmd in s:triggers[a:name].cmd
  324. execute 'silent! delc' cmd
  325. endfor
  326. for map in s:triggers[a:name].map
  327. execute 'silent! unmap' map
  328. execute 'silent! iunmap' map
  329. endfor
  330. call remove(s:triggers, a:name)
  331. endfunction
  332. function! s:lod(names, types)
  333. for name in a:names
  334. call s:remove_triggers(name)
  335. let s:loaded[name] = 1
  336. endfor
  337. call s:reorg_rtp()
  338. for name in a:names
  339. let rtp = s:rtp(g:plugs[name])
  340. for dir in a:types
  341. call s:source(rtp, dir.'/**/*.vim')
  342. endfor
  343. endfor
  344. endfunction
  345. function! s:lod_ft(pat, names)
  346. call s:lod(a:names, ['plugin', 'after/plugin'])
  347. execute 'autocmd! PlugLOD FileType' a:pat
  348. doautocmd filetypeplugin FileType
  349. doautocmd filetypeindent FileType
  350. endfunction
  351. function! s:lod_cmd(cmd, bang, l1, l2, args, names)
  352. call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  353. execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args)
  354. endfunction
  355. function! s:lod_map(map, names, prefix)
  356. call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
  357. let extra = ''
  358. while 1
  359. let c = getchar(0)
  360. if c == 0
  361. break
  362. endif
  363. let extra .= nr2char(c)
  364. endwhile
  365. call feedkeys(a:prefix . substitute(a:map, '^<Plug>', "\<Plug>", '') . extra)
  366. endfunction
  367. function! s:add(repo, ...)
  368. if a:0 > 1
  369. return s:err('Invalid number of arguments (1..2)')
  370. endif
  371. try
  372. let repo = s:trim(a:repo)
  373. let name = fnamemodify(repo, ':t:s?\.git$??')
  374. let spec = extend(s:infer_properties(name, repo),
  375. \ a:0 == 1 ? s:parse_options(a:1) : s:base_spec)
  376. let g:plugs[name] = spec
  377. let g:plugs_order += [name]
  378. let s:loaded[name] = 0
  379. catch
  380. return s:err(v:exception)
  381. endtry
  382. endfunction
  383. function! s:parse_options(arg)
  384. let opts = copy(s:base_spec)
  385. let type = type(a:arg)
  386. if type == s:TYPE.string
  387. let opts.branch = a:arg
  388. elseif type == s:TYPE.dict
  389. call extend(opts, a:arg)
  390. if has_key(opts, 'tag')
  391. let opts.branch = remove(opts, 'tag')
  392. endif
  393. if has_key(opts, 'dir')
  394. let opts.dir = s:dirpath(expand(opts.dir))
  395. endif
  396. else
  397. throw 'Invalid argument type (expected: string or dictionary)'
  398. endif
  399. return opts
  400. endfunction
  401. function! s:infer_properties(name, repo)
  402. let repo = a:repo
  403. if s:is_local_plug(repo)
  404. return { 'dir': s:dirpath(expand(repo)) }
  405. else
  406. if repo =~ ':'
  407. let uri = repo
  408. else
  409. if repo !~ '/'
  410. let repo = 'vim-scripts/'. repo
  411. endif
  412. let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git')
  413. let uri = printf(fmt, repo)
  414. endif
  415. let dir = s:dirpath( fnamemodify(join([g:plug_home, a:name], '/'), ':p') )
  416. return { 'dir': dir, 'uri': uri }
  417. endif
  418. endfunction
  419. function! s:install(force, names)
  420. call s:update_impl(0, a:force, a:names)
  421. endfunction
  422. function! s:update(force, names)
  423. call s:update_impl(1, a:force, a:names)
  424. endfunction
  425. function! plug#helptags()
  426. if !exists('g:plugs')
  427. return s:err('plug#begin was not called')
  428. endif
  429. for spec in values(g:plugs)
  430. let docd = join([spec.dir, 'doc'], '/')
  431. if isdirectory(docd)
  432. silent! execute 'helptags' s:esc(docd)
  433. endif
  434. endfor
  435. return 1
  436. endfunction
  437. function! s:syntax()
  438. syntax clear
  439. syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber
  440. syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX
  441. syn match plugNumber /[0-9]\+[0-9.]*/ contained
  442. syn match plugBracket /[[\]]/ contained
  443. syn match plugX /x/ contained
  444. syn match plugDash /^-/
  445. syn match plugPlus /^+/
  446. syn match plugStar /^*/
  447. syn match plugMessage /\(^- \)\@<=.*/
  448. syn match plugName /\(^- \)\@<=[^ ]*:/
  449. syn match plugInstall /\(^+ \)\@<=[^:]*/
  450. syn match plugUpdate /\(^* \)\@<=[^:]*/
  451. syn match plugCommit /^ [0-9a-z]\{7} .*/ contains=plugRelDate,plugSha
  452. syn match plugSha /\(^ \)\@<=[0-9a-z]\{7}/ contained
  453. syn match plugRelDate /([^)]*)$/ contained
  454. syn match plugNotLoaded /(not loaded)$/
  455. syn match plugError /^x.*/
  456. syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean
  457. hi def link plug1 Title
  458. hi def link plug2 Repeat
  459. hi def link plugX Exception
  460. hi def link plugBracket Structure
  461. hi def link plugNumber Number
  462. hi def link plugDash Special
  463. hi def link plugPlus Constant
  464. hi def link plugStar Boolean
  465. hi def link plugMessage Function
  466. hi def link plugName Label
  467. hi def link plugInstall Function
  468. hi def link plugUpdate Type
  469. hi def link plugError Error
  470. hi def link plugRelDate Comment
  471. hi def link plugSha Identifier
  472. hi def link plugNotLoaded Comment
  473. endfunction
  474. function! s:lpad(str, len)
  475. return a:str . repeat(' ', a:len - len(a:str))
  476. endfunction
  477. function! s:lines(msg)
  478. return split(a:msg, "[\r\n]")
  479. endfunction
  480. function! s:lastline(msg)
  481. return get(s:lines(a:msg), -1, '')
  482. endfunction
  483. function! s:new_window()
  484. execute get(g:, 'plug_window', 'vertical topleft new')
  485. endfunction
  486. function! s:plug_window_exists()
  487. let buflist = tabpagebuflist(s:plug_tab)
  488. return !empty(buflist) && index(buflist, s:plug_buf) >= 0
  489. endfunction
  490. function! s:switch_in()
  491. if !s:plug_window_exists()
  492. return 0
  493. endif
  494. if winbufnr(0) != s:plug_buf
  495. let s:pos = [tabpagenr(), winnr(), winsaveview()]
  496. execute 'normal!' s:plug_tab.'gt'
  497. let winnr = bufwinnr(s:plug_buf)
  498. execute winnr.'wincmd w'
  499. call add(s:pos, winsaveview())
  500. else
  501. let s:pos = [winsaveview()]
  502. endif
  503. setlocal modifiable
  504. return 1
  505. endfunction
  506. function! s:switch_out(...)
  507. call winrestview(s:pos[-1])
  508. setlocal nomodifiable
  509. if a:0 > 0
  510. execute a:1
  511. endif
  512. if len(s:pos) > 1
  513. execute 'normal!' s:pos[0].'gt'
  514. execute s:pos[1] 'wincmd w'
  515. call winrestview(s:pos[2])
  516. endif
  517. endfunction
  518. function! s:prepare()
  519. call s:job_abort()
  520. if s:switch_in()
  521. silent %d _
  522. else
  523. call s:new_window()
  524. nnoremap <silent> <buffer> q :if b:plug_preview==1<bar>pc<bar>endif<bar>echo<bar>q<cr>
  525. nnoremap <silent> <buffer> R :silent! call <SID>retry()<cr>
  526. nnoremap <silent> <buffer> D :PlugDiff<cr>
  527. nnoremap <silent> <buffer> S :PlugStatus<cr>
  528. nnoremap <silent> <buffer> U :call <SID>status_update()<cr>
  529. xnoremap <silent> <buffer> U :call <SID>status_update()<cr>
  530. nnoremap <silent> <buffer> ]] :silent! call <SID>section('')<cr>
  531. nnoremap <silent> <buffer> [[ :silent! call <SID>section('b')<cr>
  532. let b:plug_preview = -1
  533. let s:plug_tab = tabpagenr()
  534. let s:plug_buf = winbufnr(0)
  535. call s:assign_name()
  536. endif
  537. silent! unmap <buffer> <cr>
  538. silent! unmap <buffer> L
  539. silent! unmap <buffer> X
  540. setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap cursorline modifiable
  541. setf vim-plug
  542. call s:syntax()
  543. endfunction
  544. function! s:assign_name()
  545. " Assign buffer name
  546. let prefix = '[Plugins]'
  547. let name = prefix
  548. let idx = 2
  549. while bufexists(name)
  550. let name = printf('%s (%s)', prefix, idx)
  551. let idx = idx + 1
  552. endwhile
  553. silent! execute 'f' fnameescape(name)
  554. endfunction
  555. function! s:do(pull, force, todo)
  556. for [name, spec] in items(a:todo)
  557. if !isdirectory(spec.dir)
  558. continue
  559. endif
  560. let installed = has_key(s:update.new, name)
  561. let updated = installed ? 0 :
  562. \ (a:pull && !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', spec.dir)))
  563. if a:force || installed || updated
  564. execute 'cd' s:esc(spec.dir)
  565. call append(3, '- Post-update hook for '. name .' ... ')
  566. let type = type(spec.do)
  567. if type == s:TYPE.string
  568. try
  569. " FIXME: Escaping is incomplete. We could use shellescape with eval,
  570. " but it won't work on Windows.
  571. let g:_plug_do = '!'.escape(spec.do, '#!%')
  572. execute "normal! :execute g:_plug_do\<cr>\<cr>"
  573. finally
  574. let result = v:shell_error ? ('Exit status: '.v:shell_error) : 'Done!'
  575. unlet g:_plug_do
  576. endtry
  577. elseif type == s:TYPE.funcref
  578. try
  579. let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
  580. call spec.do({ 'name': name, 'status': status, 'force': a:force })
  581. let result = 'Done!'
  582. catch
  583. let result = 'Error: ' . v:exception
  584. endtry
  585. else
  586. let result = 'Error: Invalid type!'
  587. endif
  588. call setline(4, getline(4) . result)
  589. cd -
  590. endif
  591. endfor
  592. endfunction
  593. function! s:finish(pull)
  594. let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
  595. if new_frozen
  596. let s = new_frozen > 1 ? 's' : ''
  597. call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
  598. endif
  599. call append(3, '- Finishing ... ')
  600. redraw
  601. call plug#helptags()
  602. call plug#end()
  603. call setline(4, getline(4) . 'Done!')
  604. redraw
  605. let msgs = []
  606. if !empty(s:update.errors)
  607. call add(msgs, "Press 'R' to retry.")
  608. endif
  609. if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
  610. \ "v:val =~ '^- ' && stridx(v:val, 'Already up-to-date') < 0"))
  611. call add(msgs, "Press 'D' to see the updated changes.")
  612. endif
  613. echo join(msgs, ' ')
  614. endfunction
  615. function! s:retry()
  616. if empty(s:update.errors)
  617. return
  618. endif
  619. call s:update_impl(s:update.pull, s:update.force,
  620. \ extend(copy(s:update.errors), [s:update.threads]))
  621. endfunction
  622. function! s:is_managed(name)
  623. return has_key(g:plugs[a:name], 'uri')
  624. endfunction
  625. function! s:names(...)
  626. return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
  627. endfunction
  628. function! s:update_impl(pull, force, args) abort
  629. let args = copy(a:args)
  630. let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
  631. \ remove(args, -1) : get(g:, 'plug_threads', 16)
  632. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  633. let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
  634. \ filter(managed, 'index(args, v:key) >= 0')
  635. if empty(todo)
  636. echohl WarningMsg
  637. echo 'No plugin to '. (a:pull ? 'update' : 'install') . '.'
  638. echohl None
  639. return
  640. endif
  641. if !s:is_win && s:git_version_requirement(2, 3)
  642. let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : ''
  643. let $GIT_TERMINAL_PROMPT = 0
  644. for plug in values(todo)
  645. let plug.uri = substitute(plug.uri,
  646. \ '^https://git::@github\.com', 'https://github.com', '')
  647. endfor
  648. endif
  649. if !isdirectory(g:plug_home)
  650. try
  651. call mkdir(g:plug_home, 'p')
  652. catch
  653. return s:err(printf('Invalid plug directory: %s. '.
  654. \ 'Try to call plug#begin with a valid directory', g:plug_home))
  655. endtry
  656. endif
  657. let s:update = {
  658. \ 'start': reltime(),
  659. \ 'all': todo,
  660. \ 'todo': copy(todo),
  661. \ 'errors': [],
  662. \ 'pull': a:pull,
  663. \ 'force': a:force,
  664. \ 'new': {},
  665. \ 'threads': (s:ruby || s:nvim) ? min([len(todo), threads]) : 1,
  666. \ 'bar': '',
  667. \ 'fin': 0
  668. \ }
  669. call s:prepare()
  670. call append(0, ['', ''])
  671. normal! 2G
  672. if s:ruby && s:update.threads > 1
  673. try
  674. let imd = &imd
  675. if s:mac_gui
  676. set noimd
  677. endif
  678. call s:update_ruby()
  679. catch
  680. let lines = getline(4, '$')
  681. let printed = {}
  682. silent! 4,$d _
  683. for line in lines
  684. let name = s:extract_name(line, '.', '')
  685. if empty(name) || !has_key(printed, name)
  686. call append('$', line)
  687. if !empty(name)
  688. let printed[name] = 1
  689. if line[0] == 'x' && index(s:update.errors, name) < 0
  690. call add(s:update.errors, name)
  691. end
  692. endif
  693. endif
  694. endfor
  695. finally
  696. let &imd = imd
  697. call s:update_finish()
  698. endtry
  699. else
  700. call s:update_vim()
  701. endif
  702. endfunction
  703. function! s:update_finish()
  704. if exists('s:git_terminal_prompt')
  705. let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt
  706. endif
  707. if s:switch_in()
  708. call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'has_key(v:val, "do")'))
  709. call s:finish(s:update.pull)
  710. call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
  711. call s:switch_out('normal! gg')
  712. endif
  713. endfunction
  714. function! s:job_abort()
  715. if !s:nvim || !exists('s:jobs')
  716. return
  717. endif
  718. augroup PlugJobControl
  719. autocmd!
  720. augroup END
  721. for [name, j] in items(s:jobs)
  722. silent! call jobstop(j.jobid)
  723. if j.new
  724. call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir))
  725. endif
  726. endfor
  727. let s:jobs = {}
  728. endfunction
  729. function! s:job_handler(name) abort
  730. if !s:plug_window_exists() " plug window closed
  731. return s:job_abort()
  732. endif
  733. if !has_key(s:jobs, a:name)
  734. return
  735. endif
  736. let job = s:jobs[a:name]
  737. if v:job_data[1] == 'exit'
  738. let job.running = 0
  739. if s:lastline(job.result) ==# 'Error'
  740. let job.error = 1
  741. let job.result = substitute(job.result, "Error[\r\n]$", '', '')
  742. endif
  743. call s:reap(a:name)
  744. call s:tick()
  745. else
  746. let job.result .= s:to_s(v:job_data[2])
  747. " To reduce the number of buffer updates
  748. let job.tick = get(job, 'tick', -1) + 1
  749. if job.tick % len(s:jobs) == 0
  750. call s:log(job.new ? '+' : '*', a:name, job.result)
  751. endif
  752. endif
  753. endfunction
  754. function! s:spawn(name, cmd, opts)
  755. let job = { 'running': 1, 'new': get(a:opts, 'new', 0),
  756. \ 'error': 0, 'result': '' }
  757. let s:jobs[a:name] = job
  758. if s:nvim
  759. let x = jobstart(a:name, 'sh', ['-c',
  760. \ (has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd)
  761. \ . ' || echo Error'])
  762. if x > 0
  763. let job.jobid = x
  764. augroup PlugJobControl
  765. execute 'autocmd JobActivity' a:name printf('call s:job_handler(%s)', string(a:name))
  766. augroup END
  767. else
  768. let job.running = 0
  769. let job.error = 1
  770. let job.result = x < 0 ? 'sh is not executable' :
  771. \ 'Invalid arguments (or job table is full)'
  772. endif
  773. else
  774. let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd]
  775. let job.result = call('s:system', params)
  776. let job.error = v:shell_error != 0
  777. let job.running = 0
  778. endif
  779. endfunction
  780. function! s:reap(name)
  781. if s:nvim
  782. silent! execute 'autocmd! PlugJobControl JobActivity' a:name
  783. endif
  784. let job = s:jobs[a:name]
  785. if job.error
  786. call add(s:update.errors, a:name)
  787. elseif get(job, 'new', 0)
  788. let s:update.new[a:name] = 1
  789. endif
  790. let s:update.bar .= job.error ? 'x' : '='
  791. call s:log(job.error ? 'x' : '-', a:name, job.result)
  792. call s:bar()
  793. call remove(s:jobs, a:name)
  794. endfunction
  795. function! s:bar()
  796. if s:switch_in()
  797. let total = len(s:update.all)
  798. call setline(1, (s:update.pull ? 'Updating' : 'Installing').
  799. \ ' plugins ('.len(s:update.bar).'/'.total.')')
  800. call s:progress_bar(2, s:update.bar, total)
  801. call s:switch_out()
  802. endif
  803. endfunction
  804. function! s:logpos(name)
  805. for i in range(1, line('$'))
  806. if getline(i) =~# '^[-+x*] '.a:name.':'
  807. return i
  808. endif
  809. endfor
  810. return 0
  811. endfunction
  812. function! s:log(bullet, name, lines)
  813. if s:switch_in()
  814. let pos = s:logpos(a:name)
  815. if pos > 0
  816. execute pos 'd _'
  817. if pos > winheight('.')
  818. let pos = 4
  819. endif
  820. else
  821. let pos = 4
  822. endif
  823. call append(pos - 1, s:format_message(a:bullet, a:name, a:lines))
  824. call s:switch_out()
  825. endif
  826. endfunction
  827. function! s:update_vim()
  828. let s:jobs = {}
  829. call s:bar()
  830. call s:tick()
  831. endfunction
  832. function! s:tick()
  833. let pull = s:update.pull
  834. let prog = s:progress_opt(s:nvim)
  835. while 1 " Without TCO, Vim stack is bound to explode
  836. if empty(s:update.todo)
  837. if empty(s:jobs) && !s:update.fin
  838. let s:update.fin = 1
  839. call s:update_finish()
  840. endif
  841. return
  842. endif
  843. let name = keys(s:update.todo)[0]
  844. let spec = remove(s:update.todo, name)
  845. let new = !isdirectory(spec.dir)
  846. call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
  847. redraw
  848. if !new
  849. let [valid, msg] = s:git_valid(spec, 0)
  850. if valid
  851. if pull
  852. call s:spawn(name,
  853. \ printf('(git fetch %s 2>&1 && git checkout -q %s 2>&1 && git merge --ff-only origin/%s 2>&1 && git submodule update --init --recursive 2>&1)',
  854. \ prog, s:shellesc(spec.branch), s:shellesc(spec.branch)), { 'dir': spec.dir })
  855. else
  856. let s:jobs[name] = { 'running': 0, 'result': 'Already installed', 'error': 0 }
  857. endif
  858. else
  859. let s:jobs[name] = { 'running': 0, 'result': msg, 'error': 1 }
  860. endif
  861. else
  862. call s:spawn(name,
  863. \ printf('git clone %s --recursive %s -b %s %s 2>&1',
  864. \ prog,
  865. \ s:shellesc(spec.uri),
  866. \ s:shellesc(spec.branch),
  867. \ s:shellesc(s:trim(spec.dir))), { 'new': 1 })
  868. endif
  869. if !s:jobs[name].running
  870. call s:reap(name)
  871. endif
  872. if len(s:jobs) >= s:update.threads
  873. break
  874. endif
  875. endwhile
  876. endfunction
  877. function! s:update_ruby()
  878. ruby << EOF
  879. module PlugStream
  880. SEP = ["\r", "\n", nil]
  881. def get_line
  882. buffer = ''
  883. loop do
  884. char = readchar rescue return
  885. if SEP.include? char.chr
  886. buffer << $/
  887. break
  888. else
  889. buffer << char
  890. end
  891. end
  892. buffer
  893. end
  894. end unless defined?(PlugStream)
  895. def esc arg
  896. %["#{arg.gsub('"', '\"')}"]
  897. end
  898. require 'rubygems'
  899. require 'thread'
  900. require 'fileutils'
  901. require 'timeout'
  902. if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('1.9')
  903. def popen cmd
  904. IO.popen(cmd, :pgroup => true)
  905. end
  906. def killall pid
  907. Process.kill 'TERM', - pid rescue nil
  908. end
  909. else
  910. def popen cmd
  911. IO.popen(cmd)
  912. end
  913. def killall pid
  914. pids = [pid]
  915. unless `which pgrep 2> /dev/null`.empty?
  916. children = pids
  917. until children.empty?
  918. children = children.map { |pid|
  919. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  920. }.flatten
  921. pids += children
  922. end
  923. end
  924. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  925. end
  926. end
  927. running = true
  928. iswin = VIM::evaluate('s:is_win').to_i == 1
  929. pull = VIM::evaluate('s:update.pull').to_i == 1
  930. base = VIM::evaluate('g:plug_home')
  931. all = VIM::evaluate('s:update.todo')
  932. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  933. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  934. nthr = VIM::evaluate('s:update.threads').to_i
  935. maxy = VIM::evaluate('winheight(".")').to_i
  936. cd = iswin ? 'cd /d' : 'cd'
  937. tot = VIM::evaluate('len(s:update.todo)') || 0
  938. bar = ''
  939. skip = 'Already installed'
  940. mtx = Mutex.new
  941. take1 = proc { mtx.synchronize { running && all.shift } }
  942. logh = proc {
  943. cnt = bar.length
  944. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  945. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  946. VIM::command('normal! 2G')
  947. VIM::command('redraw') unless iswin
  948. }
  949. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  950. log = proc { |name, result, type|
  951. mtx.synchronize do
  952. ing = ![true, false].include?(type)
  953. bar += type ? '=' : 'x' unless ing
  954. b = case type
  955. when :install then '+' when :update then '*'
  956. when true, nil then '-' else
  957. VIM::command("call add(s:update.errors, '#{name}')")
  958. 'x'
  959. end
  960. result =
  961. if type || type.nil?
  962. ["#{b} #{name}: #{result.lines.to_a.last}"]
  963. elsif result =~ /^Interrupted|^Timeout/
  964. ["#{b} #{name}: #{result}"]
  965. else
  966. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  967. end
  968. if lnum = where.call(name)
  969. $curbuf.delete lnum
  970. lnum = 4 if ing && lnum > maxy
  971. end
  972. result.each_with_index do |line, offset|
  973. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  974. end
  975. logh.call
  976. end
  977. }
  978. bt = proc { |cmd, name, type, cleanup|
  979. tried = timeout = 0
  980. begin
  981. tried += 1
  982. timeout += limit
  983. fd = nil
  984. data = ''
  985. if iswin
  986. Timeout::timeout(timeout) do
  987. tmp = VIM::evaluate('tempname()')
  988. system("#{cmd} > #{tmp}")
  989. data = File.read(tmp).chomp
  990. File.unlink tmp rescue nil
  991. end
  992. else
  993. fd = popen(cmd).extend(PlugStream)
  994. first_line = true
  995. log_prob = 1.0 / nthr
  996. while line = Timeout::timeout(timeout) { fd.get_line }
  997. data << line
  998. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  999. first_line = false
  1000. end
  1001. fd.close
  1002. end
  1003. [$? == 0, data.chomp]
  1004. rescue Timeout::Error, Interrupt => e
  1005. if fd && !fd.closed?
  1006. killall fd.pid
  1007. fd.close
  1008. end
  1009. cleanup.call if cleanup
  1010. if e.is_a?(Timeout::Error) && tried < tries
  1011. 3.downto(1) do |countdown|
  1012. s = countdown > 1 ? 's' : ''
  1013. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  1014. sleep 1
  1015. end
  1016. log.call name, 'Retrying ...', type
  1017. retry
  1018. end
  1019. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  1020. end
  1021. }
  1022. main = Thread.current
  1023. threads = []
  1024. watcher = Thread.new {
  1025. while VIM::evaluate('getchar(1)')
  1026. sleep 0.1
  1027. end
  1028. mtx.synchronize do
  1029. running = false
  1030. threads.each { |t| t.raise Interrupt }
  1031. end
  1032. threads.each { |t| t.join rescue nil }
  1033. main.kill
  1034. }
  1035. refresh = Thread.new {
  1036. while true
  1037. mtx.synchronize do
  1038. break unless running
  1039. VIM::command('noautocmd normal! a')
  1040. end
  1041. sleep 0.2
  1042. end
  1043. } if VIM::evaluate('s:mac_gui') == 1
  1044. progress = VIM::evaluate('s:progress_opt(1)')
  1045. nthr.times do
  1046. mtx.synchronize do
  1047. threads << Thread.new {
  1048. while pair = take1.call
  1049. name = pair.first
  1050. dir, uri, branch = pair.last.values_at *%w[dir uri branch]
  1051. branch = esc branch
  1052. subm = "git submodule update --init --recursive 2>&1"
  1053. exists = File.directory? dir
  1054. ok, result =
  1055. if exists
  1056. dir = esc dir
  1057. ret, data = bt.call "#{cd} #{dir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil, nil
  1058. current_uri = data.lines.to_a.last
  1059. if !ret
  1060. if data =~ /^Interrupted|^Timeout/
  1061. [false, data]
  1062. else
  1063. [false, [data.chomp, "PlugClean required."].join($/)]
  1064. end
  1065. elsif current_uri.sub(/git::?@/, '') != uri.sub(/git::?@/, '')
  1066. [false, ["Invalid URI: #{current_uri}",
  1067. "Expected: #{uri}",
  1068. "PlugClean required."].join($/)]
  1069. else
  1070. if pull
  1071. log.call name, 'Updating ...', :update
  1072. bt.call "#{cd} #{dir} && (git fetch #{progress} 2>&1 && git checkout -q #{branch} 2>&1 && git merge --ff-only origin/#{branch} 2>&1 && #{subm})", name, :update, nil
  1073. else
  1074. [true, skip]
  1075. end
  1076. end
  1077. else
  1078. d = esc dir.sub(%r{[\\/]+$}, '')
  1079. log.call name, 'Installing ...', :install
  1080. bt.call "git clone #{progress} --recursive #{uri} -b #{branch} #{d} 2>&1", name, :install, proc {
  1081. FileUtils.rm_rf dir
  1082. }
  1083. end
  1084. mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
  1085. log.call name, result, ok
  1086. end
  1087. } if running
  1088. end
  1089. end
  1090. threads.each { |t| t.join rescue nil }
  1091. logh.call
  1092. refresh.kill if refresh
  1093. watcher.kill
  1094. EOF
  1095. endfunction
  1096. function! s:shellesc(arg)
  1097. return '"'.substitute(a:arg, '"', '\\"', 'g').'"'
  1098. endfunction
  1099. function! s:glob_dir(path)
  1100. return map(filter(s:lines(globpath(a:path, '**')), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  1101. endfunction
  1102. function! s:progress_bar(line, bar, total)
  1103. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  1104. endfunction
  1105. function! s:compare_git_uri(a, b)
  1106. let a = substitute(a:a, 'git:\{1,2}@', '', '')
  1107. let b = substitute(a:b, 'git:\{1,2}@', '', '')
  1108. return a ==# b
  1109. endfunction
  1110. function! s:format_message(bullet, name, message)
  1111. if a:bullet != 'x'
  1112. return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
  1113. else
  1114. let lines = map(s:lines(a:message), '" ".v:val')
  1115. return extend([printf('x %s:', a:name)], lines)
  1116. endif
  1117. endfunction
  1118. function! s:with_cd(cmd, dir)
  1119. return (s:is_win ? 'cd /d ' : 'cd ').s:esc(a:dir).' && '.a:cmd
  1120. endfunction
  1121. function! s:system(cmd, ...)
  1122. try
  1123. let sh = &shell
  1124. if !s:is_win
  1125. set shell=sh
  1126. endif
  1127. let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
  1128. return system(s:is_win ? '('.cmd.')' : cmd)
  1129. finally
  1130. let &shell = sh
  1131. endtry
  1132. endfunction
  1133. function! s:system_chomp(...)
  1134. let ret = call('s:system', a:000)
  1135. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  1136. endfunction
  1137. function! s:git_valid(spec, check_branch)
  1138. let ret = 1
  1139. let msg = 'OK'
  1140. if isdirectory(a:spec.dir)
  1141. let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url', a:spec.dir))
  1142. let remote = result[-1]
  1143. if v:shell_error
  1144. let msg = join([remote, 'PlugClean required.'], "\n")
  1145. let ret = 0
  1146. elseif !s:compare_git_uri(remote, a:spec.uri)
  1147. let msg = join(['Invalid URI: '.remote,
  1148. \ 'Expected: '.a:spec.uri,
  1149. \ 'PlugClean required.'], "\n")
  1150. let ret = 0
  1151. elseif a:check_branch
  1152. let branch = result[0]
  1153. if a:spec.branch !=# branch
  1154. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
  1155. if a:spec.branch !=# tag
  1156. let msg = printf('Invalid branch/tag: %s (expected: %s). Try PlugUpdate.',
  1157. \ (empty(tag) ? branch : tag), a:spec.branch)
  1158. let ret = 0
  1159. endif
  1160. endif
  1161. endif
  1162. else
  1163. let msg = 'Not found'
  1164. let ret = 0
  1165. endif
  1166. return [ret, msg]
  1167. endfunction
  1168. function! s:clean(force)
  1169. call s:prepare()
  1170. call append(0, 'Searching for unused plugins in '.g:plug_home)
  1171. call append(1, '')
  1172. " List of valid directories
  1173. let dirs = []
  1174. let [cnt, total] = [0, len(g:plugs)]
  1175. for [name, spec] in items(g:plugs)
  1176. if !s:is_managed(name) || s:git_valid(spec, 0)[0]
  1177. call add(dirs, spec.dir)
  1178. endif
  1179. let cnt += 1
  1180. call s:progress_bar(2, repeat('=', cnt), total)
  1181. normal! 2G
  1182. redraw
  1183. endfor
  1184. let allowed = {}
  1185. for dir in dirs
  1186. let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
  1187. let allowed[dir] = 1
  1188. for child in s:glob_dir(dir)
  1189. let allowed[child] = 1
  1190. endfor
  1191. endfor
  1192. let todo = []
  1193. let found = sort(s:glob_dir(g:plug_home))
  1194. while !empty(found)
  1195. let f = remove(found, 0)
  1196. if !has_key(allowed, f) && isdirectory(f)
  1197. call add(todo, f)
  1198. call append(line('$'), '- ' . f)
  1199. let found = filter(found, 'stridx(v:val, f) != 0')
  1200. end
  1201. endwhile
  1202. normal! G
  1203. redraw
  1204. if empty(todo)
  1205. call append(line('$'), 'Already clean.')
  1206. else
  1207. call inputsave()
  1208. let yes = a:force || (input('Proceed? (y/N) ') =~? '^y')
  1209. call inputrestore()
  1210. if yes
  1211. for dir in todo
  1212. if isdirectory(dir)
  1213. call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(dir))
  1214. endif
  1215. endfor
  1216. call append(line('$'), 'Removed.')
  1217. else
  1218. call append(line('$'), 'Cancelled.')
  1219. endif
  1220. endif
  1221. normal! G
  1222. endfunction
  1223. function! s:upgrade()
  1224. let new = s:me . '.new'
  1225. echo 'Downloading '. s:plug_src
  1226. redraw
  1227. try
  1228. if executable('curl')
  1229. let output = s:system(printf('curl -fLo %s %s', s:shellesc(new), s:plug_src))
  1230. if v:shell_error
  1231. throw get(s:lines(output), -1, v:shell_error)
  1232. endif
  1233. elseif s:ruby
  1234. call s:upgrade_using_ruby(new)
  1235. else
  1236. return s:err('curl executable or ruby support not found')
  1237. endif
  1238. catch
  1239. return s:err('Error upgrading vim-plug: '. v:exception)
  1240. endtry
  1241. if readfile(s:me) ==# readfile(new)
  1242. echo 'vim-plug is already up-to-date'
  1243. silent! call delete(new)
  1244. return 0
  1245. else
  1246. call rename(s:me, s:me . '.old')
  1247. call rename(new, s:me)
  1248. unlet g:loaded_plug
  1249. echo 'vim-plug has been upgraded'
  1250. return 1
  1251. endif
  1252. endfunction
  1253. function! s:upgrade_using_ruby(new)
  1254. ruby << EOF
  1255. require 'open-uri'
  1256. File.open(VIM::evaluate('a:new'), 'w') do |f|
  1257. f << open(VIM::evaluate('s:plug_src')).read
  1258. end
  1259. EOF
  1260. endfunction
  1261. function! s:upgrade_specs()
  1262. for spec in values(g:plugs)
  1263. let spec.frozen = get(spec, 'frozen', 0)
  1264. endfor
  1265. endfunction
  1266. function! s:status()
  1267. call s:prepare()
  1268. call append(0, 'Checking plugins')
  1269. call append(1, '')
  1270. let ecnt = 0
  1271. let unloaded = 0
  1272. let [cnt, total] = [0, len(g:plugs)]
  1273. for [name, spec] in items(g:plugs)
  1274. if has_key(spec, 'uri')
  1275. if isdirectory(spec.dir)
  1276. let [valid, msg] = s:git_valid(spec, 1)
  1277. else
  1278. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  1279. endif
  1280. else
  1281. if isdirectory(spec.dir)
  1282. let [valid, msg] = [1, 'OK']
  1283. else
  1284. let [valid, msg] = [0, 'Not found.']
  1285. endif
  1286. endif
  1287. let cnt += 1
  1288. let ecnt += !valid
  1289. " `s:loaded` entry can be missing if PlugUpgraded
  1290. if valid && get(s:loaded, name, -1) == 0
  1291. let unloaded = 1
  1292. let msg .= ' (not loaded)'
  1293. endif
  1294. call s:progress_bar(2, repeat('=', cnt), total)
  1295. call append(3, s:format_message(valid ? '-' : 'x', name, msg))
  1296. normal! 2G
  1297. redraw
  1298. endfor
  1299. call setline(1, 'Finished. '.ecnt.' error(s).')
  1300. normal! gg
  1301. setlocal nomodifiable
  1302. if unloaded
  1303. echo "Press 'L' on each line to load plugin, or 'U' to update"
  1304. nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1305. xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1306. end
  1307. endfunction
  1308. function! s:extract_name(str, prefix, suffix)
  1309. return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
  1310. endfunction
  1311. function! s:status_load(lnum)
  1312. let line = getline(a:lnum)
  1313. let name = s:extract_name(line, '-', '(not loaded)')
  1314. if !empty(name)
  1315. call plug#load(name)
  1316. setlocal modifiable
  1317. call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
  1318. setlocal nomodifiable
  1319. endif
  1320. endfunction
  1321. function! s:status_update() range
  1322. let lines = getline(a:firstline, a:lastline)
  1323. let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
  1324. if !empty(names)
  1325. echo
  1326. execute 'PlugUpdate' join(names)
  1327. endif
  1328. endfunction
  1329. function! s:is_preview_window_open()
  1330. silent! wincmd P
  1331. if &previewwindow
  1332. wincmd p
  1333. return 1
  1334. endif
  1335. return 0
  1336. endfunction
  1337. function! s:find_name(lnum)
  1338. for lnum in reverse(range(1, a:lnum))
  1339. let line = getline(lnum)
  1340. if empty(line)
  1341. return ''
  1342. endif
  1343. let name = s:extract_name(line, '-', '')
  1344. if !empty(name)
  1345. return name
  1346. endif
  1347. endfor
  1348. return ''
  1349. endfunction
  1350. function! s:preview_commit()
  1351. if b:plug_preview < 0
  1352. let b:plug_preview = !s:is_preview_window_open()
  1353. endif
  1354. let sha = matchstr(getline('.'), '\(^ \)\@<=[0-9a-z]\{7}')
  1355. if empty(sha)
  1356. return
  1357. endif
  1358. let name = s:find_name(line('.'))
  1359. if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
  1360. return
  1361. endif
  1362. execute 'pedit' sha
  1363. wincmd P
  1364. setlocal filetype=git buftype=nofile nobuflisted
  1365. execute 'silent read !cd' s:esc(g:plugs[name].dir) '&& git show' sha
  1366. normal! gg"_dd
  1367. wincmd p
  1368. endfunction
  1369. function! s:section(flags)
  1370. call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
  1371. endfunction
  1372. function! s:diff()
  1373. call s:prepare()
  1374. call append(0, 'Collecting updated changes ...')
  1375. normal! gg
  1376. redraw
  1377. let cnt = 0
  1378. for [k, v] in items(g:plugs)
  1379. if !isdirectory(v.dir) || !s:is_managed(k)
  1380. continue
  1381. endif
  1382. let diff = s:system_chomp('git log --pretty=format:"%h %s (%cr)" "HEAD...HEAD@{1}"', v.dir)
  1383. if !empty(diff)
  1384. call append(1, '')
  1385. call append(2, '- '.k.':')
  1386. call append(3, map(s:lines(diff), '" ". v:val'))
  1387. let cnt += 1
  1388. normal! gg
  1389. redraw
  1390. endif
  1391. endfor
  1392. call setline(1, cnt == 0 ? 'No updates.' : 'Last update:')
  1393. nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
  1394. nnoremap <silent> <buffer> X :call <SID>revert()<cr>
  1395. normal! gg
  1396. setlocal nomodifiable
  1397. if cnt > 0
  1398. echo "Press 'X' on each block to revert the update"
  1399. endif
  1400. endfunction
  1401. function! s:revert()
  1402. let name = s:find_name(line('.'))
  1403. if empty(name) || !has_key(g:plugs, name) ||
  1404. \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
  1405. return
  1406. endif
  1407. call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir)
  1408. setlocal modifiable
  1409. normal! "_dap
  1410. setlocal nomodifiable
  1411. echo 'Reverted.'
  1412. endfunction
  1413. function! s:snapshot(...) abort
  1414. let home = get(s:, 'plug_home_org', g:plug_home)
  1415. let [type, var, header] = s:is_win ?
  1416. \ ['dosbatch', '%PLUG_HOME%',
  1417. \ ['@echo off', ':: Generated by vim-plug', ':: '.strftime("%c"), '',
  1418. \ ':: Make sure to PlugUpdate first', '', 'set PLUG_HOME='.s:esc(home)]] :
  1419. \ ['sh', '$PLUG_HOME',
  1420. \ ['#!/bin/sh', '# Generated by vim-plug', '# '.strftime("%c"), '',
  1421. \ 'vim +PlugUpdate +qa', '', 'PLUG_HOME='.s:esc(home)]]
  1422. call s:prepare()
  1423. execute 'setf' type
  1424. call append(0, header)
  1425. call append('$', '')
  1426. 1
  1427. redraw
  1428. let dirs = sort(map(values(filter(copy(g:plugs),
  1429. \'has_key(v:val, "uri") && isdirectory(v:val.dir)')), 'v:val.dir'))
  1430. let anchor = line('$') - 1
  1431. for dir in reverse(dirs)
  1432. let sha = s:system_chomp('git rev-parse --short HEAD', dir)
  1433. if !empty(sha)
  1434. call append(anchor, printf('cd %s && git reset --hard %s',
  1435. \ substitute(dir, '^'.g:plug_home, var, ''), sha))
  1436. redraw
  1437. endif
  1438. endfor
  1439. if a:0 > 0
  1440. let fn = expand(a:1)
  1441. let fne = s:esc(fn)
  1442. call writefile(getline(1, '$'), fn)
  1443. if !s:is_win | call s:system('chmod +x ' . fne) | endif
  1444. echo 'Saved to '.a:1
  1445. silent execute 'e' fne
  1446. endif
  1447. endfunction
  1448. function! s:split_rtp()
  1449. return split(&rtp, '\\\@<!,')
  1450. endfunction
  1451. let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
  1452. let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
  1453. if exists('g:plugs')
  1454. let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
  1455. call s:upgrade_specs()
  1456. call s:define_commands()
  1457. endif
  1458. let &cpo = s:cpo_save
  1459. unlet s:cpo_save