Wandering Thoughts archives

2022-12-23

Handling numbers in Vim when they have a dash in front of them

Over on the Fediverse, I mentioned a Vim situation I'd run into:

Here's a situation Vim's Ctrl-A feature for handily incrementing numbers doesn't readily handle: if you have machines called eg 'something-1' and want to make that 'something-2', 'something-3', and so on. Vim will interpret the '-1' bit as the number -1 and auto-increment it to 'something0'. There is probably a clever Vim way around this, or you can use another option.

(Then people in the replies gave me a number of clever Vim solutions.)

The situation where this came up was that I was writing some new DNS entries for a series of boring names, starting with:

machine-1   IN A 10.x.y.z

I wanted to copy and duplicate in order to make 'machine-2', 'machine-3', and so on entries, so I copied that first line and hit Ctrl-A to increment the machine number, which didn't work because Vim, by default, saw the '-1' as a negative number and duly incremented it to '0'. Visually selecting the number before using Ctrl-A isn't really a great solution for this particular case, because I want to do it repeatedly to create different numbers; at best I'd be repeatedly selecting shorter and shorter columns and incrementing them by one.

Jeff Forcier offered the best general solution for people like me, which is to tell Vim that I don't work with negative numbers by adding 'unsigned to the 'nrformats' setting. I understand why this isn't the default, but I sort of wish it was or at least that Vim was more sophisticated about what it considered a negative number (so that it required a free-standing '-', not one that text before it).

The obvious quick fix if you remember is switching to Ctrl-X to decrement the number. Related to this is that I could start at the end of the sequence instead of the start, so I'd start with, say, 'machine-5', duplicate it a bunch, and then use Ctrl-A to create machine-4, machine-3, and so on. Both of these rely on realizing that Vim is going to interpret the '-1' as a negative number, which is something that doesn't come up very often for me.

Having written this entry, I will hopefully remember the whole issue. I'm not sure if I want to add 'set nrformats+=unsigned' to any .vimrc, though, because that's a subtle trap in its own right. If I put it in, I'll probably forget it, then someday I may actually be working with negative numbers and get another surprise. The current surprise is at least readily understandable.

unix/VimHandlingDashedNumbers written at 22:12:31; Add Comment


Page tools: See As Normal.
Search:
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.