emacstext-cursor

How to change the cursor's color to red when reaching row 90 in Emacs Lisp?


I have opened a buffer with some text on 100 lines.

I would like to change the color of my cursor to red when I reach the row 90?

How would such Elisp function I could put in my init file look like?

Let's say the hook should work for all modes, for simplicity.


Solution

  • Disclaimer: I did not know how to do that before answering. I will tell you how I did find the solution using Emacs.

    You can change the colour of the cursor by changing the :background attribute of the cursor face (as seen when using describe-face, or by reading the "Cursor Display" section of the Emacs manual - which is built-in and can be read from Emacs)

    I am not aware of a "good" hook that could be used to do this, though. An idea could be to use post-command-hook, but it might be slow.

    A (possibly, and probably bad, not thoroughly tested) solution:

    (defun my/switch-cursor-color ()
      (if (< (line-number-at-pos) 90)
          (set-face-attribute 'cursor nil :background "#abcd12") ;; hex-code for your colour
        (set-face-attribute 'cursor nil :background "#1234ef")))
    
    (add-hook 'post-command-hook 'my/switch-cursor-color)
    

    Of course, to be safe, you should probably do other checks (what happens in pdf-view-mode/doc-view-mode, etc), but this "should work".


    How to get all this information: Inside Emacs:

    To customize its color, change the ‘:background’ attribute of the face named ‘cursor’ (see Face Customization).