2

I am looking for a way to highlight text on the line above a matched pattern. For example, my text may appear like this:

Some text
---------

What I want is to match on the underline dashes and then highlight the 'Some text' based on that. I can match the dashes and highlight them by matching any set of three dashes like this:

syn match dashes "\v^\-\-\-.*$"

But I am not sure how to also highlight the line above. Does anyone have any ideas on how to accomplish that?

3

This is fairly straightforward using the \zs and \ze atoms. I would do this:

syn match preDashes ".*\n\ze---"

Using the \ze atom here makes it so the matched text is only what matches before the \ze, but the whole pattern still must match.

As for style, I'd would highly recommend dropping the \v setting. In general, it's only useful when it makes the whole regex shorter or more readable. Which is easier to understand at first glance?

\v^\-\-\-.*$
^---.*$

For what it's worth, since .* is greedy, it will match as much text as possible, so the EOL ($) is not needed either. Putting all of this together, I would recommend:

syn match dashes "^---.*"
syn match preDashes ".*\n\ze---"

(Although I'm sure you can come up with a better name than preDashes)

  • Thanks! I am new to this and now realize that I was making it much more difficult than I needed to. This was a great answer! – JGP Feb 25 '17 at 13:01
  • @jgp I'm glad you found it useful! – DJMcMayhem Feb 25 '17 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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