Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send visual block to external command

Tags:

vim

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.

like image 293
user2001487 Avatar asked Mar 11 '23 21:03

user2001487


2 Answers

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>

like image 41
Vinícius Souza Avatar answered Mar 18 '23 15:03

Vinícius Souza


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'
like image 162
Ingo Karkat Avatar answered Mar 18 '23 15:03

Ingo Karkat