How to call external program from vim with visual marked text as param?
Call pattern: path-to-programm visual-marked-text filetype directory
Example: "C:\Programme\WinGrep\grep32.exe" search-pattern *.sql D:开发者_如何学Go\MyProject\build
You select the text and then type:
:!<program>
For instance, to sort the lines, select them and type:
:!sort
Note that this will replace the marked text with the output of the external program
The following Vim-script function can be used to do that.
function! FeedVisualCmd(cmdpat)
let [qr, qt] = [getreg('"'), getregtype('"')]
silent norm! gvy
let cmd = printf(a:cmdpat, shellescape(@"))
call setreg('"', qr, qt)
echo system(cmd)
if v:shell_error
echohl ErrorMsg | echom 'Failed to run ' . cmd | echohl NONE
endif
endfunction
It copies currently selected text to the unnamed register (see :help ""
),
runs given template of the command through the printf
function, and then
executes resulting command echoing its output.
If the only part of the command that changes is pattern, it is convenient to define a mapping,
vnoremap <leader>g :<c-u>call FeedVisualCmd('"C:\Programme\WinGrep\grep32.exe" %s *.sql D:\MyProject\build')<cr>
You can yank the selected text with y and paste it in the command line:
: ! cmd Ctrl-R " [other params]
To pass the the highlighted text as parameter you can use xargs on linux/unix (or cygwin on windows) like this:
:'<,'>!xargs -I {} path-to-program {} filetype directory
You enter this command by highlighting text in visual mode and then typing
:
, !
and typing rest of command.
{}
part of command will be replaced by the input to the xargs command which is the highlighted text. So path-to-program
will be executed with required parameters in proper order (selected text first).
精彩评论