brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Ctrl-A in Vim adds one to a number, g Ctrl-A turns a column into a sequence

Vim
~/tips/tip-vim-ctrl-a-increment-numbers

Ctrl-A add 1 to the number at or after the cursor

Adds to or subtracts from numbers in Vim, or numbers a list in one go.

This is one of my favourite small Vim keys. Put the cursor on a number, or anywhere before it on the line, and Ctrl-A adds one. Ctrl-X subtracts one. Type a count first and it adds that instead, so 5 then Ctrl-A on 8080 gives 8085.

Ctrl-A      add 1 to the number at or after the cursor
Ctrl-X      subtract 1
10 Ctrl-A   add 10
g Ctrl-A    in visual mode: 1, 2, 3, 4 down the selected lines

The visual-mode version is where it gets nice. Say you have a list where every item starts with 1. and you want it numbered. Go to the second line, press V, select down to the last item and type g then Ctrl-A. Each selected line gets one more than the line above it, so you end up with 1, 2, 3, 4. With a count, 2g Ctrl-A, you get steps of two. That’s the example the Vim help itself uses.

I’d reach for this when editing a docker-compose file with a run of ports like 8081, 8082 and so on, or when renumbering a Markdown list after you’ve moved items around.

The caveat is the nrformats option, which decides how Vim reads a number. Plain Vim includes octal, so 007 becomes 010, which is rarely what you want for a version or a port. The defaults.vim that ships with Vim sets it to bin,hex, but if you have your own vimrc that doesn’t load it, add set nrformats-=octal. And if tmux or GNU screen on your machine uses Ctrl-A as its prefix, that key never reaches Vim unless your config has a binding that sends the prefix through (often pressing it twice).

Further reading: Vim help: CTRL-A, Vim help: 'nrformats'

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Vim tips :%s/<Ctrl-r><Ctrl-w>/newname/g /oldname find . -name "*.conf" | vim – vim --clean file.txt :set textwidth=72 All Vim tips (45) All topics

Link