For me, the clearest measure for the size of a file is its number of lines.
So, I want this information in my mode line.
I am using Doom emacs and, even I could define my own mode line, for such a minor change I would prefer to follow the recommended way: add the information to
global-mode-string (see point 4 in doom-mode-line)
I ended up with the following code, which works very well except for one thing.
When I open a file, the displayed number of total lines is not the actual number of lines.
I tried different ways to set correctly
brust-buffer-total-lines when opening a file, but none of them worked. The two versions of the function
brust-buffer-total-lines-activate summarise all my ideas so far.
(Of course, comments on any part of the code are very well come.)
- Why these function do not work when they are called from the hook
- How could I set correctly the variable
brust-buffer-total-lines when opening a file?
;; Variable to buffer-locally store the total number of lines. (defvar-local brust-buffer-total-lines "" "Show the numbers of total lines in modeline") ;; Funtion to update the number of lines after every command modifying the buffer (it will be hooked in `post-command-hook`). (defun brust-buffer-update-total-lines nil (when (buffer-modified-p) ;; lighten up post-command hook (setq brust-buffer-total-lines (save-excursion (goto-char (point-max)) (format-mode-line "/%l/"))))) ;; Version 1 of the function to buffer-locally initiate the whole process. (defun brust-buffer-total-lines-activate nil (let* ((curr-file (buffer-file-name)) (num-total-lines (with-temp-buffer (insert-file-contents curr-file) (line-number-at-pos (point-max))))) (setq brust-buffer-total-lines num-total-lines)) (add-hook 'post-command-hook #'brust-buffer-update-total-lines nil t)) ;; Version 2 of the function to buffer-locally initiate the whole process. (defun brust-buffer-total-lines-activate nil (setq brust-buffer-total-lines (save-excursion (goto-char (point-max)) (format-mode-line "/%l/"))) (add-hook 'post-command-hook #'brust-buffer-update-total-lines nil t)) ;; Final steps: ;; (add-hook 'text-mode-hook #'brust-buffer-total-lines-activate) (add-hook 'find-file-hook #'brust-buffer-total-lines-activate) (setq global-mode-string '("" brust-buffer-total-lines)))
This strange behaviour can be reproduced in vanilla emacs, just init emacs with
emacs -Q load the previous code and open a file. You will see that the total number of lines is wrong and it is corrected after modifying the buffer.