The short answer
When in normal and visual mode, pressing gg goes to the beginning of the file.
While gg is the most commonly used command, there are other shortcuts to bring the cursor to the first line of a file.
- 1G
- :1
- [[
Navigating to the first top column
All aforementioned commands will place the cursor on the first non-whitespace character.
To navigate to the first column of the first line instead, you can use:
gg0 or 1G0. The addition of the 0 brings the cursor to the beginning of the line.
Highlight sections of the code
In Vim, there are two ways you can highlight text starting from the first line of the file.
To highlight one or more lines starting from the top of the file, you can:
- 1. Press the ESC key twice to enter Normal mode.
- 2. Press gg to bring the cursor to the first non-whitespace character at the top.
- 3. Press the v key to enter Visual mode.
- 4. Use the arrow keys, the mouse, or the <line-number>gg command to widen your selection.
To highlight every line from the current cursor position to the top of the file, you can:
- 1. Press the ESC key twice to enter Normal mode.
- 2. Press the v key to enter Visual mode.
- 3. Press gg to bring the cursor to the first non-whitespace character of the file.
Delete sections of the code
To delete everything from the top to the current line, you can press dgg.
To delete everything from the top to the bottom of the file, you can run the :%d command.
To delete everything from your cursor location to the top of the file, you can press d[[.
Search and replace keywords from the top of the file
To find and replace keywords from the top of the file, you can provide a range to the substitute command as follows:
:1,<line number>s/<search-key>/<replace-key>
For example, :1,7s/hello/world replaces any text from lines 1 to 7 matching hello with world.
In addition to navigating from the top of the file, read more about how to move to the end and to a specific line of a file.
Written by
Glory Kim
Software Engineer, Loom
Filed Under
Related Articles
Vim Find And Replace
You can use either the substitute command or the slash and dot method to search for patterns and replace with different values.
Vim Modes
Learn about seven of Vim’s modes
Go To Line In Vim
Variety of approaches to go to lines
Vim / Vi Page Up and Down Controls
Quick reference for Vim's page up and down controls
Vim Go To End/Start of Line
Go to the end or beginning of a line in Vim
Copy & Paste in Vim / Vi
Copy (Yank), Paste (Put) and Cut (Delete) in Vim
Undo & Redo in Vim / Vi
Keyboard shortcuts and summary of how Vim tracks changes
Show & Hide Line Numbers in Vim / Vi
Toggle absolute and relative line numbers
Select all in Vim / Vi
Select all and copy, paste, or delete the contents
Searching in Vim
Search forward, backward, case insensitive, and more
Go To End of File in Vim / Vi
Select and delete to the end of a file in Vim
How to delete lines in Vim / Vi
The best answer depends on which mode you use