4

I noticed that whenever I narrow a region in emacs, the line numbering is relative to the narrowed region rather than being relative to the original file. Is there any way I can preserve the line numbering from the original buffer ?

Drew
  • 75,699
  • 9
  • 109
  • 225
Chakravarthy Raghunandan
  • 3,132
  • 2
  • 18
  • 42
  • 1
    If you don't get an answer, consider making an enhancement request: `M-x report-emacs-bug` is also for requests. – Drew Jul 25 '16 at 20:51
  • @Drew -- Unfortunately, Eli Z. will do nothing to enhance `linum.el`: https://debbugs.gnu.org/cgi/bugreport.cgi?bug=17787#8 Perhaps submitting a feature request directly to Stefan for `nlinum.el` would have better results if that library does not already provide the feature the original poster seeks. – lawlist Oct 29 '16 at 04:36
  • 1
    @lawlist: The question does not say that OP is using `linum.el`. I suggest reporting such an enhancement request for `nlinum.el`. – Drew Oct 29 '16 at 04:52

1 Answers1

5

A little late, but here's what I have in my .emacs. It does change the numbering for all linum-mode enabled buffers, but that's what I generally want:

(require 'linum)

(defvar my-linum-base-line nil)
(defvar my-linum-format nil)

(add-hook 'linum-before-numbering-hook
          (lambda ()
            (save-excursion
              (save-restriction
                (goto-char (point-min))
                (widen)
                (setq my-linum-base-line (count-lines 1 (point)))
                (setq my-linum-format
                      (format "%%%dd"
                              (length
                               (int-to-string
                                (+ my-linum-base-line
                                   (count-lines (point)
                                                (point-max)))))))))))

(setq-default linum-format
              (lambda (line)
                (format my-linum-format
                        (+ line my-linum-base-line))))

There's probably many things wrong with this in regards to proper elisp use, but it seems to work for me :)

mrtimdog
  • 166
  • 1
  • 4
  • Note that if your version of Emacs >= 26.1, you can use `(setq-default display-line-numbers-widen 't)` (Source: https://emacs.stackexchange.com/a/48591/18064). Not that I have anything against this implementation, just mentioning that current versions of Emacs have it already implemented. – colelemonz Jan 03 '22 at 20:49