JAVH
JAVH

Reputation: 223

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:\MyProject\build

Upvotes: 3

Views: 3074

Answers (4)

ib.
ib.

Reputation: 28934

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>

Upvotes: 4

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

You can yank the selected text with y and paste it in the command line:

: ! cmd Ctrl-R " [other params]

Upvotes: 4

Paweł Nadolski
Paweł Nadolski

Reputation: 8473

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).

Upvotes: 0

Nathan Fellman
Nathan Fellman

Reputation: 127428

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

Upvotes: 5

Related Questions