Error messages and code reviews often identify text by line number. Vim can show or hide line numbers beside the text and keep them enabled by default.

Vim provides both absolute and relative line numbering. Absolute numbering shows the exact line number for every line in the file, while relative numbering shows the distance from the current line. Hybrid numbering keeps the current line's absolute number and shows relative numbers on the other lines.

Interactive numbering changes affect the current window. A setting in your user vimrc file supplies the default for future Vim sessions, so reopening a file in the same session does not prove that the preference was saved.

Steps to add or remove line numbers in Vim:

  1. Press Esc to enter Normal mode.
  2. Enable absolute line numbers in the current Vim window.
    :set number norelativenumber

    Optional alternatives for the current window are :set nonumber norelativenumber to hide all line numbers, :set nonumber relativenumber for relative numbers with zero on the current line, or :set number relativenumber for hybrid numbering. These are separate choices; :set nonumber alone leaves relative numbers visible when they are enabled.

  3. Save any unsaved changes to the current file.
  4. Identify the user configuration file loaded by Vim.
    :echo $MYVIMRC

    The result is the path to your active user vimrc file. In a normal Linux or macOS session with no user vimrc yet, the result is empty.

  5. Open the active user configuration from inside Vim.
    :edit $MYVIMRC

    If the previous result was empty on Linux or macOS, use :edit ~/.vimrc instead to create your user configuration.

  6. Add the absolute-numbering setting at the end of your user vimrc file.
    set number norelativenumber

    This setting overrides earlier numbering settings in the file while preserving your other configuration. For a different saved default, substitute one of the optional commands above without the leading colon.

  7. Save the user vimrc file.
    :write
  8. Quit Vim.
    :quitall
  9. Reopen a text file from the shell in a fresh Vim session.
    vim example.txt

    Here, example.txt represents a text file of your choice. Absolute numbers should appear beside its lines without another :set command.

  10. Check that the numbering options match your saved default.
    :set number? relativenumber?
      number
    norelativenumber

    The output shown is for the absolute-numbering default. Both options are off for hidden numbers; only relativenumber is on for relative-only numbering; both are on for hybrid numbering. If the values differ from your saved choice, :verbose set number? relativenumber? shows where they were last set.

Share this guide