How do I force magic regex mode for one substitute command in Vim?
Answer
:smagic/\vfoo.+/bar/
Explanation
If you prefer very-magic regex syntax but don't want to change global settings, :smagic is a targeted solution. It applies 'magic' behavior for a single substitute command, then leaves the rest of your session untouched. This is useful when you need a dense regex once, but still want your normal substitute habits afterward.
How it works
:smagicruns a substitute with magic mode enabled/\vfoo.+/is the search pattern (here using\vvery magic syntax)/bar/is the replacement
Because this is command-scoped, you avoid toggling options like set magic globally or re-escaping patterns when switching contexts.
Example
Given:
foo123
fooABC
zzz
Run:
:smagic/\vfoo.+/bar/
Result:
bar
bar
zzz
Only lines matching the regex are replaced, and magic handling applies only to this one command.
Tips
- Use
:snomagicfor the opposite behavior when you want mostly literal matching. - Add flags as usual, for example
:smagic/\vfoo.+/bar/gcfor global+confirm. - Keep
:smagicin mind when working with copied regexes from other tools where escaping differs.