Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 739
dkiyatkin Avatar asked Nov 18 '11 23:11

dkiyatkin


1 Answers

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.

like image 95
scottfrazer Avatar answered Oct 05 '22 06:10

scottfrazer