The doc about the substitute function :h substitute() tells us:

[...] the matching with {pat} is always done like the 'magic' option is set [...]

That's cool but what if I need to use substitute() with another mode like say, verymagic or verynomagic? Is there a way to modify this behavior?

I guess a flag won't help me since the same doc topic says:

[...] When {flags} is "g", all matches of {pat} in {expr} are replaced. Otherwise {flags} should be "".

So here are my two questions:

  • Is it possible to modify the magic mode used by substitute()?
  • If it is not possible, what is the most elegant/efficient way to perform a substitution on a string contained in a variable with another magic mode?

1 Answer 1


You can do this by including escapes in the pattern that change the magic mode.

From :help pattern

Use of "\m" makes the pattern after it be interpreted as if 'magic' is set, ignoring the actual value of the 'magic' option. Use of "\M" makes the pattern after it be interpreted as if 'nomagic' is used.

Use of "\v" means that in the pattern after it all ASCII characters except '0'-'9', 'a'-'z', 'A'-'Z' and '_' have a special meaning. "very magic"

Use of "\V" means that in the pattern after it only the backslash and the terminating character (/ or ?) has a special meaning. "very nomagic"

  • Damn I probably don't have all of my head today, I was trying to add the mode in the {expr} part instead of the {pat} part...
    – statox
    Oct 11, 2016 at 14:29
  • Can you provide an example of this? For me :echo substitute("foo123", "\v.", "x", "g") returns foo123
    – Wolfie
    Oct 11, 2016 at 14:45
  • 6
    @Wolfie, it should either be "\\v." (double quotes) or '\v' (single quotes).
    – xaizek
    Oct 11, 2016 at 14:53
  • 5
    Which is why just about any regexp in Vim that is supposed to be used on more than one computer has to start with either \m, \v, or \V. There's a similar problem with case sensitivity, where ignorecase and smartcase boobytrap most command / functions / whatever that use regexps, to the effect that you also need to specify either \C or \c everywhere where you care about case. This also makes things interesting for multibyte encodings, but that's from another story. Ah, the fractal beauty of design mistakes in Vim. :)
    – lcd047
    Oct 11, 2016 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.