Search code examples
emacsorg-mode

Add enabling Relative Line Number to init.el


In Emacs 26.x, How do I get Emacs to start with Relative Line Numbers turned on by default ?

I tried to use C-x h, then clicked the menu item and the help showed the following

<menu-bar> <options> <showhide> <display-line-numbers> <relative> 
runs the command #[nil "\300\301!\210\302\303!\207"
[menu-bar-display-line-numbers-mode relative message "Relative line
numbers enabled"] 2 nil nil] (found in global-map), which is an
interactive compiled Lisp function.

So tried adding the command into init.el as

(menu-bar-display-line-numbers-mode relative message "Relative line
numbers enabled")

How do I make this work ?


Solution

  • Unfortunately, Emacs's help message is pretty bad in this case. The menu button is bound to an anonymous function, and the help system is basically displaying the byte-compiled version of that function. I got the Emacs source, searched for the unique looking string "Relative line numbers enabled", and found the function in lisp/menu-bar.el:

       (lambda ()
         (interactive)
         (menu-bar-display-line-numbers-mode 'relative)
         (message "Relative line numbers enabled"))
    

    So you can use menu-bar-display-line-numbers-mode, which takes only one argument, to set it:

    (menu-bar-display-line-numbers-mode 'relative)
    

    The canonical way to set this is adding display-line-numbers-mode to a mode hook,

    (add-hook 'foo-mode-hook #'display-line-numbers-mode)
    

    or enabling global-display-line-numbers-mode if you want them everywhere,

    (global-display-line-numbers-mode 1)
    

    and to set display-line-numbers-type to the desired style:

    (setq display-line-numbers-type 'relative)