rnso
rnso

Reputation: 24545

Multiple possible find-replace in Gvim

I want to create a command or function to combine multiple finds and replaces. I have tried following command:

command MyFR %s/first/1st/g | %s/second/2nd/g | %s/third/3rd/g

It works but stops midway if no 'first' or 'second' is found. The error is:

E486: Pattern not found: <pattern>

How can I make this command work for 'second' and 'third' to be replaced, even if there is no 'first' in text? Thanks for your help.

Upvotes: 4

Views: 473

Answers (1)

user852573
user852573

Reputation: 1750

You could add the e flag to each of your substitution command, which is described in :h :s_flags:

[e]     When the search pattern fails, do not issue an error message and, in
    particular, continue in maps as if no error occurred.  This is most
    useful to prevent the "No match" error from breaking a mapping.  Vim
    does not suppress the following error messages, however:
        Regular expressions can't be delimited by letters
        \ should be followed by /, ? or &
        No previous substitute regular expression
        Trailing characters
        Interrupted

It would give:

com! MyFR %s/first/1st/ge | %s/second/2nd/ge | %s/third/3rd/ge

Another solution would be to merge all substitutions into a single one:

com! MyFR %s/\vfirst|second|third/\={'first': '1st', 'second': '2nd', 'third': '3rd'}[tolower(submatch(0))]/g

This time, in the replacement part, instead of using a literal string, you would use an expression (see :h s/\=). Here, the expression is a given value of a dictionary.

The keys of the dictionary are all your possible matched texts, and the values are their replacements.

The value you retrieve from the dictionary is tolower(submatch(0)) which evaluates into the matched text (see :h submatch()), normalized in its lowercase version (all uppercase characters are turned into their lowercase counterpart through tolower()).

Upvotes: 4

Related Questions