1

Is there a way search backward from the cursor for a line that doesn't contain a pattern?

For example, many of my lines match the regular expression ^ adding: \i\+. I want to find the first line above the current line which doesn't match this pattern, even if it is an empty line.

I don't want to use zero-width matching expressions because I don't want to have to specify a non-zero-width matching portion, which could cause the search to miss some qualifying lines.

I also avoided global commands, including the inverse global command :v, because I want to search backward from the cursor to the first occurrence.

| improve this question | | | | |
  • 1
    I initially thought to try :help pattern; maybe there's a negate-a-pattern syntax? \@! and \@<! looked promising, but I couldn't make them work (i.e., it's not as simple as \(pattern\)\@<!.). Only other thing to add is that ?pattern?-1 takes you to the line above a pattern match, so with hlsearch turned on you could just hold n until you're on an un-highlighted line. Or you could write a while loop to search backwards... – D. Ben Knoble Jan 19 at 0:24
  • I tried paging backward until I saw unhighlighted text, but it's such high volume that detection is unreliable. Other workarounds is to use global with inverse matching to prepend a unique string to nonmatching lines, then search backword for the string. I prefer not to mess with file, and not to assume uniqueness of a string. – user2153235 Jan 19 at 2:52
2

In your specific case, you can use a zero-width negative match and still have it work on empty lines.

I don't want to use zero-width matching expressions because I don't want to have to specify a non-zero-width matching portion, which could cause the search to miss some qualifying lines.

So you can use the ^ as the matching portion outside the zero-width negative lookahead.

This works:

?^\( adding: \i\+\)\@!

It will properly skip the adding: lines and it will stop on all other lines, including empty ones.

| improve this answer | | | | |
  • 1
    Thanks, filbranden. I ran into problems in the past assuming that positional anchors like ^ counted as matches, but I don't recall the environment (most likely Matlab). Thankfully, not vim. – user2153235 Jan 19 at 2:58
  • 1
    Damn. I fiddled for ages and couldn’t make this work. Nice job. – D. Ben Knoble Jan 19 at 3:59

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.