0

When using replace-string from the M-x while having some text selected, it only operates on that selection (specifically, on an Evil visual selection, in my case). However, if I put the same replacement in a function in my init.el, like

(defun my-custom-replace ()
    "Replaces 'foo' with 'bar'."
    (interactive)
    (replace-string "foo" "bar") )

it always seems to modify the entire buffer instead. How can I get this to respect the selection?

1

Please consult the documentation for replace-string (you get the doc with C-h f replace-string RET). The Section on the arguments START and END clearly says how to reproduce the interactive behavior in elisp functions:

Operates on the region between START and END (if both are nil, from point to the end of the buffer). Interactively, if Transient Mark mode is enabled and the mark is active, operates on the contents of the region; otherwise from point to the end of the buffer’s accessible portion.

So the corrected version of your code is:

(defun my-custom-replace ()
    "Replaces 'foo' with 'bar'."
    (interactive)
    (replace-string "foo" "bar" nil (region-beginning) (region-end)) )

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.