1

I noticed that the following mapping does not cause an infinite recursion (when pressing x).

:map x x

I didn't see anything in Vim's documentation that would explain this.

Further experimentation seems to suggest that when the right-hand-side of a mapping starts with the left-hand-side, there is no infinite recursion. For example, :map x Xx causes infinite recursion, but :map x xX doesn't (when pressing x).

My expectation is that when the contents of the left-hand-side are included on the right-hand-side, this would result in an infinite recursion, regardless of the positioning within the right-hand-side.

Is there some documented reason for the behavior I'm observing (e.g., special handling if the beginning of the right-hand-side matches the left-hand-side)?

1

This behavior is documented in :help recursive_mapping:

There is one exception: If the {rhs} starts with {lhs}, the first character is not mapped again (this is Vi compatible).

For example:

:map ab abcd

will execute the a command and insert "bcd" in the text. The ab in the {rhs} will not be mapped again.

0

Normally vim prevent a mapping to go crazy by limiting the maximum number of recursion. You can set the value of the maxmapdepth option (see :help maxmapdepth):

                                                'maxmapdepth' 'mmd' E223
'maxmapdepth' 'mmd'     number  (default 1000)
                        global
        Maximum number of times a mapping is done without resulting in a
        character to be used.  This normally catches endless mappings, like
        ":map x y" with ":map y x".  It still does not catch ":map g wg",
        because the 'w' is used before the next mapping is done.  See also
        key-mapping.

2
  • 1
    It appears that maxmapdepth is not related to :map x xX not having an infinite recursion. For other scenarios where the maxmapdepth is reached, I receive an error message, E223: recursive mapping. However, I do not receive that for the :map x xX mapping (when pressing x). Also, setting maxmapdepth to its largest value, 9223372036854775807, does not impact the responsiveness of pressing x (the UI would freeze if the mapping were expanded that many times).
    – dannyadam
    Jan 4 at 23:45
  • hmm, this is strange and really interesting. I didn't noticed this kind of behaviour. It would be cool to find an explanation about this problem Jan 4 at 23:56

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.