Many possible substitute finds in Gvim

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

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

It works, but stops halfway if "first" or "second" is not found. Error:

E486: Pattern not found: <pattern>

How can I make this command work for the “second” and “third” for replacement, even if there is no “first” in the text? Thank you for your help.

+4
source share
1 answer

You can add a flag eto each of your substitution commands, 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

This would give:

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

Another solution would be to combine all the permutations into one:

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

(. :h s/\=). .

- , - .

, , tolower(submatch(0)), (. :h submatch()), ( tolower()).

+4

Source: https://habr.com/ru/post/1683094/


All Articles