Search code examples
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:

    • C-h i opens the Info directory
    • Navigate (or use m) to the Emacs one
    • Press i and search for cursor, or search in the Index directly, or search with s the "cursor" regexp ... until you find the "Cursor Display" section. If you forgot how to do that, as usual in this kind of mode, try pressing h, or ?, or C-h m (they don't necessarily do the same thing, but are all helping you)
    • In this node, you find that

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

    • Click on the "Face Customization" link to view how to do it via the "Customization Interface". To do it programmatically (i.e. as I did above, using the set-face-attribute function), repeat the steps above to view how to do it.
    • You can also use the function set-face-background, a simple wrapper around set-face-attribute. To discover this function, you can (and should) also use Emacs: a proper completion/selection system, or the function apropos-command, bound to C-h a, with e.g. the search "face background", and the aforementioned function is then immediately found.
    • Aaaand if you forgot how to look for help, then use C-h C-h. This command is shown in the tutorial, itself accessible from the menus, or from the initial buffer when starting Emacs (by default), or ... etc.