I have faced loads of situations where there is a large block of text which needs a particular action performed per line. This can easily be done using a macro in vim. But when we use vim, we care about efficiency. So we will be seeing how it can be done by using the
visual block mode in vim.
Visual Block Mode
The visual block mode in vim is used to visually select multiple lines/block of text in vim and perform a certain action on it. This action can be anything ranging from an insertion to a deletion. This action is then reflected in each and every line of the block of text just like you would use multiple cursors in an IDE like VS Code.
To activate visual block mode, press Ctrl + v. Now you can select lines horizontally/vertically by using the navigation keys:
Once you select a block of text, you can press any of the vim's keybindings for performing actions on the block. For example, you can press d to delete the block.
Line by line operation in visual block mode
To insert/delete text on a line-by-line basis, press I to go into insert mode in the visual block or A to go into append mode. Once you do that, It will deselect the block and take you to the top line. Perform your desired action there and press escape. This action will then be reflected in each and very line of the visual block.
Incrementing numbers in a list
Imagine that you have to make a long list of incremental numbers. What would you do?
There is a very easy way to do this in vim using the visual block mode. Let us say we need to write numbers from 1 to 100. Follow the following steps:
Write 1 and a newline and copy it a 100 times by typing: y1j. Now paste it a 100 times using 100p.
Go to the visual block mode Ctrl + v and select the number block from the second 1, using 99j.
Press g and then Ctrl a. The latter is used to increment numbers and the former makes sure that the global context of numbers in a visual block is realized.
Indenting a block of code
A block of code can be effortlessly indented using the visual block mode. Select a block using Ctrl + v and the navigation keys. Then hit >> for right indentation and << for left indentation.
The o button can be used to go to the other side of the selected text in visual block mode, in addition to using $. The latter will take you to the end of a line rather than the end of the highlighted block.
Top comments (6)
These short intros are good for beginners, but consider using a key press On-Screen-Display for your recordings, it will make it much more obvious to the beginners what you are actually doing.
Okay thanks for the feedback :)
For the on-screen-display, you may check out a YouTuber called
devaslife. He made a tutorial video about it and it looks great!
I've been recently getting started with Vim - just discovered your series and will be reading through them all.
Thanks for the articles!
Thanks. Let me know if you find something worth sharing with everyone :)
I didn't know that! Thanks for mentioning!