Martín Fixman
Martín Fixman

Reputation: 9585

How to repeat some action certain times on Vim?

In Vim, I usually want to repeat some series of commands some times. Say, I want to comment 5 lines, I would use

I//<Esc>j
.j.j.j.j

Is there any way to repeat the last ".j" part several times?

Upvotes: 32

Views: 25297

Answers (7)

unrealapex
unrealapex

Reputation: 630

You can repeat a macro by appending a count before the macro. For example, if you recorded a macro to the a register and you wanted to perform it five times, you would type this:

5@a

Upvotes: 5

George Eliozov
George Eliozov

Reputation: 71

Try this:

  1. Do something

  2. Exit to normal mode

  3. Type, for example, 22.

The last commands will repeats 22 times.

Upvotes: 6

too much php
too much php

Reputation: 90998

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.

Upvotes: 16

michaelmichael
michaelmichael

Reputation: 14125

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.

Upvotes: 12

Greg Bacon
Greg Bacon

Reputation: 139451

Another way to do it is to set marks and run substitutions over that range:

ma
jjjj
mb
:'a,'bs,^,// ,

Upvotes: 3

daryn
daryn

Reputation: 926

For your particular example. you could also use a range .,.5s#^#//# (to do this and the next 5 lines) or a visual block (hit v, then select the text you want) followed by :%s#^#//#.

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 992975

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.

Upvotes: 49

Related Questions