So I mainly use Vim for work in python at the moment, and I've recently discovered 2 great strategies for running code externally and bringing it back into Vim. The first is the use of a function called Shell
from the Vim pages:
function! s:ExecuteInShell(command)
let command = join(map(split(a:command), 'expand(v:val)'))
let winnr = bufwinnr('^' . command . '$')
silent! execute winnr < 0 ? 'botright new ' . fnameescape(command) : winnr . 'wincmd w'
setlocal buftype=nowrite bufhidden=wipe nobuflisted noswapfile nowrap number
echo 'Execute ' . command . '...'
silent! execute 'silent %!'. command
silent! execute 'resize ' . line('$')
silent! redraw
silent! execute 'au BufUnload <buffer> execute bufwinnr(' . bufnr('#') . ') . ''wincmd w'''
silent! execute 'nnoremap <silent> <buffer> <LocalLeader>r :call <SID>ExecuteInShell(''' . command . ''')<CR>'
echo 'Shell command ' . command . ' executed.'
endfunction
command! -complete=shellcmd -nargs=+ Shell call s:ExecuteInShell(<q-args>)
which allows one to run something like :Shell nosetests
and see the results in a new window that is:
- Persistent (no "hit enter" to make it go away)
- Uses a temporary buffer (not a temp file)
- And most importantly, running the command again just refreshes the current window, it doesn't open a new one every time.
Then I use this little gem as well:
:'<,'>:w !python
which let's me use a selection from my current buffer, but which goes away after hitting enter.
What I can't figure out how to do is combine the two. What I want is:
- All the window properties of the
Shell
command, but - The ability to run it from a selection on the screen.
- EDIT: do this for selected python code, not bash code. The function already does regular shell commands. Instead of using Shell to run
$ python script.py
I want it to run code directly like:'<,'>:w !python
would.
I don't know enough Vimscript to modify Shell
to include a selection, and I can't for the life of me figure out how to at least put :'<,'>:w !python
into it's own window without the use of a temporary file, which seems unnecessary to me. Any ideas? Tips?