Reputation: 785
I recently added the following code in the .vimrc:
" Runs python inside vim
autocmd FileType python nnoremap <buffer> <F9> :exec '!clear; python' shellescape(@%, 1)<cr>
which allows me to run the entire python script from inside vim when pressed the F9 key. Nevertheless, several times I do not want to run the entire python script but just one line or even a block of lines. I googled in searching for these behavior but could not find any solution that worked, at least for me.
Someone can help me on this?
Thanks
Upvotes: 0
Views: 793
Reputation: 728
First you should make a function to get your visually selected text. I brought it from https://stackoverflow.com/a/6271254/3108885:
function! s:GetVisualSelection()
let [lnum1, col1] = getpos("'<")[1:2]
let [lnum2, col2] = getpos("'>")[1:2]
let lines = getline(lnum1, lnum2)
let lines[-1] = lines[-1][:col2 - (&selection == 'inclusive' ? 1 : 2)]
let lines[0] = lines[0][col1 - 1:]
return join(lines, "\n")
endfunction
Then, add an autocmd
for Visual mode.
autocmd FileType python vnoremap <buffer> <F9> :<C-U>exec '!clear; python -c' shellescape(<SID>GetVisualSelection(), 1)<CR>
Note that <C-U>
is for cleaning '<,'>
things when :
is pressed on Visual mode. Also we use python -c
to pass a program as a string.
Upvotes: 1