2

I'm trying to wrap my head around this line of code:

:execute "normal! gg/for .\\+ in .\\+:\<cr>"

I understand that it's executing in normal mode (ignoring remappings) the command that starts with gg. It goes up to the first line and searches for the word "for". Then I'm lost. Can anyone help me?

1 Answer 1

2

The upshot is that what follows normal! is almost what you would type on your keyboard except for having to deal with some tricky double-escaping (\\+) and the special \<cr> notation. (If the : is throwing you don't let it. It's just a literal colon in the search string.)

So you're right about gg. Following that is a search with this vim regular expression:

for .\+ in .\+:

...which matches strings of the form

for <blah> in <bleh>:

...where <blah> and <bleh> each must have at least one (non-newline) character.

If that's the right regular expression then something happened to one of the \s preceding each +. Where'd they go? The double escaping is a byproduct of two things. First, we know that the wildcard + in a vim regexp requires one \ (unless we use very-magic mode...see below).

Next is the fact that the double quoted string's contents are not executed as is. The string is a parameter for the :execute command which takes whatever is passed to it, "evaluates" it and executes the result. (Which we hope is a valid Vim expression at this point.) Evaluation involves things like resolving variables into their values and, relevant to us, looking for special chars occurring after escape chars.

Since we need the escaping to get through to search (/) we add an extra escape to cope with :executes inclination to strip them. (:execute will see an escaped \ and an escaped \ is not special. In that context it's just a backslash.)

As for the \<cr> at the end, that's simpler. Vim's rules around key codes say we have to escape them in expressions like this (exception: in a mapping it's not required). This one, of course, will resolve into the equivalent of pressing the Enter key...just like you'd press it yourself if entering the command manually.

Regarding the "very magic" mode mentioned above, this is enabled by pre-pending the regexp with \v. Just like \+ there's escaping here but we could trade two instances of double-escaping for one and perhaps make it a little more familiar...

execute "normal! gg/\\vfor .+ in .+:\<cr>"
2
  • 1
    @guntbert Actually there was no typo there. I reworded it, though. Maybe it makes better sense now.
    – B Layer
    Commented Feb 3, 2020 at 21:29
  • @user26778 Does this answer your question?
    – B Layer
    Commented Feb 7, 2020 at 0: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.