4

From :help ordinary-atom:

      ordinary atom ~
      magic   nomagic   matches ~
|/^|    ^   ^   start-of-line (at start of pattern) |/zero-width|
|/\^|   \^  \^  literal '^'
|/\_^|  \_^ \_^ start-of-line (used anywhere) |/zero-width|

I can see from testing that to match rain\nand in

There is rain and rain
and rain

I could use /rain\_.\_^and but /rain\_.^and does not work.

I understand how to use it, but why does this exist? Why not just let ^ always be a start of line?

4

Why not just let ^ always be a start of line?

Mostly for compatibility.

Vim was originally not able to match patterns across lines. That feature was only introduced in Vim version 6.

Previous to that version, the ^ and $ anchors would only make sense at the start or end of the pattern, resp., and in a few other specific locations around \(, \| and ). But it was safe to make them match the literal characters elsewhere, since that was the only possibility that made sense at the time.

When multi-line matches were introduced, changing the way those characters worked might have broken existing code, since code could have relied on that existing behavior. So rather than change the way those characters match, it was deemed safer to introduce a new match that would also work on patterns meant for multi-line matches (which go along with \_. and other items under the \.x "namespace.")

See :help new-seatchpat, which is part of the changelog for Vim 6 and mentions the introduction of these new pattern items as part of that new feature.

BTW, if you want to match the words rain and and across a line break, an easier way is to match /rain\nand, since in your example the \_^ will only work when the \_. matches exactly a newline, so you might just match on that explicitly... The \_^ anchor is more useful when you might be matching patterns separated by a number of lines in between them.

| improve this answer | |
  • Yeah, I was just coming up with an example of how to use it. Thanks for the reasoning behind it! – jeremysprofile Aug 9 at 20:35
  • Can you comment on the use of anchors around \( and )? I don't think I know how ^ would come into play there – jeremysprofile Aug 9 at 20:36
  • 1
    @jeremysprofile You can match word1 at the beginning of the line or word2 anywhere: /\(^word1\|word2\), that needs ^ to work inside a \(...\) group. – filbranden Aug 9 at 22:35

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.