This question applies in the context of all line numbering implementations I've tried, including line-number
, nlinum
, and linum
, so I have a feeling that the answer will have something to do with Emacs internals, especially with the abstraction of buffers.
Getting on with it... Let's say I have a buffer with the following content (leading digits represent line numbers, not buffer content):
1 foo
2 bar
3 baz
4 quux
If I were to do a narrow-to-region
on the last two lines, I'd end up with a narrowed buffer like this:
1 baz
2 quux
But what I really want is this:
3 baz
4 quux
Is there any way to accomplish that last case? I'm willing to redefine or advise internal Emacs constructs to get this to work and deal with the consequences as they arise.
EDIT: As pointed out in the comments, this question seems to invalidate my own as a duplicate. Let me add a couple of points that will hopefully add some distinction:
- I am most interested in a solution that is agnostic to line numbering package. Something that will work for
line-number
,nlinum
, andlinum
without needing to customize each one. - I would also settle for a fix that only works with
line-number
, as that is the package that I use (given that it ships with Emacs 26.1 and is more performant than the other two options).
If you feel like further edits are necessary, or if voting to close is most appropriate, no hard feelings from me.
EDIT: Thanks for the answers! This is now my line numbering setup:
(defun with-absolute-line-numbers (fun &rest args)
"Let `line-number-at-pos' always output absolute line numbers."
(cl-letf*
((old-line-number-at-pos (symbol-function 'line-number-at-pos))
((symbol-function 'line-number-at-pos)
(lambda (&optional pos absolute)
(funcall old-line-number-at-pos pos t))))
(apply fun args)))
;;; Line numbering config
(if (>= emacs-major-version 26)
;; Disregard narrowing when displaying line numbers
(setq-default display-line-numbers-widen t)
;; Same, but for [n]linum
(advice-add 'linum-update-window :around #'with-absolute-line-numbers)
(advice-add 'nlinum--line-number-at-pos :around #'with-absolute-line-numbers)
;; Use nice formatting for [n]linum
(setq linum-format "%3d ")
(setq nlinum-format " %d "))