Sending visual selection to an external program without affecting the buffer

What I am trying to achieve is to send visual selections to external programs without affecting the contents of the buffer.

Example

Let the next block of code represent the current buffer. Let [<] represent the beginning of the visual selection and [>] represent the end.

This is not a test 1
[<]This is not[>] a test 2
This is not a test 3
This is not a test 4

      

From this I would like to send this text to an external program. eg:

:<some vim command>!<some shell command>

      

Almost a solution?

The solution that almost works is:

:[range]w ! cat | <some shell command>

      

This works for dispatching things to linewise. For example:

:%w ! wc -l      # produces --> '4'
:2,3w ! wc -l    # produces --> '2'
:2w ! wc -w      # produces --> '6'

      

However, using the example buffer above:

:'<,'>w ! wc -w  # produces --> '6'

      

But I would like something that creates a "3" and does not affect the contents of the buffer.

Ideas?

+3


source to share


2 answers


The range is always equal to a string.

No matter what you do, every Ex command that accepts a range will always take '<

as its starting lineand '>

as the final string...

Passing a nonlinear selection to an external program is done as follows:

  • back up register contents
  • select selection in this register
  • pass the contents of this register to system()

    and output the result
  • restore register

Here it is in the 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

      

which you can use in the mapping like this:



xnoremap <F6> :call VisualCountWords()<CR>

      


Also using a cat is useless :

:[range]w ! cat | <some shell command>

      

it should be:

:[range]w ! <some shell command>

      

+8


source


select...
<esc>
:exe '!echo '.string(lh#visual#selection()).' | wc -w'

      

This seems to be a trick.



C lh#visual#selection()

from lh-vim-lib

+1


source







All Articles