Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply vim user defined command to visual selection or all

Tags:

vim

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.

like image 460
highsciguy Avatar asked Nov 28 '25 01:11

highsciguy


2 Answers

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
like image 188
ronakg Avatar answered Nov 30 '25 22:11

ronakg


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.

like image 31
romainl Avatar answered Nov 30 '25 22:11

romainl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!