[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
RE: A query-replace question
From: |
Drew Adams |
Subject: |
RE: A query-replace question |
Date: |
Thu, 9 Dec 2010 00:43:03 -0800 |
> In a large .tex file, I wish to replace all `x' with `a', but
> only those occurrences of x that lay between two dollars symbols:
> e.g., $x = y$. Could that be ever possible with Emacs, and how?
Yes. Use Icicles search: `C-`' (command `icicle-search').
C-` \$[^$]+\$ RET
That enters a context regexp that matches `$' followed by one or more non-`$'
chars followed by `$'. Your search-and-replace will then be limited to matches
of this regexp.
You can show all matches by typing `x' in the minibuffer. You can hit `S-TAB'
to see the matches as completion candidates in *Completions* (optional). You
can visit them in order by hitting `C-next' (Control + the `next' key).
You can replace the current match you are visiting by hitting `C-S-RET'.
However, you first need to hit `M-_' to toggle (turn off) replacement of the
whole match. That is, if you don't use `M-_' to turn the default replacement
mode off, then everything matching `$...x...$' will get replaced, not just the
`x'.
After you hit `C-S-RET' you are prompted for the replacement text you want -
type `y'. Each time you then hit `C-S-RET' the next `x' within a context match
is replaced. When there are no more `x' matches within a context match,
`C-S-RET' replaces the first `x' match in the next context match, and so on.
IOW, just repeat `C-S-RET' to keep replacing `x' occurrences within your $...$
contexts. (You are prompted for the `y' replacement only once, and you only
need to use `M-_' once.)
If you want to replace *all* `x' occurrences in such contexts at once, just hit
`M-|' - no need to repeat `C-S-RET, no need to visit any occurrences.
Summary:
1. Define the contexts you want to search, using a regexp - `\$[^$]+\$'.
2. Use `M-_' if necessary to make sure you will not be replacing whole context
matches. It's just a toggle.
3. Type the text you want to replace: `x'.
4. Use `C-next' to cycle to a context match where you want to replace one or
more `x's.
5. Use `C-S-RET' to replace the first `x' in the context. Repeat to replace the
next one, etc. For the first replacement you are prompted for the replacement
text (`y').
Instead of #5, you can use `M-|' to replace all occurrences of `x' within all
context matches in the buffer.
More explanation here:
http://www.emacswiki.org/emacs/Icicles_-_Search-And-Replace