2

This question has been asked here, but it wasn't the main problem. Since the main problem is solved, and the more general question remains, I feel it deserves to be posted on its own.

Is it possible in Vim to inject some logic like conditional statements, manipulating on regex back references? The example for this in Emacs could be:

C-M-% \(^.*\)\(linear-gradient(\)\(to right\|to bottom\)\(.*$\) <RET>
\& C-q C-j
\1-prefix-\2\,(if (equal "to right" \3) "left" "top")\4

This one helped me about a year+ ago to refactor some huge scary HTML code that had a much of inline CSS. Sorry that I can't give an example of it.

The concept explained well here.

So there is a way to inject Emacs Lisp logic when substituting regular expressions, thus making possible to do fast conditional manipulations on large texts with some regularity in them - without writing standalone scripts. It seems to be a nice feature.

Is there some similar capability in Vim?

Thanks!

Community
  • 1
  • 1
a1111exe
  • 641
  • 4
  • 18

1 Answers1

4

You can use any Vimscript expression on the replacement part of :s via :help sub-replace-expression. The only difference is that backreferences become submatch(1) instead of \1, and to concatenate those with other expression parts, you have to use expr1 . expr2.

Example

:s/\<...\>/\=submatch(0) == 'foo' ? 'bar' : toupper(submatch(0))/g
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324