Domanda

I'm trying to use Tablular to match against the first assignment operator in a line, ignoring other operators in the line that have an = in it (e.g. ==, <=, >=, /=, !=, ~=, etc.)

The best I've gotten so far is the following:

:Tabularize /\zs[=<>/!]\@<!=[=<>/!]\@!\ze/<CR>

What this does is match against an =, making sure that on either side of it are not one of =, <, >, / or !.

This works if I only have one assignment in the line, e.g.:

one = uno
two = dos
three = tres

becomes

one   = uno
two   = dos
three = tres

However, if I have more than one assignment in the line, e.g.:

one = uno = alpha
two = dos = beta
three = tres = gamma

then I end up with (note the aligned second set of equal signs):

one   = uno  = alpha
two   = dos  = beta
three = tres = gamma

where as what I really want is just (note second set of equal signs not aligned):

one   = uno = alpha
two   = dos = beta
three = tres = gamma

What I'm really after is for Tablular to match only the first assignment operator above, taking care to not match other operators that have = also in it.

What do I have to do to the pattern /\zs[=<>/!]\@<!=[=<>/!]\@!\ze/ to make this happen?

È stato utile?

Soluzione

I think you just need to add a .* to the end of the regex (instead of \ze)

:Tabularize /\zs[=<>/!]\@<!=[=<>/!]\@!.*/

To just include the rest of the line as part of the separator.

Altri suggerimenti

There are a few common :Tabular idioms that come in handy:

  • using \zs to start a match at a certain point in a pattern
  • ending a pattern with .* to consume the rest of the line to prevent more matches

I applaud the use of negative look-aheads and look-behinds however I think we can make this a bit more simple:

:Tabularize/\s\zs=\s.*/

This assume you have a space on either side of your operators (assuming you have nicely formatted code)

For more help see:

:h /\zs
:h tabular-walkthrough

There is an example in the "walkthrough" section of :help tabular:

But, what if you only wanted to act on the first comma on the line, rather than
all of the commas on the line?  Let's say we want everything before the first
comma right aligned, then the comma, then everything after the comma left
aligned:

    abc,def,ghi
    a,b
    a,b,c

    :Tabularize /^[^,]*\zs,/r0c0l0

    abc,def,ghi
      a,b
      a,b,c

Here, we used a Vim regex that would only match the first comma on the line.
It matches the beginning of the line, followed by all the non-comma characters
up to the first comma, and then forgets about what it matched so far and
pretends that the match starts exactly at the comma.

that you can easily adapt to your needs:

:Tabularize /^[^=]*\zs=
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top