I'm not sure of the right language here, but I need to modify all occurrences of a pattern (specifically &) that occur inside a pair of delimiters while leaving unmodified the pattern if it is 'outside all open delimiters'. With apologies, here's a complicated real world example (I'm concerned that an answer to a simplified example might exploit special features of the example that won't hold in general.)

In the following line, the first & is outside all delimiters, but the second one is located to the right of a { and to the left of the matching }. I need to modify the second one but not the first.

 \begin{array}{l l}E\left( {\tau |k} \right) & =  E\left[ {\left. {\left( {\frac{1}{{n - 2d}}\sum\nolimits_{i  =  1}^n {{Z_i}} } \right)\tau } \right|k} \right]  = \frac{1}{{n - 2d}}\sum\nolimits_{i  & =  1}^n {E\left( {{Z_i}\tau |k} \right)} \\

Here's an even nastier example.

\left| {E\left( {X|A} \right)} \right| & =  \left| {E\left( {{q_2}|{q_1} < {q_2}  <  {q_3}  <  {q_4}} \right)} \right| & =  \frac{{\left| {E\left( {{q_2}{I_{{q_1} & <  {q_2} & <  {q_3} & <  {q_4}}}} \right)} \right|}}{{P\left( A \right)}}

Again, the first and second &'s are outside of any matching delimiters, but the third, fourth and fifth are enclosed in matching delimiters, and need to be modified.

Thanks very much for any advice, and apologies for the persnickety nature of this horrible problem.

1 Answer 1


Many Vims provide support for some scripting languages (Perl, Ruby, Python). if your vim has Perl support (some distributions don't provide it) you can use :perl perl-command and :perldo perl-command.

In the following we are going to count the curly brackets level (c) and add it to each & (&-c).

:perl $a{'{'}=1; $a{'}'}=-1; $c=0
:perldo s/([{}&])/if($1 eq '&'){"$1-$c"}else{$c += $a{$1}; "$1"}/ge

1) initialization of c and a ( curly brackets delta)

2) (using perl s/regexp/perl-exp/eval),
...for each occurence of { } recalculate c; for each &, show c. We get:

\left| {E\left( {X|A} \right)} \right| &-0 =  \left| {E\left( {{q_2}|{q_1} <
{q_2}  <  {q_3}  <  {q_4}} \right)} \right| &-0 =  \frac{{\left| {E\left(
{{q_2}{I_{{q_1} &-6 <  {q_2} &-6 <  {q_3} &-6 <  {q_4}}}} \right)} 
\right|}}{{P\left( A \right)}}

Now it is easy to see what are the "bad &" (s/&-[^0]/BAD_ones/g)

  • Miraculous, thanks so much. That's amazingly powerful. I needed install vim.gtk on my ubuntu machine to get perl support. Is there any reason not to use vim.gtk as my default editor?
    – Leo Simon
    Commented Oct 1, 2015 at 23:18

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.