这是一个可以用来执行任意 shell 命令并在新窗口中显示它们的输出的函数(你可以把它放在你的 _vimrc 中):
let s:lastcmd = ''
function! s:RunShellCommand(cmdline, bang)
" Support for repeating last cmd with bang:
let _ = a:bang != '' ? s:lastcmd : a:cmdline == '' ? '' : join(map(split(a:cmdline), 'expand(v:val)'))
if _ == ''
return
endif
let s:lastcmd = _
let bufnr = bufnr('%')
let winnr = bufwinnr(_)
" You can position the new window whenever you want, I chose below + right:
silent! execute winnr < 0 ? 'belowright new ' . fnameescape(_) : winnr . 'wincmd w'
" I could set buftype=nofile, but then no switching back and forth buffers.
" The results are presented just for viewing, not editing, modify at will:
setlocal buftype=nowrite bufhidden=wipe nobuflisted noswapfile wrap number
setlocal modifiable
silent! :%d
" Useful for debugging, if you encounter issues with fnameescape():
call setline(1, 'You entered: ' . a:cmdline)
call setline(2, 'Expanded to: ' . _)
call append(line('$'), substitute(getline(2), '.', '=', 'g'))
silent execute '$read !' . _
silent! execute 'autocmd BufUnload <buffer> execute bufwinnr(' . bufnr . ') . ''wincmd w'''
" If resizing is unwanted for commands with too much output, remove this line:
silent! execute 'autocmd BufEnter <buffer> execute ''resize '' . line(''$'')'
" You can use <localleader>r to re-execute the last command:
silent! execute 'nnoremap <silent> <buffer> <localleader>r :call <SID>RunShellCommand(''' . _ . ''', '''')<CR>'
execute 'resize ' . line('$')
setlocal nomodifiable
1
endfunction " RunShellCommand(cmdline)
command! -complete=shellcmd -nargs=* -bang Shell call s:RunShellCommand(<q-args>, '<bang>')
像这样使用:
:Shell gcc -ggdb -o test test.c && ./test