The README for repeat.vim begins:
If you’ve ever tried using the
.
command after a plugin map, you were likely disappointed to discover it only repeated the last native command inside that map, rather than the map as a whole. That disappointment ends today. Repeat.vim remaps.
in a way that plugins can tap into it.
I’ve often felt this sense of disappointment when using Vim’s xp
commands to transpose two characters. I’d like to be able to use the dot command to repeat xp
, but it only repeats the p
command, which is the last native command. Let’s create a custom cp
mapping that transposes two characters in a way that can be repeated using the .
command.
Constructing a repeatable mapping
Usually, Vim’s mappings follow this general format:
:map LHS RHS
This instructs Vim to execute the keys on the right-hand side (RHS) of the expression whenever the user presses the keys on the left-hand side (LHS). Alternatively, we can create a named mapping by using the <Plug>
key on the LHS of the expression. Named mappings can’t be executed directly by the user, but they can be referenced by other mappings (see :help using-<Plug>
). For example, this pair of mappings:
nmap <Plug>TransposeCharacters xp nmap cp <Plug>TransposeCharacters
Has the same effect as this single mapping:
nmap cp xp
That is, when the user presses cp
, Vim executes the x
command followed by the p
command. We can use the repeat#set()
function (supplied by repeat.vim) to tell Vim to invoke our named mapping when the dot command is used. Here’s the complete mapping:
nnoremap <silent> <Plug>TransposeCharacters xp \:call repeat#set("\<Plug>TransposeCharacters")<CR> nmap cp <Plug>TransposeCharacters
Note that the line beginning with \
is a continuation of the previous line. When the user presses cp
, Vim executes the <Plug>TransposeCharacters
named mapping. That mapping executes the Normal commands x
then p
, then runs :call repeat#set("\<Plug>TransposeCharacters")
, which instructs the dot command to execute the named mapping.
Further reading
:h .
- repeat.vim by tpope
:h <Plug>
:h using-<Plug>