How do I record a macro to toggle comments on a line?
Answer
qaI// <Esc>jq
Explanation
This macro adds a // comment prefix to the beginning of the current line and moves down. For uncommenting, record a separate macro that removes the prefix.
How it works
Comment macro:
qa— start recording toaI//— insert//at line start<Esc>j— return to normal mode, move downq— stop recording
Uncomment macro:
qb— start recording tob^3x— go to first non-blank, delete 3 chars (//)j— move downq— stop recording
Example
5@a comments 5 lines. 5@b uncomments them.
Tips
- Adjust the prefix for different languages (
#,--,/* */) - The vim-commentary plugin handles this automatically
- Use visual mode +
I// <Esc>for block commenting - Consider using
norm I//with ranges for one-off use