views:

129

answers:

5

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?

+10  A: 

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.

Greg Hewgill
+3  A: 

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#^#//#.

daryn
You could also use ":s#^#//# 5" (the line count is at the end).
Neil
+2  A: 

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

ma
jjjj
mb
:'a,'bs,^,// ,
Greg Bacon
+4  A: 

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.

michaelmichael
I use this one: http://vim.sourceforge.net/scripts/script.php?script_id=1173Pretty nice.
ThePosey
+6  A: 

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.

too much php