Search code examples
emacsbookmarks

How to highlight a particular line in emacs?


I need to highlight facility for emacs in order to mark some lines in file while working with it. It should be smth like M-s h l but should work based on line number, not on a regexp. I want to highlight a current line, but the hl-line-mode is not suitable, as I need to highlight many lines, every time I press a specific key on each of them.


Solution

  • I just quickly wrote the following:

    (defun find-overlays-specifying (prop pos)
      (let ((overlays (overlays-at pos))
            found)
        (while overlays
          (let ((overlay (car overlays)))
            (if (overlay-get overlay prop)
                (setq found (cons overlay found))))
          (setq overlays (cdr overlays)))
        found))
    
    (defun highlight-or-dehighlight-line ()
      (interactive)
      (if (find-overlays-specifying
           'line-highlight-overlay-marker
           (line-beginning-position))
          (remove-overlays (line-beginning-position) (+ 1 (line-end-position)))
        (let ((overlay-highlight (make-overlay
                                  (line-beginning-position)
                                  (+ 1 (line-end-position)))))
            (overlay-put overlay-highlight 'face '(:background "lightgreen"))
            (overlay-put overlay-highlight 'line-highlight-overlay-marker t))))
    
    
    (global-set-key [f8] 'highlight-or-dehighlight-line)
    

    (Here find-overlays-specifying came from the manual page)

    It will highlight current line, and when used again it will remove it.

    Maybe the following could be useful as well: removing all your highlight from the buffer (could be dangerous, you might not want it if you highlight important things)

    (defun remove-all-highlight ()
      (interactive)
      (remove-overlays (point-min) (point-max))
      )
    
    (global-set-key [f9] 'remove-all-highlight)