将可视块发送到外部命令

5

如何将可视块发送到外部命令?

我使用 Ctrl-q 选择我的块,然后按下 !*program_name*,但 Vim 发送的是整行而不是所选文本块。

我在 Windows 10 上使用 gVim。


2
请参见http://vi.stackexchange.com/questions/7388/replace-selection-with-output-of-external-command,包括对最佳答案的顶部评论。 - Sundeep
2个回答

4

Ex命令是基于行的,而块状可视模式是Vim的扩展。这就解释了功能不匹配的原因。

vis.vim插件提供了一个:B命令,允许您将实际选择的块发送到一个Ex命令。它也可以与:!一起使用,所以您可以做类似下面的事情:

:'<,'>B !tr 'a-z' 'A-Z'

我说得太早了。这个插件更接近我想要的,但我想对块选择中的所有行进行排序。我正在使用的外部排序命令允许我按版本号进行排序(sort -V)。类似于Vissort但具有更多的灵活性。 - user2001487
如果你只想排序选定的文本(并将每行前后的内容保持不变),那么vis.vim就是解决方案。如果你想对整行进行排序,但是基于选择的列,请使用 :!sort ...,但要指定字段(通过 --key=...)。 - Ingo Karkat

3

Vim总是将整行发送给外部命令,但您可以使用romainl在此问题的答案中提供的功能来执行此操作:

将视觉选择发送到外部程序而不影响缓冲区

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>


1
谢谢。不幸的是,由于设计的原因,我将无法做我想做的事情。我需要能够发送文本块并具有外部命令或脚本的灵活性。哦,好吧。 - user2001487

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接