From e2c64a3a8eba5bc4c011c1d2aa4ee9d1182b6011 Mon Sep 17 00:00:00 2001 From: Fernando Schauenburg Date: Fri, 27 Jan 2017 14:38:59 +0100 Subject: [PATCH] [vim] update vim-plug (by running :PlugUpgrade) The command :PlugUpgrade will automatically clone the HEAD on master from https://github.com/junegunn/vim-plug.git. As of today, the output of `git describe master` is 0.9.1-45-g5fc9eab. --- vim/autoload/plug.vim | 547 ++++++++++++++++++++++++++++++------------ 1 file changed, 389 insertions(+), 158 deletions(-) diff --git a/vim/autoload/plug.vim b/vim/autoload/plug.vim index e07a8ca..95d8eab 100644 --- a/vim/autoload/plug.vim +++ b/vim/autoload/plug.vim @@ -18,7 +18,7 @@ " " Any valid git URL is allowed " Plug 'https://github.com/junegunn/vim-github-dashboard.git' " -" " Group dependencies, vim-snippets depends on ultisnips +" " Multiple Plug commands can be written in a single line using | separators " Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets' " " " On-demand loading @@ -28,6 +28,9 @@ " " Using a non-master branch " Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' } " +" " Using a tagged release; wildcard allowed (requires git 1.9.2 or above) +" Plug 'fatih/vim-go', { 'tag': '*' } +" " " Plugin options " Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' } " @@ -37,7 +40,7 @@ " " Unmanaged plugin (manually installed and updated) " Plug '~/my-prototype-plugin' " -" " Add plugins to &runtimepath +" " Initialize plugin system " call plug#end() " " Then reload .vimrc and :PlugInstall to install plugins. @@ -58,7 +61,7 @@ " More information: https://github.com/junegunn/vim-plug " " -" Copyright (c) 2016 Junegunn Choi +" Copyright (c) 2017 Junegunn Choi " " MIT License " @@ -95,6 +98,7 @@ let s:plug_buf = get(s:, 'plug_buf', -1) let s:mac_gui = has('gui_macvim') && has('gui_running') let s:is_win = has('win32') || has('win64') let s:nvim = has('nvim') && exists('*jobwait') && !s:is_win +let s:vim8 = has('patch-8.0.0039') && exists('*job_start') let s:me = resolve(expand(':p')) let s:base_spec = { 'branch': 'master', 'frozen': 0 } let s:TYPE = { @@ -128,7 +132,7 @@ function! plug#begin(...) endfunction function! s:define_commands() - command! -nargs=+ -bar Plug call s:Plug() + command! -nargs=+ -bar Plug call plug#() if !executable('git') return s:err('`git` executable not found. Most commands will not be available. To suppress this message, prepend `silent!` to `call plug#begin(...)`.') endif @@ -168,14 +172,22 @@ function! s:assoc(dict, key, val) let a:dict[a:key] = add(get(a:dict, a:key, []), a:val) endfunction -function! s:ask(message) +function! s:ask(message, ...) call inputsave() echohl WarningMsg - let proceed = input(a:message.' (y/N) ') =~? '^y' + let answer = input(a:message.(a:0 ? ' (y/N/a) ' : ' (y/N) ')) echohl None call inputrestore() echo "\r" - return proceed + return (a:0 && answer =~? '^a') ? 2 : (answer =~? '^y') ? 1 : 0 +endfunction + +function! s:ask_no_interrupt(...) + try + return call('s:ask', a:000) + catch + return 0 + endtry endfunction function! plug#end() @@ -191,8 +203,13 @@ function! plug#end() endif let lod = { 'ft': {}, 'map': {}, 'cmd': {} } - filetype off + if exists('g:did_load_filetypes') + filetype off + endif for name in g:plugs_order + if !has_key(g:plugs, name) + continue + endif let plug = g:plugs[name] if get(s:loaded, name, 0) || !has_key(plug, 'on') && !has_key(plug, 'for') let s:loaded[name] = 1 @@ -208,6 +225,7 @@ function! plug#end() endif call add(s:triggers[name].map, cmd) elseif cmd =~# '^[A-Z]' + let cmd = substitute(cmd, '!*$', '', '') if exists(':'.cmd) != 2 call s:assoc(lod.cmd, cmd, name) endif @@ -222,7 +240,9 @@ function! plug#end() if has_key(plug, 'for') let types = s:to_a(plug.for) if !empty(types) + augroup filetypedetect call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim') + augroup END endif for type in types call s:assoc(lod.ft, type, name) @@ -232,7 +252,7 @@ function! plug#end() for [cmd, names] in items(lod.cmd) execute printf( - \ 'command! -nargs=* -range -bang %s call s:lod_cmd(%s, "", , , , %s)', + \ 'command! -nargs=* -range -bang -complete=file %s call s:lod_cmd(%s, "", , , , %s)', \ cmd, string(cmd), string(names)) endfor @@ -240,8 +260,8 @@ function! plug#end() for [mode, map_prefix, key_prefix] in \ [['i', '', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']] execute printf( - \ '%snoremap %s %s:call lod_map(%s, %s, "%s")', - \ mode, map, map_prefix, string(map), string(names), key_prefix) + \ '%snoremap %s %s:call lod_map(%s, %s, %s, "%s")', + \ mode, map, map_prefix, string(map), string(names), mode != 'i', key_prefix) endfor endfor @@ -259,7 +279,7 @@ function! plug#end() syntax enable end else - call s:reload() + call s:reload_plugins() endif endfunction @@ -267,9 +287,13 @@ function! s:loaded_names() return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)') endfunction -function! s:reload() +function! s:load_plugin(spec) + call s:source(s:rtp(a:spec), 'plugin/**/*.vim', 'after/plugin/**/*.vim') +endfunction + +function! s:reload_plugins() for name in s:loaded_names() - call s:source(s:rtp(g:plugs[name]), 'plugin/**/*.vim', 'after/plugin/**/*.vim') + call s:load_plugin(g:plugs[name]) endfor endfunction @@ -289,7 +313,7 @@ endfunction function! s:git_version_requirement(...) if !exists('s:git_version') - let s:git_version = map(split(split(s:system('git --version'))[-1], '\.'), 'str2nr(v:val)') + let s:git_version = map(split(split(s:system('git --version'))[2], '\.'), 'str2nr(v:val)') endif return s:version_requirement(s:git_version, a:000) endfunction @@ -337,7 +361,12 @@ function! s:err(msg) echohl ErrorMsg echom '[vim-plug] '.a:msg echohl None - return 0 +endfunction + +function! s:warn(cmd, msg) + echohl WarningMsg + execute a:cmd 'a:msg' + echohl None endfunction function! s:esc(path) @@ -373,7 +402,7 @@ function! s:reorg_rtp() let s:middle = get(s:, 'middle', &rtp) let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])') - let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), 'isdirectory(v:val)') + let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), '!empty(v:val)') let rtp = join(map(rtps, 'escape(v:val, ",")'), ',') \ . ','.s:middle.',' \ . join(map(afters, 'escape(v:val, ",")'), ',') @@ -387,7 +416,20 @@ function! s:reorg_rtp() endfunction function! s:doautocmd(...) - execute 'doautocmd' ((v:version > 703 || has('patch442')) ? '' : '') join(a:000) + if exists('#'.join(a:000, '#')) + execute 'doautocmd' ((v:version > 703 || has('patch442')) ? '' : '') join(a:000) + endif +endfunction + +function! s:dobufread(names) + for name in a:names + let path = s:rtp(g:plugs[name]).'/**' + for dir in ['ftdetect', 'ftplugin'] + if len(finddir(dir, path)) + return s:doautocmd('BufRead') + endif + endfor + endfor endfunction function! plug#load(...) @@ -405,9 +447,7 @@ function! plug#load(...) for name in a:000 call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) endfor - if exists('#BufRead') - doautocmd BufRead - endif + call s:dobufread(a:000) return 1 endfunction @@ -443,9 +483,7 @@ function! s:lod(names, types, ...) endif call s:source(rtp, a:2) endif - if exists('#User#'.name) - call s:doautocmd('User', name) - endif + call s:doautocmd('User', name) endfor endfunction @@ -453,21 +491,19 @@ function! s:lod_ft(pat, names) let syn = 'syntax/'.a:pat.'.vim' call s:lod(a:names, ['plugin', 'after/plugin'], syn, 'after/'.syn) execute 'autocmd! PlugLOD FileType' a:pat - if exists('#filetypeplugin#FileType') - doautocmd filetypeplugin FileType - endif - if exists('#filetypeindent#FileType') - doautocmd filetypeindent FileType - endif + call s:doautocmd('filetypeplugin', 'FileType') + call s:doautocmd('filetypeindent', 'FileType') endfunction function! s:lod_cmd(cmd, bang, l1, l2, args, names) call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) + call s:dobufread(a:names) execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args) endfunction -function! s:lod_map(map, names, prefix) +function! s:lod_map(map, names, with_prefix, prefix) call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) + call s:dobufread(a:names) let extra = '' while 1 let c = getchar(0) @@ -476,10 +512,22 @@ function! s:lod_map(map, names, prefix) endif let extra .= nr2char(c) endwhile - call feedkeys(a:prefix . substitute(a:map, '^', "\", '') . extra) + + if a:with_prefix + let prefix = v:count ? v:count : '' + let prefix .= '"'.v:register.a:prefix + if mode(1) == 'no' + if v:operator == 'c' + let prefix = "\" . prefix + endif + let prefix .= v:operator + endif + call feedkeys(prefix, 'n') + endif + call feedkeys(substitute(a:map, '^', "\", '') . extra) endfunction -function! s:Plug(repo, ...) +function! plug#(repo, ...) if a:0 > 1 return s:err('Invalid number of arguments (1..2)') endif @@ -529,8 +577,7 @@ function! s:infer_properties(name, repo) let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git') let uri = printf(fmt, repo) endif - let dir = s:dirpath( fnamemodify(join([g:plug_home, a:name], '/'), ':p') ) - return { 'dir': dir, 'uri': uri } + return { 'dir': s:dirpath(g:plug_home.'/'.a:name), 'uri': uri } endif endfunction @@ -578,6 +625,7 @@ function! s:syntax() syn match plugRelDate /([^)]*)$/ contained syn match plugNotLoaded /(not loaded)$/ syn match plugError /^x.*/ + syn region plugDeleted start=/^\~ .*/ end=/^\ze\S/ syn match plugH2 /^.*:\n-\+$/ syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean hi def link plug1 Title @@ -597,6 +645,7 @@ function! s:syntax() hi def link plugUpdate Type hi def link plugError Error + hi def link plugDeleted Ignore hi def link plugRelDate Comment hi def link plugEdge PreProc hi def link plugSha Identifier @@ -660,7 +709,7 @@ function! s:switch_out(...) endfunction function! s:finish_bindings() - nnoremap R :silent! call retry() + nnoremap R :call retry() nnoremap D :PlugDiff nnoremap S :PlugStatus nnoremap U :call status_update() @@ -674,12 +723,22 @@ function! s:prepare(...) throw 'Invalid current working directory. Cannot proceed.' endif + for evar in ['$GIT_DIR', '$GIT_WORK_TREE'] + if exists(evar) + throw evar.' detected. Cannot proceed.' + endif + endfor + call s:job_abort() if s:switch_in() - normal q + if b:plug_preview == 1 + pc + endif + enew + else + call s:new_window() endif - call s:new_window() nnoremap q :if b:plug_preview==1pcendifbd if a:0 == 0 call s:finish_bindings() @@ -689,11 +748,10 @@ function! s:prepare(...) let s:plug_buf = winbufnr(0) call s:assign_name() - silent! unmap - silent! unmap L - silent! unmap o - silent! unmap X - setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap cursorline modifiable + for k in ['', 'L', 'o', 'X', 'd', 'dd'] + execute 'silent! unmap ' k + endfor + setlocal buftype=nofile bufhidden=wipe nobuflisted nolist noswapfile nowrap cursorline modifiable nospell setf vim-plug if exists('g:syntax_on') call s:syntax() @@ -712,15 +770,25 @@ function! s:assign_name() silent! execute 'f' fnameescape(name) endfunction +function! s:chsh(swap) + let prev = [&shell, &shellredir] + if !s:is_win && a:swap + set shell=sh shellredir=>%s\ 2>&1 + endif + return prev +endfunction + function! s:bang(cmd, ...) try + let [sh, shrd] = s:chsh(a:0) " FIXME: Escaping is incomplete. We could use shellescape with eval, " but it won't work on Windows. - let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd + let cmd = a:0 ? s:with_cd(a:cmd, a:1) : a:cmd let g:_plug_bang = '!'.escape(cmd, '#!%') execute "normal! :execute g:_plug_bang\\" finally unlet g:_plug_bang + let [&shell, &shellredir] = [sh, shrd] endtry return v:shell_error ? 'Exit status: ' . v:shell_error : '' endfunction @@ -748,7 +816,20 @@ function! s:do(pull, force, todo) let error = '' let type = type(spec.do) if type == s:TYPE.string - let error = s:bang(spec.do) + if spec.do[0] == ':' + call s:load_plugin(spec) + try + execute spec.do[1:] + catch + let error = v:exception + endtry + if !s:plug_window_exists() + cd - + throw 'Warning: vim-plug was terminated by the post-update hook of '.name + endif + else + let error = s:bang(spec.do) + endif elseif type == s:TYPE.funcref try let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged') @@ -759,6 +840,7 @@ function! s:do(pull, force, todo) else let error = 'Invalid hook type' endif + call s:switch_in() call setline(4, empty(error) ? (getline(4) . 'OK') \ : ('x' . getline(4)[1:] . error)) if !empty(error) @@ -812,6 +894,7 @@ function! s:retry() if empty(s:update.errors) return endif + echo call s:update_impl(s:update.pull, s:update.force, \ extend(copy(s:update.errors), [s:update.threads])) endfunction @@ -824,8 +907,20 @@ function! s:names(...) return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)')) endfunction +function! s:check_ruby() + silent! ruby require 'thread'; VIM::command("let g:plug_ruby = '#{RUBY_VERSION}'") + if !exists('g:plug_ruby') + redraw! + return s:warn('echom', 'Warning: Ruby interface is broken') + endif + let ruby_version = split(g:plug_ruby, '\.') + unlet g:plug_ruby + return s:version_requirement(ruby_version, [1, 8, 7]) +endfunction + function! s:update_impl(pull, force, args) abort - let args = copy(a:args) + let sync = index(a:args, '--sync') >= 0 || has('vim_starting') + let args = filter(copy(a:args), 'v:val != "--sync"') let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ? \ remove(args, -1) : get(g:, 'plug_threads', 16) @@ -834,10 +929,7 @@ function! s:update_impl(pull, force, args) abort \ filter(managed, 'index(args, v:key) >= 0') if empty(todo) - echohl WarningMsg - echo 'No plugin to '. (a:pull ? 'update' : 'install') . '.' - echohl None - return + return s:warn('echo', 'No plugin to '. (a:pull ? 'update' : 'install')) endif if !s:is_win && s:git_version_requirement(2, 3) @@ -859,13 +951,12 @@ function! s:update_impl(pull, force, args) abort endif if has('nvim') && !exists('*jobwait') && threads > 1 - echohl WarningMsg - echomsg 'vim-plug: update Neovim for parallel installer' - echohl None + call s:warn('echom', '[vim-plug] Update Neovim for parallel installer') endif - let python = (has('python') || has('python3')) && (!s:nvim || has('vim_starting')) - let ruby = has('ruby') && !s:nvim && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running')) + let use_job = s:nvim || s:vim8 + let python = (has('python') || has('python3')) && !use_job + let ruby = has('ruby') && !use_job && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running')) && threads > 1 && s:check_ruby() let s:update = { \ 'start': reltime(), @@ -875,7 +966,7 @@ function! s:update_impl(pull, force, args) abort \ 'pull': a:pull, \ 'force': a:force, \ 'new': {}, - \ 'threads': (python || ruby || s:nvim) ? min([len(todo), threads]) : 1, + \ 'threads': (python || ruby || use_job) ? min([len(todo), threads]) : 1, \ 'bar': '', \ 'fin': 0 \ } @@ -889,7 +980,7 @@ function! s:update_impl(pull, force, args) abort \ '--depth 1' . (s:git_version_requirement(1, 7, 10) ? ' --no-single-branch' : '') : '' " Python version requirement (>= 2.7) - if python && !has('python3') && !ruby && !s:nvim && s:update.threads > 1 + if python && !has('python3') && !ruby && !use_job && s:update.threads > 1 redir => pyv silent python import platform; print platform.python_version() redir END @@ -930,6 +1021,12 @@ function! s:update_impl(pull, force, args) abort endtry else call s:update_vim() + while use_job && sync + sleep 100m + if s:update.fin + break + endif + endwhile endif endfunction @@ -944,8 +1041,8 @@ function! s:update_finish() endif if s:switch_in() call append(3, '- Updating ...') | 4 - for [name, spec] in items(filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && (s:update.pull || has_key(s:update.new, v:key))')) - let pos = s:logpos(name) + for [name, spec] in items(filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && (s:update.force || s:update.pull || has_key(s:update.new, v:key))')) + let [pos, _] = s:logpos(name) if !pos continue endif @@ -953,8 +1050,17 @@ function! s:update_finish() call s:log4(name, 'Checking out '.spec.commit) let out = s:checkout(spec) elseif has_key(spec, 'tag') - call s:log4(name, 'Checking out '.spec.tag) - let out = s:system('git checkout -q '.s:esc(spec.tag).' 2>&1', spec.dir) + let tag = spec.tag + if tag =~ '\*' + let tags = s:lines(s:system('git tag --list '.string(tag).' --sort -version:refname 2>&1', spec.dir)) + if !v:shell_error && !empty(tags) + let tag = tags[0] + call s:log4(name, printf('Latest tag for %s -> %s', spec.tag, tag)) + call append(3, '') + endif + endif + call s:log4(name, 'Checking out '.tag) + let out = s:system('git checkout -q '.s:esc(tag).' 2>&1', spec.dir) else let branch = s:esc(get(spec, 'branch', 'master')) call s:log4(name, 'Merging origin/'.branch) @@ -962,23 +1068,29 @@ function! s:update_finish() \. (has_key(s:update.new, name) ? '' : ('&& git merge --ff-only origin/'.branch.' 2>&1')), spec.dir) endif if !v:shell_error && filereadable(spec.dir.'/.gitmodules') && - \ (has_key(s:update.new, name) || s:is_updated(spec.dir)) + \ (s:update.force || has_key(s:update.new, name) || s:is_updated(spec.dir)) call s:log4(name, 'Updating submodules. This may take a while.') let out .= s:bang('git submodule update --init --recursive 2>&1', spec.dir) endif - let msg = printf('%s %s: %s', v:shell_error ? 'x': '-', name, get(s:lines(out), -1, '')) + let msg = s:format_message(v:shell_error ? 'x': '-', name, out) if v:shell_error call add(s:update.errors, name) call s:regress_bar() - execute pos 'd _' + silent execute pos 'd _' call append(4, msg) | 4 elseif !empty(out) - call setline(pos, msg) + call setline(pos, msg[0]) endif redraw endfor - 4 d _ - call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && has_key(v:val, "do")')) + silent 4 d _ + try + call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && has_key(v:val, "do")')) + catch + call s:warn('echom', v:exception) + call s:warn('echo', '') + return + endtry call s:finish(s:update.pull) call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.') call s:switch_out('normal! gg') @@ -986,12 +1098,16 @@ function! s:update_finish() endfunction function! s:job_abort() - if !s:nvim || !exists('s:jobs') + if (!s:nvim && !s:vim8) || !exists('s:jobs') return endif for [name, j] in items(s:jobs) - silent! call jobstop(j.jobid) + if s:nvim + silent! call jobstop(j.jobid) + elseif s:vim8 + silent! call job_stop(j.jobid) + endif if j.new call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir)) endif @@ -999,59 +1115,88 @@ function! s:job_abort() let s:jobs = {} endfunction -" When a:event == 'stdout', data = list of strings -" When a:event == 'exit', data = returncode -function! s:job_handler(job_id, data, event) abort - if !s:plug_window_exists() " plug window closed - return s:job_abort() - endif +function! s:last_non_empty_line(lines) + let len = len(a:lines) + for idx in range(len) + let line = a:lines[len-idx-1] + if !empty(line) + return line + endif + endfor + return '' +endfunction - if a:event == 'stdout' - let complete = empty(a:data[-1]) - let lines = map(filter(a:data, 'len(v:val) > 0'), 'split(v:val, "[\r\n]")[-1]') - call extend(self.lines, lines) - let self.result = join(self.lines, "\n") - if !complete - call remove(self.lines, -1) - endif - " To reduce the number of buffer updates - let self.tick = get(self, 'tick', -1) + 1 - if self.tick % len(s:jobs) == 0 - call s:log(self.new ? '+' : '*', self.name, self.result) - endif - elseif a:event == 'exit' - let self.running = 0 - if a:data != 0 - let self.error = 1 - endif - call s:reap(self.name) - call s:tick() +function! s:job_out_cb(self, data) abort + let self = a:self + let data = remove(self.lines, -1) . a:data + let lines = map(split(data, "\n", 1), 'split(v:val, "\r", 1)[-1]') + call extend(self.lines, lines) + " To reduce the number of buffer updates + let self.tick = get(self, 'tick', -1) + 1 + if !self.running || self.tick % len(s:jobs) == 0 + let bullet = self.running ? (self.new ? '+' : '*') : (self.error ? 'x' : '-') + let result = self.error ? join(self.lines, "\n") : s:last_non_empty_line(self.lines) + call s:log(bullet, self.name, result) endif endfunction +function! s:job_exit_cb(self, data) abort + let a:self.running = 0 + let a:self.error = a:data != 0 + call s:reap(a:self.name) + call s:tick() +endfunction + +function! s:job_cb(fn, job, ch, data) + if !s:plug_window_exists() " plug window closed + return s:job_abort() + endif + call call(a:fn, [a:job, a:data]) +endfunction + +function! s:nvim_cb(job_id, data, event) dict abort + return a:event == 'stdout' ? + \ s:job_cb('s:job_out_cb', self, 0, join(a:data, "\n")) : + \ s:job_cb('s:job_exit_cb', self, 0, a:data) +endfunction + function! s:spawn(name, cmd, opts) - let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [], 'result': '', - \ 'new': get(a:opts, 'new', 0), - \ 'on_stdout': function('s:job_handler'), - \ 'on_exit' : function('s:job_handler'), - \ } + let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [''], + \ 'new': get(a:opts, 'new', 0) } let s:jobs[a:name] = job + let argv = add(s:is_win ? ['cmd', '/c'] : ['sh', '-c'], + \ has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd) if s:nvim - let argv = [ 'sh', '-c', - \ (has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd) ] + call extend(job, { + \ 'on_stdout': function('s:nvim_cb'), + \ 'on_exit': function('s:nvim_cb'), + \ }) let jid = jobstart(argv, job) if jid > 0 let job.jobid = jid else let job.running = 0 let job.error = 1 - let job.result = jid < 0 ? 'sh is not executable' : - \ 'Invalid arguments (or job table is full)' + let job.lines = [jid < 0 ? argv[0].' is not executable' : + \ 'Invalid arguments (or job table is full)'] + endif + elseif s:vim8 + let jid = job_start(argv, { + \ 'out_cb': function('s:job_cb', ['s:job_out_cb', job]), + \ 'exit_cb': function('s:job_cb', ['s:job_exit_cb', job]), + \ 'out_mode': 'raw' + \}) + if job_status(jid) == 'run' + let job.jobid = jid + else + let job.running = 0 + let job.error = 1 + let job.lines = ['Failed to start job'] endif else let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd] - let job.result = call('s:system', params) + let job.lines = s:lines(call('s:system', params)) let job.error = v:shell_error != 0 let job.running = 0 endif @@ -1066,7 +1211,9 @@ function! s:reap(name) endif let s:update.bar .= job.error ? 'x' : '=' - call s:log(job.error ? 'x' : '-', a:name, empty(job.result) ? 'OK' : job.result) + let bullet = job.error ? 'x' : '-' + let result = job.error ? join(job.lines, "\n") : s:last_non_empty_line(job.lines) + call s:log(bullet, a:name, empty(result) ? 'OK' : result) call s:bar() call remove(s:jobs, a:name) @@ -1085,24 +1232,31 @@ endfunction function! s:logpos(name) for i in range(4, line('$')) if getline(i) =~# '^[-+x*] '.a:name.':' - return i + for j in range(i + 1, line('$')) + if getline(j) !~ '^ ' + return [i, j - 1] + endif + endfor + return [i, i] endif endfor - return 0 + return [0, 0] endfunction function! s:log(bullet, name, lines) if s:switch_in() - let pos = s:logpos(a:name) - if pos > 0 - execute pos 'd _' - if pos > winheight('.') - let pos = 4 + let [b, e] = s:logpos(a:name) + if b > 0 + silent execute printf('%d,%d d _', b, e) + if b > winheight('.') + let b = 4 endif else - let pos = 4 + let b = 4 endif - call append(pos - 1, s:format_message(a:bullet, a:name, a:lines)) + " FIXME For some reason, nomodifiable is set after :d in vim8 + setlocal modifiable + call append(b - 1, s:format_message(a:bullet, a:name, a:lines)) call s:switch_out() endif endfunction @@ -1116,12 +1270,12 @@ endfunction function! s:tick() let pull = s:update.pull - let prog = s:progress_opt(s:nvim) + let prog = s:progress_opt(s:nvim || s:vim8) while 1 " Without TCO, Vim stack is bound to explode if empty(s:update.todo) if empty(s:jobs) && !s:update.fin - let s:update.fin = 1 call s:update_finish() + let s:update.fin = 1 endif return endif @@ -1135,16 +1289,16 @@ while 1 " Without TCO, Vim stack is bound to explode let has_tag = has_key(spec, 'tag') if !new - let error = s:git_validate(spec, 0) + let [error, _] = s:git_validate(spec, 0) if empty(error) if pull let fetch_opt = (has_tag && !empty(globpath(spec.dir, '.git/shallow'))) ? '--depth 99999999' : '' call s:spawn(name, printf('git fetch %s %s 2>&1', fetch_opt, prog), { 'dir': spec.dir }) else - let s:jobs[name] = { 'running': 0, 'result': 'Already installed', 'error': 0 } + let s:jobs[name] = { 'running': 0, 'lines': ['Already installed'], 'error': 0 } endif else - let s:jobs[name] = { 'running': 0, 'result': error, 'error': 1 } + let s:jobs[name] = { 'running': 0, 'lines': s:lines(error), 'error': 1 } endif else call s:spawn(name, @@ -1424,16 +1578,18 @@ class Plugin(object): self.write(Action.DONE, self.name, result[-1:]) def repo_uri(self): - cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url' + cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url' command = Command(cmd, self.args['dir'], G_TIMEOUT,) result = command.execute(G_RETRIES) return result[-1] def update(self): - match = re.compile(r'git::?@') - actual_uri = re.sub(match, '', self.repo_uri()) - expect_uri = re.sub(match, '', self.args['uri']) - if actual_uri != expect_uri: + actual_uri = self.repo_uri() + expect_uri = self.args['uri'] + regex = re.compile(r'^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$') + ma = regex.match(actual_uri) + mb = regex.match(expect_uri) + if ma is None or mb is None or ma.groups() != mb.groups(): msg = ['', 'Invalid URI: {0}'.format(actual_uri), 'Expected {0}'.format(expect_uri), @@ -1592,6 +1748,11 @@ function! s:update_ruby() end end + def compare_git_uri a, b + regex = %r{^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$} + regex.match(a).to_a.drop(1) == regex.match(b).to_a.drop(1) + end + require 'thread' require 'fileutils' require 'timeout' @@ -1693,9 +1854,8 @@ function! s:update_ruby() main = Thread.current threads = [] watcher = Thread.new { - while VIM::evaluate('getchar(1)') - sleep 0.1 - end + require 'io/console' # >= Ruby 1.9 + nil until IO.console.getch == 3.chr mtx.synchronize do running = false threads.each { |t| t.raise Interrupt } @@ -1725,7 +1885,7 @@ function! s:update_ruby() ok, result = if exists chdir = "#{cd} #{iswin ? dir : esc(dir)}" - ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url", nil, nil, nil + ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url", nil, nil, nil current_uri = data.lines.to_a.last if !ret if data =~ /^Interrupted|^Timeout/ @@ -1733,7 +1893,7 @@ function! s:update_ruby() else [false, [data.chomp, "PlugClean required."].join($/)] end - elsif current_uri.sub(/git::?@/, '') != uri.sub(/git::?@/, '') + elsif !compare_git_uri(current_uri, uri) [false, ["Invalid URI: #{current_uri}", "Expected: #{uri}", "PlugClean required."].join($/)] @@ -1779,9 +1939,15 @@ function! s:progress_bar(line, bar, total) endfunction function! s:compare_git_uri(a, b) - let a = substitute(a:a, 'git:\{1,2}@', '', '') - let b = substitute(a:b, 'git:\{1,2}@', '', '') - return a ==# b + " See `git help clone' + " https:// [user@] github.com[:port] / junegunn/vim-plug [.git] + " [git@] github.com[:port] : junegunn/vim-plug [.git] + " file:// / junegunn/vim-plug [/] + " / junegunn/vim-plug [/] + let pat = '^\%(\w\+://\)\='.'\%([^@/]*@\)\='.'\([^:/]*\%(:[0-9]*\)\=\)'.'[:/]'.'\(.\{-}\)'.'\%(\.git\)\=/\?$' + let ma = matchlist(a:a, pat) + let mb = matchlist(a:b, pat) + return ma[1:2] ==# mb[1:2] endfunction function! s:format_message(bullet, name, message) @@ -1799,10 +1965,7 @@ endfunction function! s:system(cmd, ...) try - let [sh, shrd] = [&shell, &shellredir] - if !s:is_win - set shell=sh shellredir=>%s\ 2>&1 - endif + let [sh, shrd] = s:chsh(1) let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd return system(s:is_win ? '('.cmd.')' : cmd) finally @@ -1818,7 +1981,7 @@ endfunction function! s:git_validate(spec, check_branch) let err = '' if isdirectory(a:spec.dir) - let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config remote.origin.url', a:spec.dir)) + let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url', a:spec.dir)) let remote = result[-1] if v:shell_error let err = join([remote, 'PlugClean required.'], "\n") @@ -1850,11 +2013,29 @@ function! s:git_validate(spec, check_branch) let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.', \ branch, a:spec.branch) endif + if empty(err) + let [ahead, behind] = split(s:lastline(s:system(printf( + \ 'git rev-list --count --left-right HEAD...origin/%s', + \ a:spec.branch), a:spec.dir)), '\t') + if !v:shell_error && ahead + if behind + " Only mention PlugClean if diverged, otherwise it's likely to be + " pushable (and probably not that messed up). + let err = printf( + \ "Diverged from origin/%s (%d commit(s) ahead and %d commit(s) behind!\n" + \ .'Backup local changes and run PlugClean and PlugUpdate to reinstall it.', a:spec.branch, ahead, behind) + else + let err = printf("Ahead of origin/%s by %d commit(s).\n" + \ .'Cannot update until local changes are pushed.', + \ a:spec.branch, ahead) + endif + endif + endif endif else let err = 'Not found' endif - return err + return [err, err =~# 'PlugClean'] endfunction function! s:rm_rf(dir) @@ -1865,15 +2046,23 @@ endfunction function! s:clean(force) call s:prepare() - call append(0, 'Searching for unused plugins in '.g:plug_home) + call append(0, 'Searching for invalid plugins in '.g:plug_home) call append(1, '') " List of valid directories let dirs = [] + let errs = {} let [cnt, total] = [0, len(g:plugs)] for [name, spec] in items(g:plugs) - if !s:is_managed(name) || empty(s:git_validate(spec, 0)) + if !s:is_managed(name) call add(dirs, spec.dir) + else + let [err, clean] = s:git_validate(spec, 1) + if clean + let errs[spec.dir] = s:lines(err)[0] + else + call add(dirs, spec.dir) + endif endif let cnt += 1 call s:progress_bar(2, repeat('=', cnt), total) @@ -1897,25 +2086,60 @@ function! s:clean(force) if !has_key(allowed, f) && isdirectory(f) call add(todo, f) call append(line('$'), '- ' . f) + if has_key(errs, f) + call append(line('$'), ' ' . errs[f]) + endif let found = filter(found, 'stridx(v:val, f) != 0') end endwhile - normal! G + 4 redraw if empty(todo) call append(line('$'), 'Already clean.') else - if a:force || s:ask('Proceed?') - for dir in todo - call s:rm_rf(dir) - endfor - call append(line('$'), 'Removed.') + let s:clean_count = 0 + call append(3, ['Directories to delete:', '']) + redraw! + if a:force || s:ask_no_interrupt('Delete all directories?') + call s:delete([6, line('$')], 1) else - call append(line('$'), 'Cancelled.') + call setline(4, 'Cancelled.') + nnoremap d :set opfunc=delete_opg@ + nmap dd d_ + xnoremap d :call delete_op(visualmode(), 1) + echo 'Delete the lines (d{motion}) to delete the corresponding directories' endif endif - normal! G + 4 + setlocal nomodifiable +endfunction + +function! s:delete_op(type, ...) + call s:delete(a:0 ? [line("'<"), line("'>")] : [line("'["), line("']")], 0) +endfunction + +function! s:delete(range, force) + let [l1, l2] = a:range + let force = a:force + while l1 <= l2 + let line = getline(l1) + if line =~ '^- ' && isdirectory(line[2:]) + execute l1 + redraw! + let answer = force ? 1 : s:ask('Delete '.line[2:].'?', 1) + let force = force || answer > 1 + if answer + call s:rm_rf(line[2:]) + setlocal modifiable + call setline(l1, '~'.line[1:]) + let s:clean_count += 1 + call setline(4, printf('Removed %d directories.', s:clean_count)) + setlocal nomodifiable + endif + endif + let l1 += 1 + endwhile endfunction function! s:upgrade() @@ -1962,7 +2186,7 @@ function! s:status() for [name, spec] in items(g:plugs) if has_key(spec, 'uri') if isdirectory(spec.dir) - let err = s:git_validate(spec, 1) + let [err, _] = s:git_validate(spec, 1) let [valid, msg] = [empty(err), empty(err) ? 'OK' : err] else let [valid, msg] = [0, 'Not found. Try PlugInstall.'] @@ -2026,7 +2250,6 @@ function! s:is_preview_window_open() wincmd p return 1 endif - return 0 endfunction function! s:find_name(lnum) @@ -2058,11 +2281,20 @@ function! s:preview_commit() return endif - execute 'pedit' sha - wincmd P - setlocal filetype=git buftype=nofile nobuflisted modifiable - execute 'silent read !cd' s:shellesc(g:plugs[name].dir) '&& git show --no-color --pretty=medium' sha - normal! gg"_dd + if exists('g:plug_pwindow') && !s:is_preview_window_open() + execute g:plug_pwindow + execute 'e' sha + else + execute 'pedit' sha + wincmd P + endif + setlocal previewwindow filetype=git buftype=nofile nobuflisted modifiable + try + let [sh, shrd] = s:chsh(1) + execute 'silent %!cd' s:shellesc(g:plugs[name].dir) '&& git show --no-color --pretty=medium' sha + finally + let [&shell, &shellredir] = [sh, shrd] + endtry setlocal nomodifiable nnoremap q :q wincmd p @@ -2148,7 +2380,7 @@ function! s:revert() setlocal modifiable normal! "_dap setlocal nomodifiable - echo 'Reverted.' + echo 'Reverted' endfunction function! s:snapshot(force, ...) abort @@ -2198,4 +2430,3 @@ endif let &cpo = s:cpo_save unlet s:cpo_save -