views:

296

answers:

8

If I wanted to process a batch of text files with the same set of commands for example:

:set tw=50
gggqG

Can I save the above and run it with a shortcut command?

A: 

You are looking for "vim macro".

Johan
Ah of course. Excuse my newbness :p
Jon
If you don't ask, you would not get a answer :)
Johan
+4  A: 

Here it is : http://vim.wikia.com/wiki/Macros :-)

p4bl0
+10  A: 

If you want to use it only once, use a macro as specified in some of the other answers. If you want to do it more often, you can include the following line in your .vimrc file:

:map \r :set tw=50<CR>gggqG

This will map \r to cause your two lines to be executed whenever you press \r. Of course you can also choose a different shortcut, like <C-R> (Ctrl+R) or <F12> or something.

jqno
Can I map it to a typed command rather than a keyboard shortcut (like executing a script)? I can imagine I'll run out of keys otherwise!
Jon
Yes, you can even map it to `hellomynameisjon` if you like :).
jqno
So that would be ":map \hellomynameisjon :set tw=50<CR>gggqG"? and I just hit ESC and then type it in?
Jon
No, the backslash is included in the keystroke. If you do it like that, you'd have to type `\hellomynameisjon`, with the backslash. Other than that, you are correct.
jqno
look at rson's solution to use it with a colon.
rampion
A: 

Yes, the important word is macro

But it seems like a 'command' such as :set tw=50 would be better included in the .vimrc file so vim uses it every time you start it up.

pavium
+6  A: 

As a very quick start, put this in your .vimrc:

" define the function
" '!' means override function if already defined
" always use uppercase names for your functions
function! DoSomething()
    :set tw=50
    gggqG 
endfunction

" map a keystroke (e.g. F12) in normal mode to call your function
nmap <F12> :call DoSomething()<CR>

note: the formatted code above looks rather horrible, but lines starting with " are comments.

Paolo Tedesco
+2  A: 

Other than macros, you can use argdo. This command will perform the same operation on all open files. Here is how you format all open files using :argdo and :normal:

shell> vim *.txt

:argdo exe "normal gggqG"|up
soulmerge
+1  A: 

Before you go for writing a thousands-lines .vimrc (which is a good thing, but you can postpone it for a while), I think you might want to look at the plain recording, in particular you may consider using the qx (where x is any key) for recording, q to finish recording and @x to execute recorded macro.

Michael Krelin - hacker
I will only run the macro once per file. Is there any way to save the recording?
Jon
To tell you the truth, I have no idea ;-) I think not. But the recording persists across all files as long as you don't exit vim. Try `:help repeat`.
Michael Krelin - hacker
+6  A: 

The following in .vimrc will define a new command Wrap that does what you want.

command! Wrap :set tw=50 | :normal gggqG

Call it with :Wrap

Randy Morris