plug.vim 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  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> o
  540. silent! unmap <buffer> X
  541. setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap cursorline modifiable
  542. setf vim-plug
  543. call s:syntax()
  544. endfunction
  545. function! s:assign_name()
  546. " Assign buffer name
  547. let prefix = '[Plugins]'
  548. let name = prefix
  549. let idx = 2
  550. while bufexists(name)
  551. let name = printf('%s (%s)', prefix, idx)
  552. let idx = idx + 1
  553. endwhile
  554. silent! execute 'f' fnameescape(name)
  555. endfunction
  556. function! s:do(pull, force, todo)
  557. for [name, spec] in items(a:todo)
  558. if !isdirectory(spec.dir)
  559. continue
  560. endif
  561. let installed = has_key(s:update.new, name)
  562. let updated = installed ? 0 :
  563. \ (a:pull && !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', spec.dir)))
  564. if a:force || installed || updated
  565. execute 'cd' s:esc(spec.dir)
  566. call append(3, '- Post-update hook for '. name .' ... ')
  567. let type = type(spec.do)
  568. if type == s:TYPE.string
  569. try
  570. " FIXME: Escaping is incomplete. We could use shellescape with eval,
  571. " but it won't work on Windows.
  572. let g:_plug_do = '!'.escape(spec.do, '#!%')
  573. execute "normal! :execute g:_plug_do\<cr>\<cr>"
  574. finally
  575. let result = v:shell_error ? ('Exit status: '.v:shell_error) : 'Done!'
  576. unlet g:_plug_do
  577. endtry
  578. elseif type == s:TYPE.funcref
  579. try
  580. let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
  581. call spec.do({ 'name': name, 'status': status, 'force': a:force })
  582. let result = 'Done!'
  583. catch
  584. let result = 'Error: ' . v:exception
  585. endtry
  586. else
  587. let result = 'Error: Invalid type!'
  588. endif
  589. call setline(4, getline(4) . result)
  590. cd -
  591. endif
  592. endfor
  593. endfunction
  594. function! s:finish(pull)
  595. let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
  596. if new_frozen
  597. let s = new_frozen > 1 ? 's' : ''
  598. call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
  599. endif
  600. call append(3, '- Finishing ... ')
  601. redraw
  602. call plug#helptags()
  603. call plug#end()
  604. call setline(4, getline(4) . 'Done!')
  605. redraw
  606. let msgs = []
  607. if !empty(s:update.errors)
  608. call add(msgs, "Press 'R' to retry.")
  609. endif
  610. if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
  611. \ "v:val =~ '^- ' && stridx(v:val, 'Already up-to-date') < 0"))
  612. call add(msgs, "Press 'D' to see the updated changes.")
  613. endif
  614. echo join(msgs, ' ')
  615. endfunction
  616. function! s:retry()
  617. if empty(s:update.errors)
  618. return
  619. endif
  620. call s:update_impl(s:update.pull, s:update.force,
  621. \ extend(copy(s:update.errors), [s:update.threads]))
  622. endfunction
  623. function! s:is_managed(name)
  624. return has_key(g:plugs[a:name], 'uri')
  625. endfunction
  626. function! s:names(...)
  627. return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
  628. endfunction
  629. function! s:update_impl(pull, force, args) abort
  630. let args = copy(a:args)
  631. let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
  632. \ remove(args, -1) : get(g:, 'plug_threads', 16)
  633. let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
  634. let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
  635. \ filter(managed, 'index(args, v:key) >= 0')
  636. if empty(todo)
  637. echohl WarningMsg
  638. echo 'No plugin to '. (a:pull ? 'update' : 'install') . '.'
  639. echohl None
  640. return
  641. endif
  642. if !s:is_win && s:git_version_requirement(2, 3)
  643. let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : ''
  644. let $GIT_TERMINAL_PROMPT = 0
  645. for plug in values(todo)
  646. let plug.uri = substitute(plug.uri,
  647. \ '^https://git::@github\.com', 'https://github.com', '')
  648. endfor
  649. endif
  650. if !isdirectory(g:plug_home)
  651. try
  652. call mkdir(g:plug_home, 'p')
  653. catch
  654. return s:err(printf('Invalid plug directory: %s. '.
  655. \ 'Try to call plug#begin with a valid directory', g:plug_home))
  656. endtry
  657. endif
  658. let s:update = {
  659. \ 'start': reltime(),
  660. \ 'all': todo,
  661. \ 'todo': copy(todo),
  662. \ 'errors': [],
  663. \ 'pull': a:pull,
  664. \ 'force': a:force,
  665. \ 'new': {},
  666. \ 'threads': (s:ruby || s:nvim) ? min([len(todo), threads]) : 1,
  667. \ 'bar': '',
  668. \ 'fin': 0
  669. \ }
  670. call s:prepare()
  671. call append(0, ['', ''])
  672. normal! 2G
  673. if s:ruby && s:update.threads > 1
  674. try
  675. let imd = &imd
  676. if s:mac_gui
  677. set noimd
  678. endif
  679. call s:update_ruby()
  680. catch
  681. let lines = getline(4, '$')
  682. let printed = {}
  683. silent! 4,$d _
  684. for line in lines
  685. let name = s:extract_name(line, '.', '')
  686. if empty(name) || !has_key(printed, name)
  687. call append('$', line)
  688. if !empty(name)
  689. let printed[name] = 1
  690. if line[0] == 'x' && index(s:update.errors, name) < 0
  691. call add(s:update.errors, name)
  692. end
  693. endif
  694. endif
  695. endfor
  696. finally
  697. let &imd = imd
  698. call s:update_finish()
  699. endtry
  700. else
  701. call s:update_vim()
  702. endif
  703. endfunction
  704. function! s:update_finish()
  705. if exists('s:git_terminal_prompt')
  706. let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt
  707. endif
  708. if s:switch_in()
  709. call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'has_key(v:val, "do")'))
  710. call s:finish(s:update.pull)
  711. call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
  712. call s:switch_out('normal! gg')
  713. endif
  714. endfunction
  715. function! s:job_abort()
  716. if !s:nvim || !exists('s:jobs')
  717. return
  718. endif
  719. augroup PlugJobControl
  720. autocmd!
  721. augroup END
  722. for [name, j] in items(s:jobs)
  723. silent! call jobstop(j.jobid)
  724. if j.new
  725. call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir))
  726. endif
  727. endfor
  728. let s:jobs = {}
  729. endfunction
  730. function! s:job_handler(name) abort
  731. if !s:plug_window_exists() " plug window closed
  732. return s:job_abort()
  733. endif
  734. if !has_key(s:jobs, a:name)
  735. return
  736. endif
  737. let job = s:jobs[a:name]
  738. if v:job_data[1] == 'exit'
  739. let job.running = 0
  740. if s:lastline(job.result) ==# 'Error'
  741. let job.error = 1
  742. let job.result = substitute(job.result, "Error[\r\n]$", '', '')
  743. endif
  744. call s:reap(a:name)
  745. call s:tick()
  746. else
  747. let job.result .= s:to_s(v:job_data[2])
  748. " To reduce the number of buffer updates
  749. let job.tick = get(job, 'tick', -1) + 1
  750. if job.tick % len(s:jobs) == 0
  751. call s:log(job.new ? '+' : '*', a:name, job.result)
  752. endif
  753. endif
  754. endfunction
  755. function! s:spawn(name, cmd, opts)
  756. let job = { 'running': 1, 'new': get(a:opts, 'new', 0),
  757. \ 'error': 0, 'result': '' }
  758. let s:jobs[a:name] = job
  759. if s:nvim
  760. let x = jobstart(a:name, 'sh', ['-c',
  761. \ (has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd)
  762. \ . ' || echo Error'])
  763. if x > 0
  764. let job.jobid = x
  765. augroup PlugJobControl
  766. execute 'autocmd JobActivity' a:name printf('call s:job_handler(%s)', string(a:name))
  767. augroup END
  768. else
  769. let job.running = 0
  770. let job.error = 1
  771. let job.result = x < 0 ? 'sh is not executable' :
  772. \ 'Invalid arguments (or job table is full)'
  773. endif
  774. else
  775. let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd]
  776. let job.result = call('s:system', params)
  777. let job.error = v:shell_error != 0
  778. let job.running = 0
  779. endif
  780. endfunction
  781. function! s:reap(name)
  782. if s:nvim
  783. silent! execute 'autocmd! PlugJobControl JobActivity' a:name
  784. endif
  785. let job = s:jobs[a:name]
  786. if job.error
  787. call add(s:update.errors, a:name)
  788. elseif get(job, 'new', 0)
  789. let s:update.new[a:name] = 1
  790. endif
  791. let s:update.bar .= job.error ? 'x' : '='
  792. call s:log(job.error ? 'x' : '-', a:name, job.result)
  793. call s:bar()
  794. call remove(s:jobs, a:name)
  795. endfunction
  796. function! s:bar()
  797. if s:switch_in()
  798. let total = len(s:update.all)
  799. call setline(1, (s:update.pull ? 'Updating' : 'Installing').
  800. \ ' plugins ('.len(s:update.bar).'/'.total.')')
  801. call s:progress_bar(2, s:update.bar, total)
  802. call s:switch_out()
  803. endif
  804. endfunction
  805. function! s:logpos(name)
  806. for i in range(1, line('$'))
  807. if getline(i) =~# '^[-+x*] '.a:name.':'
  808. return i
  809. endif
  810. endfor
  811. return 0
  812. endfunction
  813. function! s:log(bullet, name, lines)
  814. if s:switch_in()
  815. let pos = s:logpos(a:name)
  816. if pos > 0
  817. execute pos 'd _'
  818. if pos > winheight('.')
  819. let pos = 4
  820. endif
  821. else
  822. let pos = 4
  823. endif
  824. call append(pos - 1, s:format_message(a:bullet, a:name, a:lines))
  825. call s:switch_out()
  826. endif
  827. endfunction
  828. function! s:update_vim()
  829. let s:jobs = {}
  830. call s:bar()
  831. call s:tick()
  832. endfunction
  833. function! s:tick()
  834. let pull = s:update.pull
  835. let prog = s:progress_opt(s:nvim)
  836. while 1 " Without TCO, Vim stack is bound to explode
  837. if empty(s:update.todo)
  838. if empty(s:jobs) && !s:update.fin
  839. let s:update.fin = 1
  840. call s:update_finish()
  841. endif
  842. return
  843. endif
  844. let name = keys(s:update.todo)[0]
  845. let spec = remove(s:update.todo, name)
  846. let new = !isdirectory(spec.dir)
  847. call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
  848. redraw
  849. if !new
  850. let [valid, msg] = s:git_valid(spec, 0)
  851. if valid
  852. if pull
  853. call s:spawn(name,
  854. \ 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)',
  855. \ prog, s:shellesc(spec.branch), s:shellesc(spec.branch)), { 'dir': spec.dir })
  856. else
  857. let s:jobs[name] = { 'running': 0, 'result': 'Already installed', 'error': 0 }
  858. endif
  859. else
  860. let s:jobs[name] = { 'running': 0, 'result': msg, 'error': 1 }
  861. endif
  862. else
  863. call s:spawn(name,
  864. \ printf('git clone %s --recursive %s -b %s %s 2>&1',
  865. \ prog,
  866. \ s:shellesc(spec.uri),
  867. \ s:shellesc(spec.branch),
  868. \ s:shellesc(s:trim(spec.dir))), { 'new': 1 })
  869. endif
  870. if !s:jobs[name].running
  871. call s:reap(name)
  872. endif
  873. if len(s:jobs) >= s:update.threads
  874. break
  875. endif
  876. endwhile
  877. endfunction
  878. function! s:update_ruby()
  879. ruby << EOF
  880. module PlugStream
  881. SEP = ["\r", "\n", nil]
  882. def get_line
  883. buffer = ''
  884. loop do
  885. char = readchar rescue return
  886. if SEP.include? char.chr
  887. buffer << $/
  888. break
  889. else
  890. buffer << char
  891. end
  892. end
  893. buffer
  894. end
  895. end unless defined?(PlugStream)
  896. def esc arg
  897. %["#{arg.gsub('"', '\"')}"]
  898. end
  899. def killall pid
  900. pids = [pid]
  901. unless `which pgrep 2> /dev/null`.empty?
  902. children = pids
  903. until children.empty?
  904. children = children.map { |pid|
  905. `pgrep -P #{pid}`.lines.map { |l| l.chomp }
  906. }.flatten
  907. pids += children
  908. end
  909. end
  910. pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
  911. end
  912. require 'thread'
  913. require 'fileutils'
  914. require 'timeout'
  915. running = true
  916. iswin = VIM::evaluate('s:is_win').to_i == 1
  917. pull = VIM::evaluate('s:update.pull').to_i == 1
  918. base = VIM::evaluate('g:plug_home')
  919. all = VIM::evaluate('s:update.todo')
  920. limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
  921. tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
  922. nthr = VIM::evaluate('s:update.threads').to_i
  923. maxy = VIM::evaluate('winheight(".")').to_i
  924. cd = iswin ? 'cd /d' : 'cd'
  925. tot = VIM::evaluate('len(s:update.todo)') || 0
  926. bar = ''
  927. skip = 'Already installed'
  928. mtx = Mutex.new
  929. take1 = proc { mtx.synchronize { running && all.shift } }
  930. logh = proc {
  931. cnt = bar.length
  932. $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
  933. $curbuf[2] = '[' + bar.ljust(tot) + ']'
  934. VIM::command('normal! 2G')
  935. VIM::command('redraw') unless iswin
  936. }
  937. where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
  938. log = proc { |name, result, type|
  939. mtx.synchronize do
  940. ing = ![true, false].include?(type)
  941. bar += type ? '=' : 'x' unless ing
  942. b = case type
  943. when :install then '+' when :update then '*'
  944. when true, nil then '-' else
  945. VIM::command("call add(s:update.errors, '#{name}')")
  946. 'x'
  947. end
  948. result =
  949. if type || type.nil?
  950. ["#{b} #{name}: #{result.lines.to_a.last}"]
  951. elsif result =~ /^Interrupted|^Timeout/
  952. ["#{b} #{name}: #{result}"]
  953. else
  954. ["#{b} #{name}"] + result.lines.map { |l| " " << l }
  955. end
  956. if lnum = where.call(name)
  957. $curbuf.delete lnum
  958. lnum = 4 if ing && lnum > maxy
  959. end
  960. result.each_with_index do |line, offset|
  961. $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
  962. end
  963. logh.call
  964. end
  965. }
  966. bt = proc { |cmd, name, type, cleanup|
  967. tried = timeout = 0
  968. begin
  969. tried += 1
  970. timeout += limit
  971. fd = nil
  972. data = ''
  973. if iswin
  974. Timeout::timeout(timeout) do
  975. tmp = VIM::evaluate('tempname()')
  976. system("#{cmd} > #{tmp}")
  977. data = File.read(tmp).chomp
  978. File.unlink tmp rescue nil
  979. end
  980. else
  981. fd = IO.popen(cmd).extend(PlugStream)
  982. first_line = true
  983. log_prob = 1.0 / nthr
  984. while line = Timeout::timeout(timeout) { fd.get_line }
  985. data << line
  986. log.call name, line.chomp, type if name && (first_line || rand < log_prob)
  987. first_line = false
  988. end
  989. fd.close
  990. end
  991. [$? == 0, data.chomp]
  992. rescue Timeout::Error, Interrupt => e
  993. if fd && !fd.closed?
  994. killall fd.pid
  995. fd.close
  996. end
  997. cleanup.call if cleanup
  998. if e.is_a?(Timeout::Error) && tried < tries
  999. 3.downto(1) do |countdown|
  1000. s = countdown > 1 ? 's' : ''
  1001. log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
  1002. sleep 1
  1003. end
  1004. log.call name, 'Retrying ...', type
  1005. retry
  1006. end
  1007. [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
  1008. end
  1009. }
  1010. main = Thread.current
  1011. threads = []
  1012. watcher = Thread.new {
  1013. while VIM::evaluate('getchar(1)')
  1014. sleep 0.1
  1015. end
  1016. mtx.synchronize do
  1017. running = false
  1018. threads.each { |t| t.raise Interrupt }
  1019. end
  1020. threads.each { |t| t.join rescue nil }
  1021. main.kill
  1022. }
  1023. refresh = Thread.new {
  1024. while true
  1025. mtx.synchronize do
  1026. break unless running
  1027. VIM::command('noautocmd normal! a')
  1028. end
  1029. sleep 0.2
  1030. end
  1031. } if VIM::evaluate('s:mac_gui') == 1
  1032. progress = VIM::evaluate('s:progress_opt(1)')
  1033. nthr.times do
  1034. mtx.synchronize do
  1035. threads << Thread.new {
  1036. while pair = take1.call
  1037. name = pair.first
  1038. dir, uri, branch = pair.last.values_at *%w[dir uri branch]
  1039. branch = esc branch
  1040. subm = "git submodule update --init --recursive 2>&1"
  1041. exists = File.directory? dir
  1042. ok, result =
  1043. if exists
  1044. dir = esc dir
  1045. ret, data = bt.call "#{cd} #{dir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil, nil
  1046. current_uri = data.lines.to_a.last
  1047. if !ret
  1048. if data =~ /^Interrupted|^Timeout/
  1049. [false, data]
  1050. else
  1051. [false, [data.chomp, "PlugClean required."].join($/)]
  1052. end
  1053. elsif current_uri.sub(/git::?@/, '') != uri.sub(/git::?@/, '')
  1054. [false, ["Invalid URI: #{current_uri}",
  1055. "Expected: #{uri}",
  1056. "PlugClean required."].join($/)]
  1057. else
  1058. if pull
  1059. log.call name, 'Updating ...', :update
  1060. 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
  1061. else
  1062. [true, skip]
  1063. end
  1064. end
  1065. else
  1066. d = esc dir.sub(%r{[\\/]+$}, '')
  1067. log.call name, 'Installing ...', :install
  1068. bt.call "git clone #{progress} --recursive #{uri} -b #{branch} #{d} 2>&1", name, :install, proc {
  1069. FileUtils.rm_rf dir
  1070. }
  1071. end
  1072. mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
  1073. log.call name, result, ok
  1074. end
  1075. } if running
  1076. end
  1077. end
  1078. threads.each { |t| t.join rescue nil }
  1079. logh.call
  1080. refresh.kill if refresh
  1081. watcher.kill
  1082. EOF
  1083. endfunction
  1084. function! s:shellesc(arg)
  1085. return '"'.substitute(a:arg, '"', '\\"', 'g').'"'
  1086. endfunction
  1087. function! s:glob_dir(path)
  1088. return map(filter(s:lines(globpath(a:path, '**')), 'isdirectory(v:val)'), 's:dirpath(v:val)')
  1089. endfunction
  1090. function! s:progress_bar(line, bar, total)
  1091. call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
  1092. endfunction
  1093. function! s:compare_git_uri(a, b)
  1094. let a = substitute(a:a, 'git:\{1,2}@', '', '')
  1095. let b = substitute(a:b, 'git:\{1,2}@', '', '')
  1096. return a ==# b
  1097. endfunction
  1098. function! s:format_message(bullet, name, message)
  1099. if a:bullet != 'x'
  1100. return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
  1101. else
  1102. let lines = map(s:lines(a:message), '" ".v:val')
  1103. return extend([printf('x %s:', a:name)], lines)
  1104. endif
  1105. endfunction
  1106. function! s:with_cd(cmd, dir)
  1107. return (s:is_win ? 'cd /d ' : 'cd ').s:esc(a:dir).' && '.a:cmd
  1108. endfunction
  1109. function! s:system(cmd, ...)
  1110. try
  1111. let sh = &shell
  1112. if !s:is_win
  1113. set shell=sh
  1114. endif
  1115. let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
  1116. return system(s:is_win ? '('.cmd.')' : cmd)
  1117. finally
  1118. let &shell = sh
  1119. endtry
  1120. endfunction
  1121. function! s:system_chomp(...)
  1122. let ret = call('s:system', a:000)
  1123. return v:shell_error ? '' : substitute(ret, '\n$', '', '')
  1124. endfunction
  1125. function! s:git_valid(spec, check_branch)
  1126. let ret = 1
  1127. let msg = 'OK'
  1128. if isdirectory(a:spec.dir)
  1129. let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url', a:spec.dir))
  1130. let remote = result[-1]
  1131. if v:shell_error
  1132. let msg = join([remote, 'PlugClean required.'], "\n")
  1133. let ret = 0
  1134. elseif !s:compare_git_uri(remote, a:spec.uri)
  1135. let msg = join(['Invalid URI: '.remote,
  1136. \ 'Expected: '.a:spec.uri,
  1137. \ 'PlugClean required.'], "\n")
  1138. let ret = 0
  1139. elseif a:check_branch
  1140. let branch = result[0]
  1141. if a:spec.branch !=# branch
  1142. let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
  1143. if a:spec.branch !=# tag
  1144. let msg = printf('Invalid branch/tag: %s (expected: %s). Try PlugUpdate.',
  1145. \ (empty(tag) ? branch : tag), a:spec.branch)
  1146. let ret = 0
  1147. endif
  1148. endif
  1149. endif
  1150. else
  1151. let msg = 'Not found'
  1152. let ret = 0
  1153. endif
  1154. return [ret, msg]
  1155. endfunction
  1156. function! s:clean(force)
  1157. call s:prepare()
  1158. call append(0, 'Searching for unused plugins in '.g:plug_home)
  1159. call append(1, '')
  1160. " List of valid directories
  1161. let dirs = []
  1162. let [cnt, total] = [0, len(g:plugs)]
  1163. for [name, spec] in items(g:plugs)
  1164. if !s:is_managed(name) || s:git_valid(spec, 0)[0]
  1165. call add(dirs, spec.dir)
  1166. endif
  1167. let cnt += 1
  1168. call s:progress_bar(2, repeat('=', cnt), total)
  1169. normal! 2G
  1170. redraw
  1171. endfor
  1172. let allowed = {}
  1173. for dir in dirs
  1174. let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
  1175. let allowed[dir] = 1
  1176. for child in s:glob_dir(dir)
  1177. let allowed[child] = 1
  1178. endfor
  1179. endfor
  1180. let todo = []
  1181. let found = sort(s:glob_dir(g:plug_home))
  1182. while !empty(found)
  1183. let f = remove(found, 0)
  1184. if !has_key(allowed, f) && isdirectory(f)
  1185. call add(todo, f)
  1186. call append(line('$'), '- ' . f)
  1187. let found = filter(found, 'stridx(v:val, f) != 0')
  1188. end
  1189. endwhile
  1190. normal! G
  1191. redraw
  1192. if empty(todo)
  1193. call append(line('$'), 'Already clean.')
  1194. else
  1195. call inputsave()
  1196. let yes = a:force || (input('Proceed? (y/N) ') =~? '^y')
  1197. call inputrestore()
  1198. if yes
  1199. for dir in todo
  1200. if isdirectory(dir)
  1201. call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(dir))
  1202. endif
  1203. endfor
  1204. call append(line('$'), 'Removed.')
  1205. else
  1206. call append(line('$'), 'Cancelled.')
  1207. endif
  1208. endif
  1209. normal! G
  1210. endfunction
  1211. function! s:upgrade()
  1212. let new = s:me . '.new'
  1213. echo 'Downloading '. s:plug_src
  1214. redraw
  1215. try
  1216. if executable('curl')
  1217. let output = s:system(printf('curl -fLo %s %s', s:shellesc(new), s:plug_src))
  1218. if v:shell_error
  1219. throw get(s:lines(output), -1, v:shell_error)
  1220. endif
  1221. elseif s:ruby
  1222. call s:upgrade_using_ruby(new)
  1223. else
  1224. return s:err('curl executable or ruby support not found')
  1225. endif
  1226. catch
  1227. return s:err('Error upgrading vim-plug: '. v:exception)
  1228. endtry
  1229. if readfile(s:me) ==# readfile(new)
  1230. echo 'vim-plug is already up-to-date'
  1231. silent! call delete(new)
  1232. return 0
  1233. else
  1234. call rename(s:me, s:me . '.old')
  1235. call rename(new, s:me)
  1236. unlet g:loaded_plug
  1237. echo 'vim-plug has been upgraded'
  1238. return 1
  1239. endif
  1240. endfunction
  1241. function! s:upgrade_using_ruby(new)
  1242. ruby << EOF
  1243. require 'open-uri'
  1244. File.open(VIM::evaluate('a:new'), 'w') do |f|
  1245. f << open(VIM::evaluate('s:plug_src')).read
  1246. end
  1247. EOF
  1248. endfunction
  1249. function! s:upgrade_specs()
  1250. for spec in values(g:plugs)
  1251. let spec.frozen = get(spec, 'frozen', 0)
  1252. endfor
  1253. endfunction
  1254. function! s:status()
  1255. call s:prepare()
  1256. call append(0, 'Checking plugins')
  1257. call append(1, '')
  1258. let ecnt = 0
  1259. let unloaded = 0
  1260. let [cnt, total] = [0, len(g:plugs)]
  1261. for [name, spec] in items(g:plugs)
  1262. if has_key(spec, 'uri')
  1263. if isdirectory(spec.dir)
  1264. let [valid, msg] = s:git_valid(spec, 1)
  1265. else
  1266. let [valid, msg] = [0, 'Not found. Try PlugInstall.']
  1267. endif
  1268. else
  1269. if isdirectory(spec.dir)
  1270. let [valid, msg] = [1, 'OK']
  1271. else
  1272. let [valid, msg] = [0, 'Not found.']
  1273. endif
  1274. endif
  1275. let cnt += 1
  1276. let ecnt += !valid
  1277. " `s:loaded` entry can be missing if PlugUpgraded
  1278. if valid && get(s:loaded, name, -1) == 0
  1279. let unloaded = 1
  1280. let msg .= ' (not loaded)'
  1281. endif
  1282. call s:progress_bar(2, repeat('=', cnt), total)
  1283. call append(3, s:format_message(valid ? '-' : 'x', name, msg))
  1284. normal! 2G
  1285. redraw
  1286. endfor
  1287. call setline(1, 'Finished. '.ecnt.' error(s).')
  1288. normal! gg
  1289. setlocal nomodifiable
  1290. if unloaded
  1291. echo "Press 'L' on each line to load plugin, or 'U' to update"
  1292. nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1293. xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
  1294. end
  1295. endfunction
  1296. function! s:extract_name(str, prefix, suffix)
  1297. return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
  1298. endfunction
  1299. function! s:status_load(lnum)
  1300. let line = getline(a:lnum)
  1301. let name = s:extract_name(line, '-', '(not loaded)')
  1302. if !empty(name)
  1303. call plug#load(name)
  1304. setlocal modifiable
  1305. call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
  1306. setlocal nomodifiable
  1307. endif
  1308. endfunction
  1309. function! s:status_update() range
  1310. let lines = getline(a:firstline, a:lastline)
  1311. let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
  1312. if !empty(names)
  1313. echo
  1314. execute 'PlugUpdate' join(names)
  1315. endif
  1316. endfunction
  1317. function! s:is_preview_window_open()
  1318. silent! wincmd P
  1319. if &previewwindow
  1320. wincmd p
  1321. return 1
  1322. endif
  1323. return 0
  1324. endfunction
  1325. function! s:find_name(lnum)
  1326. for lnum in reverse(range(1, a:lnum))
  1327. let line = getline(lnum)
  1328. if empty(line)
  1329. return ''
  1330. endif
  1331. let name = s:extract_name(line, '-', '')
  1332. if !empty(name)
  1333. return name
  1334. endif
  1335. endfor
  1336. return ''
  1337. endfunction
  1338. function! s:preview_commit()
  1339. if b:plug_preview < 0
  1340. let b:plug_preview = !s:is_preview_window_open()
  1341. endif
  1342. let sha = matchstr(getline('.'), '\(^ \)\@<=[0-9a-z]\{7}')
  1343. if empty(sha)
  1344. return
  1345. endif
  1346. let name = s:find_name(line('.'))
  1347. if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
  1348. return
  1349. endif
  1350. execute 'pedit' sha
  1351. wincmd P
  1352. setlocal filetype=git buftype=nofile nobuflisted
  1353. execute 'silent read !cd' s:esc(g:plugs[name].dir) '&& git show' sha
  1354. normal! gg"_dd
  1355. wincmd p
  1356. endfunction
  1357. function! s:section(flags)
  1358. call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
  1359. endfunction
  1360. function! s:diff()
  1361. call s:prepare()
  1362. call append(0, 'Collecting updated changes ...')
  1363. normal! gg
  1364. redraw
  1365. let cnt = 0
  1366. for [k, v] in items(g:plugs)
  1367. if !isdirectory(v.dir) || !s:is_managed(k)
  1368. continue
  1369. endif
  1370. let diff = s:system_chomp('git log --pretty=format:"%h %s (%cr)" "HEAD...HEAD@{1}"', v.dir)
  1371. if !empty(diff)
  1372. call append(1, '')
  1373. call append(2, '- '.k.':')
  1374. call append(3, map(s:lines(diff), '" ". v:val'))
  1375. let cnt += 1
  1376. normal! gg
  1377. redraw
  1378. endif
  1379. endfor
  1380. call setline(1, cnt == 0 ? 'No updates.' : 'Last update:')
  1381. nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
  1382. nnoremap <silent> <buffer> o :silent! call <SID>preview_commit()<cr>
  1383. nnoremap <silent> <buffer> X :call <SID>revert()<cr>
  1384. normal! gg
  1385. setlocal nomodifiable
  1386. if cnt > 0
  1387. echo "Press 'X' on each block to revert the update"
  1388. endif
  1389. endfunction
  1390. function! s:revert()
  1391. let name = s:find_name(line('.'))
  1392. if empty(name) || !has_key(g:plugs, name) ||
  1393. \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
  1394. return
  1395. endif
  1396. call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir)
  1397. setlocal modifiable
  1398. normal! "_dap
  1399. setlocal nomodifiable
  1400. echo 'Reverted.'
  1401. endfunction
  1402. function! s:snapshot(...) abort
  1403. let home = get(s:, 'plug_home_org', g:plug_home)
  1404. let [type, var, header] = s:is_win ?
  1405. \ ['dosbatch', '%PLUG_HOME%',
  1406. \ ['@echo off', ':: Generated by vim-plug', ':: '.strftime("%c"), '',
  1407. \ ':: Make sure to PlugUpdate first', '', 'set PLUG_HOME='.s:esc(home)]] :
  1408. \ ['sh', '$PLUG_HOME',
  1409. \ ['#!/bin/sh', '# Generated by vim-plug', '# '.strftime("%c"), '',
  1410. \ 'vim +PlugUpdate +qa', '', 'PLUG_HOME='.s:esc(home)]]
  1411. call s:prepare()
  1412. execute 'setf' type
  1413. call append(0, header)
  1414. call append('$', '')
  1415. 1
  1416. redraw
  1417. let dirs = sort(map(values(filter(copy(g:plugs),
  1418. \'has_key(v:val, "uri") && isdirectory(v:val.dir)')), 'v:val.dir'))
  1419. let anchor = line('$') - 1
  1420. for dir in reverse(dirs)
  1421. let sha = s:system_chomp('git rev-parse --short HEAD', dir)
  1422. if !empty(sha)
  1423. call append(anchor, printf('cd %s && git reset --hard %s',
  1424. \ substitute(dir, '^'.g:plug_home, var, ''), sha))
  1425. redraw
  1426. endif
  1427. endfor
  1428. if a:0 > 0
  1429. let fn = expand(a:1)
  1430. let fne = s:esc(fn)
  1431. call writefile(getline(1, '$'), fn)
  1432. if !s:is_win | call s:system('chmod +x ' . fne) | endif
  1433. echo 'Saved to '.a:1
  1434. silent execute 'e' fne
  1435. endif
  1436. endfunction
  1437. function! s:split_rtp()
  1438. return split(&rtp, '\\\@<!,')
  1439. endfunction
  1440. let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
  1441. let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
  1442. if exists('g:plugs')
  1443. let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
  1444. call s:upgrade_specs()
  1445. call s:define_commands()
  1446. endif
  1447. let &cpo = s:cpo_save
  1448. unlet s:cpo_save