[Gllug] Emacs macro to do a replace-regexp

Nix nix at esperi.org.uk
Tue Feb 14 23:18:05 UTC 2006


On Mon, 13 Feb 2006, J. F. announced authoritatively:
> Hello
> 
> I'm new to Emacs and I'm trying to set up a quick way of doing a
> search & replace for a word beginning with &# and ending with a
> semi-colon (ie an HTML entity) in Emacs. But I want to be asked
> everytime whether the search string should be deleted or replaced with
> something else.
> 
> I tried to set up a keyboard macro for the command replace-regexp,
> searching for '\&\#[^;];' (without the quotes). I stopped recording it
> when it asks what it should be replaced with, but this didn't
> work... when running the keyboard macro it goes ahead and replaces
> everything without asking. This is the macro in my .emacs:
> 
> (fset 'findentities
>    [?\M-x ?r ?e ?p ?l ?a ?c ?e ?- ?r ?e ?g ?e ?x ?p return ?\\ ?& ?\\ ?# ?[ ?^ ?\; ?] ?* ?\;])
> 
> Is there a way of running this keyboard macro interactively, where it
> asks what the search string should be replace with? Or should I look
> into LISP?

Lisp is the way here. Asking questions in the minibuffer from macros is
theoretically just about possible but complex enough that you'd need to
be an Emacs hacker to do it (in which case you'd undoubtedly choose do
it in Lisp instead).

Something like

(defun jf-replace-entities (regexp &optional with)
  (interactive "sEntity to search for: \nsEntity to replace with:")
  (let ((with (or with "")))
    (while (re-search-forward (concat "&#" regexp ";") nil t)
      (replace-match with t t))))

should do the trick, once bound to a key. (Note that it's replacing the
*entire* entity string, which is perhaps not useful, but that's what you
asked for! A backreference in the regexp and a use of \N in
`replace-match' would change that.)

(This was loosely derived from code available under `C-h f
replace-regexp').

If you do want to learn elisp, I strongly recommend the emacs-lisp-intro
as a place to start: it's a *very* good introduction to the language.

-- 
`... follow the bouncing internment camps.' --- Peter da Silva
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list