1

I'm writing a loop to perform some interactive replacements on matched strings:

(while (search-forward-regexp "REGEXP" nil t)
  (read-char "Options:...")
  ; Replacements...
  )

and I need the matched string to be "temporarily" highlighted until the replacement has done (or skipped).

What is the best way to get this behaviour?

(I figure out something like this:

(while (search-forward-regexp "REGEXP" nil t)

  (push-mark (match-beginning 0))
  (let ((x (make-overlay (mark) (point))))
    (overlay-put x 'face '(:background "grey20")))

  (read-char "Options:... ")
  (remove-overlays (mark) (point))
)

but I'm pretty sure it is not the best choice)

1

Don't set the mark. Just use (match-beginning 0). You can always let-bind a variable to that, if you're worried about the match-data changing.

(while (search-forward-regexp REGEXP nil t)
  (let* ((beg  (match-beginning 0))
         (xx   (make-overlay beg (point))))
    (overlay-put xx 'face 'YOUR-FACE)
    (read-char "Options:... ")
    (remove-overlays beg (point))))

C-h f push-mark tells you this, at the end:

Novice Emacs Lisp programmers often try to use the mark for the wrong purposes. See the documentation of set-mark for more information.

And C-h f set-mark tells you this, at the end:

Novice Emacs Lisp programmers often try to use the mark for the wrong purposes. The mark saves a location for the user's convenience. Most editing commands should not alter the mark. To remember a location for internal use in the Lisp program, store it in a Lisp variable. Example:

(let ((beg (point))) (forward-line 1) (delete-region beg (point))).
  • 1
    More things to tell: (1) Use only overlays with some id (last two optional args of remove-overlays) otherwise you potentially remove overlays which are unrelated to your stuff. (2) Maybe wrap the setting of overlays in unwind-protect and put remove-overlays in the unwind forms else the overlays remain when the user quits. (3) It depends on the number of highlights whether overlays or text properties are preferable. – Tobias Jun 21 '17 at 15:10
  • @Tobias The highlight is once at time. Also, I looked for a variable for overlay settings... 'cause I figured out to let-bind it but I was not able to find it. – Gabriele Nicolardi Jun 21 '17 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.