Weekly Emacs tip #11: Display line numbers in the left margin
By default, Emacs doesn’t show line numbers in the left margin of the screen, like many other IDEs do. To me this feels especially clumsy when I’m working on a script or a LaTeX document and running the script or compiling the document points out an error on a certain line.
Luckily, the built-in display-line-numbers-mode
minor mode solves this for you. Of course you could just enable that minor mode for all buffers, but that’s too much for me. For example, I have several very large Org mode files and I really don’t care about line numbers in those. Similarly, when running R inside Emacs, I don’t need to see line numbers in the R interpreter itself, although I do want to see them in the R scripts I’m working on.
The code below from my .emacs
file solves this for my by explicitly “hooking” display-line-numbers-mode
to various other modes. For example, most major modes related to programming (e.g. in C, Bash, R) derive from prog-mode
, so that’s why I “hook it onto” that mode. Obviously, TeX-mode
handles LaTeX documents, and conf-mode
is for various type of configuration files.
;;;;;;;;;;;;;;;;;;;; ;;; Turn on line numbers on the left side of the screen for some ;;; modes. (use-package display-line-numbers :defer :custom ;; Compute the width of the line numbers based on the actual nr. of ;; lines in the file. No idea yet if this will slow things down too ;; much for large files... (display-line-numbers-width-start t) :hook ;; Turn line numbers on in programming modes (prog-mode . display-line-numbers-mode) ;; Turn line numbers on for LaTeX documents/AucTeX (TeX-mode . display-line-numbers-mode) ;; Turn on line numbers for (R-)markdown files (markdown-mode . display-line-numbers-mode) ;; Turn on line numbers in config files (conf-mode . display-line-numbers-mode) )
The :custom
part sets a variable to t
(true) which tells display-line-numbers-mode
to find the maximum number of lines in the file and then sets the correct width of the line number margin. Without this, I noticed that the margin width would fluctuate from a width 2 to a width of 3 characters every time line number 100 came in view. And similarly from 3 to 4 whenever line 1000 would appear. Too much flickering to my taste.

Figure 1: The same Emacs buffer, both without and without line numbers.
No Comments