In the buffer
With :set shiftwidth=4 expandtab, before:
retries = 3 # max attempts
timeout = 30 # seconds
backoff = 1.5 # multiplier
^
After typing <C-v>2j>:
retries = 3 # max attempts
timeout = 30 # seconds
backoff = 1.5 # multiplier
^
All three comments move four columns to the right and stay lined up with each other. The code to their left does not change. The cursor stays at the block’s old left edge, which is now whitespace.
When you would reach for it
You have a block of assignments with comments lined up after them, and you rename one variable to something longer. Now its value runs into the comment column, and you need to push the comments over. A linewise >> shifts the code too, and fixing each line with i<Space> loses the alignment. Selecting the comment column as a block and shifting it moves only that column, and every line moves by the same amount.
Gotchas
- The block’s left edge is a screen column, and it applies to every line in the block, whatever is there. If that column lands in the middle of a word on another line, the whitespace goes in the middle of the word:
total_count = 30becomestotal_coun t = 30. Put the block’s left edge in a column that is whitespace (or the start of the comment) on every line. - The amount comes from ‘shiftwidth’, and with Vim’s defaults (
shiftwidth=8,noexpandtab) the padding is written as tabs. If your file uses spaces,:set expandtabfirst, or the comments line up on screen while the file fills up with tab characters. - Block
<only removes whitespace that starts at the block’s left edge. With the block on the#itself there is no whitespace to remove, so nothing happens. Start the block inside the gap, as in the first variant below. - The cursor ends up at the old left edge, not on the comment. Pressing
.repeats the shift from there, which is what you want. A fresh<C-v>from that spot also works, because the whitespace is now part of the gap.
Variants
retries = 3 # max attempts
timeout = 30 # seconds
backoff = 1.5 # multiplier
^
retries = 3 # max attempts
timeout = 30 # seconds
backoff = 1.5 # multiplier
^
<C-v>2j9< with the cursor in column 15: shift left by a large count. Block < never removes more whitespace than is actually there, so each comment slides left until the gap is used up. They stay aligned, and the longest line keeps one space before its comment.
host = "db.local"
port = 5432
user = "admin"
^
host = "db.local"
port = 5432
user = "admin"
^
<C-v>2j9< with the block starting right after = : removes the uneven padding on every line, and leaves port alone because it has none. This works with any ‘shiftwidth’ as long as the count is big enough to cover the widest gap.
retries = 3 # max attempts
^
retries = 3 # max attempts
^
<C-v>3>: a count multiplies the shift. Three times a ‘shiftwidth’ of 4 moves the comment twelve columns. The same applies to <.