In this post, I would like to share line number settings in Neovim to move the cursor more efficiently.

Absolute number and relative number in Neovim

Show absolute line number

To know where we are in a file, it is useful to show the line number on the leftmost column of the file. To show line numbers in neovim, we can use the following setting:

set number

The absolute line number will shown at the beginning of each line.

Combine absolute number and relative number

While this option is useful for see where we are in the file, it is not convenient for moving the cursor to different lines. Because cursor movement in Neovim is based on relative distance. For example, to go to 3 lines above or below current line, we use 3k or 3j. If we want to go to a specific line, we have to manually calculate the distance between current cursor line and the destination line, which is cumbersome and error-prone.

To alleviate this problem, Neovim also support showing relative number:

set relativenumber

This option can be combined with number option. The end result is that only the cursor line shows absolute line number and the other lines show relative number to the current cursor line.

2019-01-11_220809.jpg

Automatic toggle of relative line number

In some situations, it is more convenient to absolute line numbers, eg., when you want to debug a file and run to specific lines. You can the use plugin vim-numbertoggle to automatically toggle relative number based on several events. e.g., when you go to insert mode or lost focus.

Automatic number toggle does not work inside Tmux?

But I have found that the number toggle function does not work inside tmux sessions by default1. If I open two tmux panes side by side and open a file with Neovim in one pane and then switch to another tmux pane, the relative line number in Neovim does not change to absolute number.

I opened an issue on the Neovim GitHub repo and get the right answer from the developer which solves this issue. We need to turn on the focus-events for tmux. From the Tmux documention:

 focus-events [on | off]
         When enabled, focus events are requested from the terminal if supported and passed through to applications running in tmux. Attached clients should be detached and attached again after changing this option.

Edit the tmux config file ~/.tmux.conf and add the following setting:

set -g focus-events on

Refresh the tmux session or start a new tmux session and the automatic relative number toggle should work as expected now.

References


  1. I am using Tmux 2.8-rc