[PRL] emacs question

Eli Barzilay eli at barzilay.org
Thu Dec 30 21:45:18 EST 2004


On Dec 30, Dave Herman wrote:
> I'm getting good at replace-regexp now, but is there a good way to
> apply an arbitrary procedure to all matches of a regexp in an emacs
> buffer?  Preferably interactively.
> 
> For example, I'd like to apply uppercase-region (or whatever) to all
> strings that match some regexp.

There is `query-replace-regexp-eval' that can do some of these things,
but it might be simpler to do it yourself -- the documentation for
`replace-regexp' will tell you that the equivalent code is:

  (while (re-search-forward REGEXP nil t)
    (replace-match TO-STRING nil nil))

so you can do something like:

  (while (re-search-forward REGEXP nil t)
    (replace-match (upcase (match-string 0)) nil nil))

but this will not be interactive like the above.


Personally, I find that easy access to keyboard macros is the best
solution for such things, especially if you combine it with advanced
things like regexp-replace.  For this particular thing I'd do this:

1. Search the buffer and make sure there are no occurrences of "<<<"
   or ">>>"

2. Do a standard query-replace-regexp and replace my pattern "\(...\)"
   with something like "<<<\0>>>", interactively choose only regions
   that I want to upcase.

3. Record a keyboard macro that:
   1. Searches for "<<<",
   2. Removes it,
   3. Searches for the following ">>>", the mark will be left at the
      previous location,
   4. Remove it too,
   5. Use the keybinding to do an upcase (usually C-x C-u).

This sounds a little complex, but it's really quite simple and quick,
and in many cases it is much faster than remembering arcane commands.

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!



More information about the PRL mailing list