Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the color of the mode-line depending on buffer state

Tags:

emacs

Is there a way to dynamically change the color of the mode-line depending on specific conditions e.g. change color if I'm in narrowed view and to a different color if the buffer is read-only

Thank you very much!

like image 936
user673592 Avatar asked Dec 26 '22 02:12

user673592


2 Answers

You can use a post-command-hook and then just evaluate whatever you need and set the mode-line face color. I do this to change between 3 colors depending on which evil-mode state I'm in and if the buffer has any unsaved changes.

(lexical-let ((default-color (cons (face-background 'mode-line)
                                   (face-foreground 'mode-line))))
  (add-hook 'post-command-hook
    (lambda ()
      (let ((color (cond ((minibufferp) default-color)
                         ((evil-insert-state-p) '("#e80000" . "#ffffff"))
                         ((evil-emacs-state-p)  '("#af00d7" . "#ffffff"))
                         ((buffer-modified-p)   '("#006fa0" . "#ffffff"))
                         (t default-color))))
        (set-face-background 'mode-line (car color))
        (set-face-foreground 'mode-line (cdr color))))))
like image 117
d11wtq Avatar answered May 23 '23 05:05

d11wtq


I use this code. It colors the buffer-modified indicator on the left orange if it's read-only and red if it's modified. When you narrow a buffer it colors the line number indicator yellow. Obviously you might want to change the format yourself.

(defface my-narrow-face
  '((t (:foreground "black" :background "yellow3")))
  "todo/fixme highlighting."
  :group 'faces)

(defface my-read-only-face
  '((t (:foreground "black" :background "orange3")))
  "Read-only buffer highlighting."
  :group 'faces)

(defface my-modified-face
  '((t (:foreground "gray80" :background "red4")))
  "Modified buffer highlighting."
  :group 'faces)

(setq-default
 mode-line-format
 '("  "
   (:eval (let ((str (if buffer-read-only
                         (if (buffer-modified-p) "%%*" "%%%%")
                       (if (buffer-modified-p) "**" "--"))))
            (if buffer-read-only
                (propertize str 'face 'my-read-only-face)
              (if (buffer-modified-p)
                  (propertize str 'face 'my-modified-face)
                str))))
   (list 'line-number-mode "  ")
   (:eval (when line-number-mode
            (let ((str "L%l"))
              (if (/= (buffer-size) (- (point-max) (point-min)))
                  (propertize str 'face 'my-narrow-face)
                str))))
   "  %p"
   (list 'column-number-mode "  C%c")
   "  " mode-line-buffer-identification
   "  " mode-line-modes))
like image 20
scottfrazer Avatar answered May 23 '23 05:05

scottfrazer