Today I learned something new. I learned a new way to jump to the top or bottom of a Vim document.
I've long known how to jump to the top using the following ex command:
:0
That's a colon followed by a zero. The colon is there to prompt you for an ex command. The zero is the ex command itself. It is line zero, a pseudo line that is before all other lines. Since line zero is a pseudo line, the following command does exactly the same thing:
:1
So whether it's a colon followed by a zero or it's a colon followed by the number one, the result is the same: You are immediately jumped to line 1.
That's my old way of doing things. Today I learned a new way to jump to line 1:
gg
Yes, it's that simple. Two lower-case g's in a row (gg) take you to the very first line in the file. Here's how you go to the last line in the file:
G
So, in vim normal mode, a capital-G takes you to the last line in the file and a couple of lower-case g's typed one after the other takes you to the first line in the file. For years, out of force of habit, I used the following command to go to the bottom of a file:
:$
The dollar sign represents the last line in the file. For example, the following ex command tells you how many lines there are in the file by reporting the last line number to you:
:$=
Here's how I put it all together in my head now:
- Preceding my command with a colon makes it an ex command
- Immediately following the colon with a number addresses a line number in the file
- If it is a bare-naked number with nothing else following it, the number is used to jump you to that line number rather than address that line number
- Oddly enough, there is a pseudo line number, called line number 0
- For years I've typed :0 to go to line number 1. This is purely out of habit
- To jump to line number 1 in ex, I could have typed a colon followed by the number 1 instead. Whether I jump using colon followed by a zero or colon followed by the number 1, it is the same thing, for all intents and purposes. Both take me to line 1 immediately.
- Now I have a better way to do things. I now jump to the first line in the file with gg and jump to the last line in the file with G. Both these commands can be executed without ever leave vim's normal mode.
There's another way I can put this all together in my head. I now have 3 different ways to jump to line 12:
- :12
- 12G
- 12gg
In other words, the capital G defaults to the last line in the file and the lowercase gg defaults to the first line in the file. So, another way to look at it is in terms of defaults.
One of the reasons I started this blog is so that I would think about what I'm doing. I do things the same way over and over again out of force of habit.
It seems that everything remains the same until I decide to do something different. I aim to check in on myself a bit more often these days to make sure I know exactly what it is I'm up to.
Ed Abbott