I'm looking to create a keybinding that will perform the following shortcut:

  • call isearch-forward-symbol-at-point
  • call query-replace-regexp

It's basically a shortcut for the following key combo: M-s . then C-M $

Here is my attempt, but my elisp is rather weak:

(global-set-key (kbd "C-x r")
    (lambda ()
      (query-replace-regexp (isearch-forward-symbol-at-point))))

Any suggestions?

  • 1
    You may be interested in looking at iedit (on MELPA).
    – rprimus
    Jun 13, 2019 at 16:26

2 Answers 2


You should/cannot use the interactive commands isearch-forward-symbol-at-point and query-replace-regexp in that way to define a new function.

For an instance isearch-forward-symbol-at-point does not return the symbol at point and query-replace-regexp requires a TO argument if called non-interactively.

I think the following Elisp function comes very close to what you want. It starts a query-replace-regexp with the symbol at point as default regexp. You only need to input the replacement text, i.e., the new name.

(defun query-replace-symbol-at-point ()
  "Start `query-replace-regexp' with symbol at point as default."
  (let ((sym (symbol-at-point)))
    (when sym
      (push (cons (format "\\_<%s\\_>" sym) "") query-replace-defaults)
      (call-interactively #'query-replace-regexp))))

This is the key binding that does what you want, out of the box: M-s . C-M-%.

  • The M-s . part starts searching with isearch-forward-symbol-at-point.

  • The C-M-% part starts query-replace-regexp, the current search string as the old text, to search for and replace.

(C-M-$ is undefined in isearch-mode-map (and the global map).)

  • Yes, but is there a way to make that key binding shorter? I basically want a single key combo that I can push to perform a "refactor the variable under my cursor".
    – modulitos
    Jun 16, 2019 at 4:13
  • As @Tobias said in his answer, these commands are for interactive use - they don't chain together programmatically. But you can do as he did: set up the regexp for replacement and then call query-replace-regexp. You are not really searching for the symbol at point - you are using it just to establish the regexp to use for replacement. Alternatively, you could perhaps define a keyboard macro using the two commands directly (possibly with recursive editing). But it's easier to just do it in Lisp.
    – Drew
    Jun 16, 2019 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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