Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gvim: passing the visually-selected text to the command line

I use gvim to store recipes of commands that I will execute, depending on output. Currently, I select the text in gvim and paste the commands into a terminal console, but I bet there's a way I can pass the visually selected range into a command-line for execution.

like image 878
Screenack Avatar asked Jan 18 '11 14:01

Screenack


2 Answers

Assuming you mean the Vim command line:

(if you mean the OS command line, see below).

For parts of lines (i.e. no end of line character), you could do something like this:

" Visually select lines, then:
y:<C-R>"<ENTER>

where <C-R> means press Ctrl+R. The y 'yanks' the selected text, the : enters command mode, <C-R>" pulls the contents of the " (last yanked text) register onto the command line and <ENTER> (obviously) runs the command.


If you want to do line-wise stuff, it's a bit more complicated (as the command line doesn't like ^Ms in the command). I'd recommend something like this in your vimrc:

function! RunCommands()
    exe getline('.')
endfunction
command -range RunCommands <line1>,<line2>call RunCommands()
vmap ,r :RunCommands<CR>

Select the lines (after restarting vim) and press ,r.


Another way that you may find useful is to copy the lines you want, hit q: to open the command line window and paste the lines you want into there and then move the cursor over the line you want and press ENTER. This has the advantage that you can edit the command before pressing ENTER. It'll only run one command at a time.

If you mean an (e.g.) Windows or Linux command line:

Use the function I listed above, but instead of:

exe getline('.')

use

call system(getline('.'))

or, if you want to see the result:

echo system(getline('.'))

or

echomsg system(getline('.'))

For more information:

:help :echo
:help :echomsg
:help :messages

:help :vmap
:help :command-range
:help :command
:help :function

:help c_CTRL-R
:help :exe
:help getline()
:help system()
like image 167
DrAl Avatar answered Nov 15 '22 15:11

DrAl


If you are using the vim GUI, you can do set guioptions+=a. This way, any highlighted text inside gvim in visual mode gets pasted to a clipboard.

like image 34
Benoit Avatar answered Nov 15 '22 15:11

Benoit