1

If I want to do a replace-regexp I usually start with a isearch-forward-regexp so I can get immediate visual feedback on the search string.

From there I'd like to grab the search string for using in the replace-regexp. Right now all I can see to do is use my OS to copy and paste it. Is there a way to do this built in? I had hoped those commands shared history but it didn't in my experiments.

Or is my whole approach wrong?

(Using spacemacs if that adds anything useful.)

Drew
  • 75,699
  • 9
  • 109
  • 225

1 Answers1

2

Is this for interactive use? I suppose so. As the doc string for replace-regexp says:

    This function is for interactive use only; in Lisp code
    use `re-search-forward' and `replace-match' instead.

Are you really asking about replace-regexp, and not query-replace-regexp?

Because if you use the latter then the answer is included in Isearch by default: Just use C-M-% when you're regexp-isearching, and you immediately switch to query-replace-regexp, using the search regexp as the regexp to search for with query-replace-regexp. And of course with query-replace-regexp you can always hit !, to replace all subsequent matches.

But if you really want to use replace-regexp explicitly then you can use Isearch+ to get the regexp you use with C-M-s, to use it as the regexp to use with replace-regexp. For that, you just use M-w while isearching, to copy the current search pattern to the kill ring. And then use M-x replace-regexp and use C-y, to yank that regexp as the one to use for that command.

If you want this behavior and you don't want to load library Isearch+ then you can just use the code for it:

(defun isearchp-kill-ring-save ()       ; Bound to `M-w' in `isearch-mode-map'.
  "Copy the current search string to the kill ring."
  (interactive)
  (kill-new isearch-string)
  (let ((message-log-max  nil)) (message "Copied search string as kill"))
  (sit-for 1)
  (isearch-update))

(define-key isearch-mode-map "\M-w" 'isearchp-kill-ring-save)
Drew
  • 75,699
  • 9
  • 109
  • 225