Aug 12, 2010 vim

Notes on Vim’s macros.

Registers

Registers contain:

  1. saved macros
  2. all previous operations, and acts as clipboard/history of all cmd

Useful for pasting what I copied few operations before.

View all macros & history operations

:reg <optional macro letter> (or :registers)

@: (shortcut of :reg)

:reg a: Show content of register a

History

To paste what you’ve cut 3 or 4 operations prior (http://statico.github.io/vim.html)

"3p

add next 10 lines to ‘x’ register

"x10yy

save text to register ‘a’

copy: "ay 
cut: "ad
paste: "ap

while in insert-mode

<c-r>3	# paste what was copied 3 operations ago. (see reg or @: to see them)

Macro Recording

Start recording

q <macro letter> <commands to record> q

qX ... q saves macro to letter “X” (register X)

Execute macros

<optional: number of times>@<macro letter>

@q: execute macro q

@@: replay previous macro ; i.e. repeat macro – i.e. execute macro again

Run in visual mode

Save macros

By default (in non-compatible mode), macros are saved in file ~/.viminfo.

Save macros in .vimrc. Macros can be saved in .vimrc.

let @a='0fa'
let @b='This is really frequently used line'

Edit macros

(might not work)

:let @a='
Ctrl R Ctrl R a
edit the text
'   (append ' to finish command) + Enter
:reg a		view new value

Append macro

qA...q: use capital letter (shift) to append instead of recording over it..

Helpful Vim key mapping

Map macro to a key (might not work if Space is leader )

:nnoremap <Space> @q

To get rid of annoying register pop-up window, remap q

map q: :q    

Example

On a line containing only the number 1, type this (http://peterlyons.com/leveling_up.html):

qaYp<C-a>q →
qa start recording.
Yp duplicate this line.
<C-a> increment the number.
q stop recording.

@a → write 2 under the 1
@@ → write 3 under the 2
Now do 100@@ will create a list of increasing numbers until 103.	

Multiple Files

Perform macro on multiple files of buffers

:args *.c
:argdo normal @q   
:wa					#save

Misc

Snippets from https://gist.githubusercontent.com/gmccreight/7519289/raw/master.vim

# Snippets from https://gist.githubusercontent.com/gmccreight/7519289/raw/master.vim

'<,'>normal @q
run the macro recorded into the q register on all selected lines (the '<,'> is automatically added)

:let @q="2dw"
easily fill the q register with a macro that deletes two words

norm
what's a good shorthand for "normal" on the #vim_command_line

:argdo norm @q
run your last macro against all files in the args