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 on Windows 10.
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 endfunction
that you can use in a mapping like this:
xnoremap <F6> :call VisualCountWords()<CR>
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With