Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Suppose that I have a number into register r.

How could I use this value with CTRLA and CTRLX

Here's an example to make it clearer:

Suppose that I have this text file:


I want to to increase those numbers with the value in register r to obtain (if it contains 5)


Why I'm asking it ? Because I want to use CTRLA into a macro but the number of time that I need to apply CTRLA is only know at "run time".

In a more general way, how could I execute a command a number of times stored in a register ?

All of these questions and answers where interesting but they don't answer my question:

share|improve this question
up vote 4 down vote accepted

You could make a mapping like this:

noremap <Leader><C-A> :<C-U>execute 'normal!' str2nr(getreg('r')) . '<C-A>'<CR>

It maps \Control-A (<Leader> defaults to \, see :help leader) to run the usual Control-A the number of times specified in the r register. You could even use this to rebind the default Control-A (leave out <Leader>), but that seems like it could lead to confusion later if you ever forget about the mapping.

When the r register contains 5, it works like this (switched to double-quote notation since it is impossible to represent Control-A in a single-quoted string literal):

The getreg() and str2nr() functions are evaluated, resulting in this Ex command:

:execute 'normal!' 5 . "\<C-A>"

This results in another Ex command:

:normal! "5\<C-A>"

This executes a normal-mode command:


Which uses the prefix count before the usual Control-A (non-mapped, due do the ! in :normal!).

This version always uses the value in the r register; it explicitly ignores any prefixed count (unlike the usual Control-A). Alternate implementations are possible (e.g. where a prefixed count overrides or multiplies the value in the r register), but they would be a bit more complex.

You could also put the command directly in your macro instead of using a mapping:

qq…:execute 'normal!' str2nr(getreg('r')) . 'Control-A'Return

You have to type the actual Control-A and Return instead of their <> equivalents because this is no longer part of a mapping where Vim will automatically make the translation. Also, the Control-U is dropped, since it was only there to guard against a possible prefix count before the initial : (you can protect against this in the macro content itself).

share|improve this answer
Wow! Thank you very much! – Luc M Jun 12 '12 at 13:05
I realize that your answer deserves thousand of votes. – Luc M Jun 16 '12 at 4:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .