How do I write a command in vim to run multiple commands?

I’ve written some commands that perform common functions by placing the following in my .vimrc files:

command! FixWhitespace %s/ +$//g
command! FixCommas %s/,S@=/, /g

Now I’d like to create a 3rd command that runs both of these, but the following doesn’t work:

command! Fix FixWhitespace|FixCommas

When I run :Fix from within vim I get the following message:

E488: Trailing characters: FixWhitespace|FixCommas

I’m not sure how this error message relates to what I’ve done, but I’m obviously not doing something right!

I’m using Vim 7.4.

Asked By: quant


You need to tell vim using command! -bar that a command can be followed by another command with the pipe symbol |:

command! -bar FixWhitespace %s/s+$//e
command! FixCommas %s/,S@=/, /ge

Now this is OK:

command! Fix FixWhitespace|FixCommas

but this isn’t:

command! Fix FixCommas|FixWhitespace

See :h command-bar for more details.

The error message E488: Trailing characters: FixWhitespace|FixCommas is vim’s way of telling you that it didn’t expect anything following the FixWhitespace command. See :h E488.

As an aside, your FixWhitespace command doesn’t need the g flag since the pattern can match at most once on each line. I’d also set the e flag to suppress the annoying error message. See :h s_flags.

Answered By: gaffer
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.