How do I use a macro to wrap each word in quotes?
Answer
qabi"<Esc>ea"<Esc>wq
Explanation
How it works
This macro wraps the current word in double quotes and moves to the next word, making it easy to repeat across a line or file.
The command qabi"<Esc>ea"<Esc>wq breaks down as:
qa-- start recording into registerab-- move to the beginning of the current wordi"-- enter insert mode and type an opening double quote<Esc>-- return to normal modee-- move to the end of the word (which has now shifted one character right due to the inserted quote)a"-- append a closing double quote after the last character<Esc>-- return to normal modew-- move to the next wordq-- stop recording
The macro leaves the cursor on the next word, so you can immediately repeat it with @a or @@ to process additional words.
Example
Given a line of text:
foo bar baz qux
Position your cursor on foo and record the macro. After running @a and then 3@@, the result is:
"foo" "bar" "baz" "qux"
You can adapt this macro for single quotes by replacing " with ', or for parentheses by using ( and ). The same pattern of b, insert opening, e, append closing, and w to advance works for any wrapping characters.