1

I want to execute a shell command in a new buffer from within Vimscript, but do not want to move the focus (cursor) out of the current active buffer.

Currently I'm using the following function:

function! s:ExecuteInShell(command, bang)
    " http://vim.wikia.com/wiki/Display_output_of_shell_commands_in_new_window
    let _ = a:bang != '' ? s:_ : a:command == '' ? '' : join(map(split(a:command), 'expand(v:val)'))
    if (_ != '')
        let s:_ = _
        let bufnr = bufnr('%')
        let winnr = bufwinnr('^' . _ . '$')
        silent! execute  winnr < 0 ? 'belowright new ' . fnameescape(_) : winnr . 'wincmd w'
        setlocal buftype=nowrite bufhidden=wipe nobuflisted noswapfile wrap number
        silent! :%d
        let message = 'Execute ' . _ . '...'
        call append(0, message)
        echo message
        silent! 2d | resize 1 | redraw
        silent! execute 'silent! %!'. _
        silent! execute 'resize ' . line('$')
        silent! execute 'syntax on'
        silent! execute 'autocmd BufUnload <buffer> execute bufwinnr(' . bufnr . ') . ''wincmd w'''
        silent! execute 'autocmd BufEnter <buffer> execute ''resize '' .  line(''$'')'
        silent! execute 'nnoremap <silent> <buffer> <CR> :call <SID>ExecuteInShell(''' . _ . ''', '''')<CR>'
        silent! execute 'nnoremap <silent> <buffer> <LocalLeader>r :call <SID>ExecuteInShell(''' . _ . ''', '''')<CR>'
        silent! execute 'nnoremap <silent> <buffer> <LocalLeader>g :execute bufwinnr(' . bufnr . ') . ''wincmd w''<CR>'
        nnoremap <silent> <buffer> <C-W>_ :execute 'resize ' . line('$')<CR>
        silent! syntax on
    endif
endfunction

It works great but moves the focus to the newly created buffer. Can you please tell me how to modify it so the focus stays on the current buffer?

1 Answer 1

2

Try adding:

wincmd p

at the end of the function.

This is the equivalent of Ctrl-w p (go to previous window).

See :h wincmd (and the previous topic, some lines above).

2
  • great, thank you! can you please explain what exactly wincmd p does?
    – muffel
    Commented Jul 9, 2015 at 7:56
  • 1
    yw. I edited the answer to add an explanation.
    – VanLaser
    Commented Jul 9, 2015 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.