How do I display the total number of lines in the Emacs modeline
Asked Answered
M

1

20

The default Emacs modeline only shows the current line number and its percentage in relation to the total line numbers. How do I make it show the line total as well?

Magalymagan answered 18/11, 2011 at 23:10 Comment(1)
See the alternative answer in this related thread, which uses (format-mode-line "%l") instead of count-lines in order to receive a boost in performance/speed: emacs.stackexchange.com/a/26724/2287Humble
C
18

This can be a little tricky, because if you update the line count all the time and have a large buffer it can make Emacs somewhat unresponsive since it's counting lines over and over. I wrote this to take a lazy approach to counting: it only does it when the file is first read in or after you save/revert it. If the buffer is modified it doesn't lie about the line count, it simply isn't shown until you save again.

(defvar my-mode-line-buffer-line-count nil)
(make-variable-buffer-local 'my-mode-line-buffer-line-count)

(setq-default mode-line-format
              '("  " mode-line-modified
                (list 'line-number-mode "  ")
                (:eval (when line-number-mode
                         (let ((str "L%l"))
                           (when (and (not (buffer-modified-p)) my-mode-line-buffer-line-count)
                             (setq str (concat str "/" my-mode-line-buffer-line-count)))
                           str)))
                "  %p"
                (list 'column-number-mode "  C%c")
                "  " mode-line-buffer-identification
                "  " mode-line-modes))

(defun my-mode-line-count-lines ()
  (setq my-mode-line-buffer-line-count (int-to-string (count-lines (point-min) (point-max)))))

(add-hook 'find-file-hook 'my-mode-line-count-lines)
(add-hook 'after-save-hook 'my-mode-line-count-lines)
(add-hook 'after-revert-hook 'my-mode-line-count-lines)
(add-hook 'dired-after-readin-hook 'my-mode-line-count-lines)

You might want to adjust mode-line-format to suit your taste of course, the above is what I personally prefer.

Chime answered 19/11, 2011 at 1:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.