A little bit ago, I covered the basics of Vim registers. We’ve got a good handle on yanking, deleting and putting, but registers have a bit more to offer. Let’s dig in a little deeper and see if we can’t find the good stuff.
You can assign deletes, yanks & macros to named registers. All alpha characters are fair game to use. But be careful: lowercase & uppercase characters are not the same.
Lowercase letters are used to assign or replace anything in that register. Uppercase letters are used to append to registers. Let’s use the following text as an example.
Now put your hands up Up in the club, we just broke up, I'm doing my own little thing. Decided to dip and now you wanna trip 'Cause another brother noticed me
So you decided that “Now put your hands up” is something you want to
reference throughout the file. Let’s head up to line 1 and yank that in
to register a:
Great! Now we can use that text in the
a register until we replace it.
But shoot! We just remembered that the first line has no power
without the second. Let’s add that to our register. Head up to line
2, and enter
"Ayy. That’s going to append line 2 to the text already
in there. Fantastic!
Now whenever we need to tell our ex-boyfriend that we’re partying it up,
we can just enter
"ap and we’re good to go.
Macros record a sequence of commands to playback at a later time. And guess what? They’re stored in a register!
Let’s use our fantastic set of lyrics up top again. We like them so much, we want to put a ring on it. No problem, let’s do that with a macro.
Head up to the first line and hit
qa. That tells Vim to start
recording to the
a register. Now we just need to execute the commands
to add a ring to one line.
I(<esc>A)<esc> That will wrap our line in
parenthesis (a ring). Hit
q to stop the recording and now drop down a
@a and the macro will replay those commands.
If we want to execute that macro for all lines in one fell swoop, we can
either include it in the strategy of recording the macro and run it
three times with
3@a. Or, we can visually select each line we want the
macro to run on and in command mode execute
How cool is that? We modified all the lines in substantially less commands!
Many times I’ve needed to copy something outside of Vim and paste it in.
:set paste, paste in the goods and remember to
but that’s not a very Vim way to do it. Use the
"+ register to paste
that content in.
Sometimes you need to delete text and never see it again. Send it into
the nether regions of our computers to be forgotten forever. More
importantly, you don’t want that text messing up the numbered registers
currently stored. The black hole register:
"_ will do just
"_dd will delete the line to the black hole register and not
effect any of the other registers. See ya later text, nice knowing you.
Macros & named registers have easily found a place in my Vim tool belt. It makes the tedious text editing tasks more enjoyable and saves my fingers keystroke fatigue. (The Good Stuff, if you will.)