Patricia Sauer - Authentic Programming

Display line numbers in vi

A runner starting field with numbered lanes

If you're a regular user of vi, you know how frustrating it can be to navigate large files without line numbers. Without them, it's easy to lose track of where you are in a file and waste time scrolling up and down to find the line you need. In this article, we'll learn how to display line numbers in vi, making it much easier to work with text files of any size.

Display line numbers in the currently opened file

To display line numbers in the currently opened file, you can use either :set number or :set nu if you prefer a shorter command. This will display line numbers for this file until you close it. When opening it again, the line numbers won't be displayed automatically.

Display line numbers in all files permanently

To display line numbers in all files permanently, you need to edit the .vimrc file in your home directory. In case that you don't have such a file: Open your terminal, navigate to your home directory and type vi .vimrc. You now have an empty buffer for the .vimrc file in your memory and opened in the editor. Let's start filling it with the content needed to display line numbers for every file. To do so, you need to go to insert mode and type set number. Then, press ESC to go back to command mode and save and close the file by using :wq. If you now open a file using the vi command, line numbers should be displayed automatically.

Additional useful commands

To turn off line numbering, you can type :set nonumber or :set nonu in command mode. You can also toggle line numbering on and off by typing :set number!or :set nonu! in command mode.

Recap

In this article we learned

  • that we can display line numbers temporarily in the currently opened file by using :set number or :set nu
  • that we can display line numbers for every opened file per default by adding set number to the .vimrc file
  • that we can turn off line numbering by using :set nonumber or :set nonu
  • that we can toggle line numbering on and off by using :set number!or :set nonu!

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

CommandResult
:set number or :set nuTurn on line numbering for the currently opened file
:set nonumber or :set nonuTurn off line numbering for the currently opened file
:set number!or :set nonu!Toggle between displaying and hiding line numbering for the currently opened file

Watch it on YouTube

You can watch me explaining how to display line numbers in vi and vim in this video:

Liked this article?

Buy Me A Coffee

© 2018 - 2024 Patricia Sauer