highsciguy
highsciguy

Reputation: 2647

Apply vim user defined command to visual selection or all

I have a user defined command in my .vimrc

command! RemoveOutput :'<,'> ! grep -v 'OUT'

But that is obviously applied to the visual selection only if it was selected before and deselected again. Instead I would like to apply it to the present visual selection or the whole file if there is no such selection. How would I achieve that? Note that I am aware that I do not need to use grep here. Please think of it as a placeholder for a more complicated shell command.

Upvotes: 3

Views: 840

Answers (2)

romainl
romainl

Reputation: 196876

This is the syntax you need:

command! -range=% Foo execute <line1> . "," . <line2> . "!command"

Note the -range argument. The command above will work on the current visual selection, an arbitrary range or on the whole buffer if there's no visual selection or arbitrary range.

See :help :command-nargs.

Upvotes: 1

ronakg
ronakg

Reputation: 4212

You need to pass range to your command so that it can operate on a range of lines.

command! -range=% RemoveOutput :<line1>,<line2> ! grep -v 'OUT'

Read more at the vim documentation for commands.

LINE RANGE

Some commands take a range as their argument.  To tell Vim that you are
defining such a command, you need to specify a -range option.  The values for
this option are as follows:

    -range      Range is allowed; default is the current line.
    -range=%    Range is allowed; default is the whole file.
    -range={count}  Range is allowed; the last number in it is used as a
            single number whose default is {count}.

When a range is specified, the keywords <line1> and <line2> get the values of
the first and last line in the range.  For example, the following command
defines the SaveIt command, which writes out the specified range to the file
"save_file":

    :command -range=% SaveIt :<line1>,<line2>write! save_file

Upvotes: 6

Related Questions