Sunday, April 19, 2015

Vim Script Quick Tip

Actually, this is about macros, but "macro" didn't rhyme with "quick", so deal with it.

The other day, a colleague asked me if I knew of a quick way to generate a list of hexadecimal numbers from 0000 through ffff. And I do, in Vim:

  • Start the buffer with 0x0000
  • Start a new macro using q and choosing any buffer name you like (I tend to go with d out of habit)
  • Yank the whole line
  • Paste it
  • Increment it using ctrl-a
  • Terminate macro recording
  • Execute the macro 65534 times
The commands look like this:


And if you don't want the 0x prefix, then remove it using a single replace command:


The reason I use the 0x prefix is to tell the ctrl-a (increment) command that the number format is hexadecimal and not octal, without having to diddle with the nrformats option.

On the other hand, if you increment numbers that are not prefixed, Vim will assume they are decimal, like this:

Also, if you want to decrement (as opposed to increment) numbers, you can use ctrl-x.

Happy Vimming.

No comments:

Post a Comment