How to repeat some action certain times on Vim?

Try this:

  1. Do something

  2. Exit to normal mode

  3. Type, for example, 22.

The last commands will repeats 22 times.


One way to do this is to assign your key sequence to a macro, then run the macro once followed by the @@ run-last-macro command. For example:

qa.jq@a@@

If you know how many times you want to repeat the macro, you can use 4@@ or whatever.


Regarding your specific example, I prefer to do multiple-line insertion using visual block mode (accessed with Ctrl-v). For example, if I had the following lines:

This should be a comment.
So should this.
This is definitely a comment.
Is this a comment? Yes.

I'd go to the top first character in the top line, hit Ctrl-v to enter visual block mode, navigate to last line (maybe using 3j to move down 3 lines, maybe using 4g to go directly to 4th line, or maybe simply G to go the end), then type I// <esc> to insert the comments on all the lines at once:

// This should be a comment.
// So should this.
// This is definitely a comment.
// Is this a comment? Yes.

Also, there's a very handy commenter/un-commenter plugin that supports many languages here. It's easier than manually inserting/removing comments.


You can visually select the lines you want to repeat it on, type :normal! . to make vim use . on each line. Because you started with a visual selection, it ends up looking like this:

:'<,'>normal! .

However, if you're adding and removing // comments alot, you might find the following mappings useful:

" add // comment with K
noremap K :s,^\(//\)\=,//,e <BAR> nohls<CR>j
" remove // comment with CTRL+K
noremap <C-K> :s,^//,,e <BAR> nohls<CR>j

You can use 5K to comment 5 lines, you can use visual mode to select your lines first, or you can just hammer K until you've commented everything you want.

Tags:

Vim

Macros

Repeat