问题
How do I send a visual block to an external command?
I select my block using Ctrl-q and then press !program_name but vim sends the entire lines rather than the selected text blocks.
I'm using gvim in Windows 10.
回答1:
Vim always send the whole line to external commands, but you can do that using the function of the answer of romainl in this question:
Sending visual selection to external program without affecting the buffer
Passing a non-linewise selection to an external program is done like this:
- backup the content of a register
- yank the selection in that register
- pass the content of that register to system() and output the result
- restore the register
Here it is, in a function:
function! VisualCountWords() range let n = @n silent! normal gv"ny echo "Word count:" . system("echo '" . @n . "' | wc -w") let @n = n " bonus: restores the visual selection normal! gv endfunctionthat you can use in a mapping like this:
xnoremap <F6> :call VisualCountWords()<CR>
回答2:
The Ex commands are line-based, whereas blockwise visual mode is a Vim extension. That explains the feature mismatch.
The vis.vim plugin provides a :B command that allows you to send the actual selected block to an Ex command. It also works with :!, so you can do things like this:
:'<,'>B !tr 'a-z' 'A-Z'
来源:https://stackoverflow.com/questions/40072761/vim-send-visual-block-to-external-command