Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

How do I replace current word under cursor in Emacs?

I know that I can use query-replace or replace-string but every time I do so I have to type entire string to be replaced, this is just annoying.

Vi has equivalent command cword and I can use a shortcut to pull the word under cursor for replacement:

nmap <leader>z :%s#\<<C-r>=expand("<cword>")<CR>\>#

Anybody know how to do it with Emacs?

share|improve this question
Check out… –  Emanuel Berg Oct 14 '12 at 21:31

3 Answers 3

up vote 1 down vote accepted

Use copy-paste: M-d C-_ M-x replace-string RET C-y (kill-word, undo, replace-string, yank). If you've already started the replacement, you can switch back to the original buffer to do the copy-paste with the usual window or buffer switching commands: M-x replace-string RET … C-x o M-d C-_ C-x o C-y. You can use a prefix argument on M-d (e.g. ESC 4 2 M-d) to replace multiple words.

If you're planning to replace one or more words at the cursor, you can instead start from incremental search (C-s), use C-w to start searching the word under the cursor, then press M-% to switch to replace-string.

share|improve this answer

Incremental search has this feature, but the replace functions don't. Fortunately, incremental search does have a way to switch to replace mode once you've selected a search term. So:

  • Press C-s to switch to incremental search mode
  • Press C-w to yank the current word into the search buffer You can keep pressing it to append multiple words, and you can also use C-M-y to yank individual characters and C-y to yank whole lines
  • Press M-% to switch to replace mode using the search buffer you've already constructed

As you probably know from using M-% normally, this is a query replace mode where it prompts you for what to do with each match. If you just want to replace them all, hit ! on the first match

share|improve this answer
;; query-replace current word
(defun qrc (replace-str)
   (interactive "sDo query-replace current word with: ")
   (let ((end (point)))
      (kill-ring-save (point) end)
      (query-replace (current-kill 0) replace-str) ))
share|improve this answer
This solution works nicely and is much more useful than being told how to do it manually. I'm way too lazy to be bothered with copy-and-paste. –  Paul Coccoli Jun 29 at 17:09

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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