Learn Practice Daily golf Reference

How to go to a line in Vim

In Normal mode, type the line number and then G: 42G goes to line 42. Typing :42 and pressing ↵ does the same as a command.

Try it here

Follow the line numbers

A review says line 11 has a stray console.log and line 4 is missing its semicolon. Go to each by its number with G, then fix it.

1 of 2Line 11: 11G, then dd
1import { fetchOrders } from './api';
1
2export async function report(userId) {
3 const orders = await fetchOrders(userId)
4 const paid = orders.filter((o) => o.paid);
5 let total = 0;
6 for (const o of paid) {
7 total += o.amount;
8 }
9 const average = total / paid.length;
10 console.log('average', average);
11 return { total, average };
12}
NORMALLoading the editor…1/20.0s1:1

This editor needs a keyboard. Read on, and play it at your computer.

KeysGoes to
42Gline 42
:42 ↵line 42, typed as a command
42ggline 42 as well (without a count, gg goes to the first line)
gg / Gthe first / the last line
12j / 12ktwelve lines down / up from where you are
50%halfway through the file (any percentage works)
``back to where you were before the last jump
Ctrl-o / Ctrl-iback / forward through the jump list, one jump at a time
vim +42 report.jsopens the file with the cursor on line 42 (from the shell)

Line number or count?

42G is an address: line 42, wherever you are now. 12j is a distance: twelve lines below the cursor. Use the number you have. An error message or a stack trace gives you an address, so type it before G. For a line you can see on screen, a distance is usually shorter to type, and relative line numbers do the counting for you: with :set relativenumber the gutter shows how far each line is from the cursor, so the number beside your target is the count for j or k.

Open a file at a line

From the shell, put + and the line number before the file name: vim +42 report.js (or nvim +42 report.js) opens it with the cursor on line 42. vim + report.js opens it at the last line, and vim +/average report.js at the first match of average. Inside Vim, :e +42 report.js does the same for another file.

Back to where you were

G, gg, searches and % are jumps: Vim remembers where the cursor was before each one. Two backticks, ``, take you straight back there, and pressing them again returns you to the line you jumped to, so you can flip between two places. Ctrl-o goes further back, one jump at a time, and Ctrl-i comes forward again. Counted moves like 12j are not jumps, so they don't add a place to come back to.