VIM: Send visual block to external command

不打扰是莪最后的温柔 提交于 2020-06-14 08:35:50

问题


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 
endfunction

that 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!