Patricia Sauer - Authentic Programming

Moving the cursor within a line and between lines in vi

a bridge during sunset

In the last article, we learned how to move word by word in vi. By learning how to move within a line, we want to become even faster with navigating in vi. So let's have a look at how to move within a line.

It's important to note that the length of a line in a text file may be longer than what is shown in your terminal window. This is because the maximum number of characters that can be displayed as a line may be exceeded. The screen width also affects this. In such cases, vi wraps the line onto the next line, even though it is technically still considered one line. This means that navigating to the end of a line, for example, may result in jumping over multiple "lines" that are actually part of the same line. Keep in mind that a line is defined as the text between two newline characters, regardless of how it is displayed.

Moving to the beginning of the current line

You can move to the beginning of the current line by pressing the 0 key. This key will move the cursor to the beginning of the line, no matter how long it is.

Moving to the end of the current line

You can move to the end of the current line by pressing the $ key. This key will move the cursor to the end of the line, no matter how long it is.

Moving to the first character of the next line

Vi provides a way to navigate to the first character of the next line. Just press the + key to get there.

Moving to the first character of the previous line

Vi provides a way to navigate to the first character of the previous line. Just press the - key to get there.

Moving between brackets or parentheses

Another useful command for word navigation is %, which jumps the cursor to the corresponding bracket or parenthesis. This can be useful when working with code or complex documents.

Recap

In this article we learned that

  • we can move the cursor to the beginning of the current line using the 0 key
  • we can move the cursor to the end of the current line using the $ key
  • we can move the cursor to the first character of the next line using the + key
  • we can move the cursor to the first character of the previous line using the - key
  • we can move the cursor between brackets or parentheses using the % key
  • moving between brackets and parentheses may span multiple lines

You can check the following table to get another overview about the commands and their effects.

CommandResult
0Move the cursor to the beginning of the current line
$Move the cursor to the end of the current line
+Move the cursor to the first character of the next line
-Move the cursor to the first character of the previous line
%Move between brackets and parentheses

Watch it on YouTube

You can watch me explaining how to navigate within a line in vi and vim in this video:

Liked this article?

Buy Me A Coffee

© 2018 - 2024 Patricia Sauer