05 September 2013

Clearing a register in Vim

Earlier this week, I had a repetitive programming task to carry out. It involved converting lots of SELECT statements in SQL into Kohana ORM code. For part of this task, I needed a way to find a bunch of non-adjacent lines in the code and move them somewhere else. My editor of choice is Vim, so there are many ways this can be done.

The first method I thought of was yanking or deleting lines into a specific register. In Vim, you can do edit operations using a number of different registers, including one named for each letter on the keyboard. For example, you can delete a line into the x register with "xdd. You can also append to a register by referring to it by its capital letter variant. So, if we had previously yanked a line into register x, we could append another line to it with "Xyy. This was to be the basis of my macro: finding relevant lines and appending them to a register.

I figured it would be a good idea to clear the contents of the register at the beginning of the macro, so that successive runs don't accumulate larger and larger register contents. I didn't know how to do this at the time; I don't think there's a way to yank "nothing". Then a thought occurred to me: macros are stored in registers!

Whenever you record a macro, you choose a letter to identify it. For example, to record a macro that deletes 3 lines and identify it as e, you would use qe3ddq (qe - start recording into e; 3dd - delete 3 lines; q - stop recording). This identifier e is actually the same as the register e. To demonstrate this, you can paste the contents into your buffer with "ep. You can then edit it and yank it back into the e register and run the new macro (if it still makes sense) with @e.

So what does this mean? We have identified a quick way to clear a register: record an empty macro! So, to clear out my x register, I can just use qxq (qx - start recording into x; q - stop recording). And there you have it!

Of course, after spending no more than a minute on Google, I found a more proper way to do this using the VimL scripting language in command mode: :set @x = ''. This way seems a bit more direct, but it's not as quick or easy.

image

No comments: