1

Currently, I am doing the replacement of the word under the cursor on a script using:

(setq bounds (bounds-of-thing-at-point 'word))
(setq pos1 (car bounds))
(setq pos2 (cdr bounds))
(delete-region pos1 pos2)
(insert newword)

But this does not preserve the case pattern of the original word. The function replace-match would preserve case, but it would require me to do a search before; something like this:

(left-word)
(search-forward originalword)
(replace-match newword)

Is there a replace command which would allow me to replace the word at point preserving the original word pattern case? If not, am I missing a simple way to write one?

6

The replace-match function is your best bet. It's a C primitive and that's where the case preservation logic is implemented.

replace-match replaces the text indicated by the match data. You can call set-match-data to set the match data to bounds that don't result from a search.

(save-match-data
  (let ((bounds (bounds-of-thing-at-point 'word)))
    (set-match-data (list (car bounds) (cdr bounds)))
    (replace-match new-word)))
  • My understanding of the doc is that if using integers instead of markers like you do, the buffer itself should be added at the end of the list. Apparently this is not necessary. – JeanPierre Jul 15 '16 at 6:25

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.