在 vim 中运行代码块 [英] Running blocks of code inside vim
问题描述
我最近在 .vimrc 中添加了以下代码:
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>
它允许我在按下 F9 键时从 vim 内部运行整个 python 脚本.尽管如此,有几次我不想运行整个 python 脚本,而只想运行一行甚至一行行.我用谷歌搜索这些行为,但找不到任何有效的解决方案,至少对我来说是这样.
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.
有人可以帮助我吗?
谢谢
推荐答案
首先,您应该创建一个函数来获取视觉上选择的文本.我从 https://stackoverflow.com/a/6271254/3108885 带来:
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
然后,为可视模式添加一个 autocmd
.
Then, add an autocmd
for Visual mode.
autocmd FileType python vnoremap <buffer> <F9> :<C-U>exec '!clear; python -c' shellescape(<SID>GetVisualSelection(), 1)<CR>
注意
是为了在可视模式下按下 :
时清理 '<,'>
东西.我们也使用 python -c
将程序作为字符串传递.
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.
这篇关于在 vim 中运行代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!