With point at the beginning of the word you want to replace, e.g., foo
:
C-s C-w M-%
Then type the replacement word, e.g. bar
, then RET
.
Then follow the prompts to query-replace subsequent occurrences of foo
. (You can use !
to replace all of them, for instance.)
To limit query-replace to a paragraph, you can narrow to it (C-x n n
). Alternatively, just quit query-replace after that paragraph (using q
), or quit it at the last replacement (.
).
Explanation:
C-s
starts Isearch (incremental search). An immediate C-w
yanks the text from point to the end of the word at point (e.g. foo
) to the search string, so C-s C-w
searches for that word.
M-%
while searching switches to query-replace
, using the search-string as the text to replace.
A minor shortcut for this question: you can use M-% M-n
instead of C-s C-w M-%
if you use library Replace+ (replace+.el
)
With Replace+, query-replace
and similar commands provide this behavior out of the box. Just use M-n
to insert the word at point - it's the default FROM
pattern.
Actually, the default value can be more than just the word at point. (And you have control over it using options search/replace-region-as-default-flag
,
search/replace-2nd-sel-as-default-flag
, and search/replace-default-fn
.)
And option replace-w-completion-flag
, if non-nil
, provides for
minibuffer completion while you type the arguments. In that case, to
insert a SPC
or TAB
character, you will need to precede it by C-q
.