Alex Rivera | Logout

Emacs: how do I replace-regexp with a lisp function in a defun?

Asked 2011-06-18T12:09:38.743
9

For example I want to make all text in parenthesis, (), UPCASE. It's trivial to do the following interactively:

M-x query-replace-regexp
replace: "(\(.+?\))"
with   : "(\,(upcase \1))"

Instead I want to write a defun which will do that:

(defun upcs ()
  (interactive)
  (goto-char 1)
  (while (search-forward "(\\(.+?\\))" nil t) (replace-match "(\\,(upcase \\1))" t nil)))

but it doesn't work! While the following works (it appends foo and bar to the parenthesized texts):

(defun HOOK ()
  (interactive)
  (goto-char 1)
  (while (search-forward-regexp "(\\(.+?\\))" nil t) (replace-match "(foo \\1 bar)" t nil)))
Edit
Report

2 Answers

6

So this solves the problem.

(defun put-in-par (str)
  (concat "(" str ")"))

(defun upcs-luke ()
    (interactive)
    (goto-char 1)
        (while (search-forward-regexp "(\\([^\\)]+\\))" nil t) 
            (replace-match (put-in-par (upcase (match-string 1))) t nil)))

Thanks to BillC and Luke Girvin for help.

answered 2011-06-20T15:06:41.680
3

This was very useful, thanks all.

In the interest of putting more examples on the web, I went from this:

(replace-regexp "\([\%\)\”\"]\..?\)[0-9]+" "\1")

(which didn't work, but which used the regexps that did work in interactive mode)

to this:

(while (re-search-forward "\\([\\%\\\"\\”]\\)\\.?[0-9]+" nil t)
    (replace-match (match-string 1) t nil))

I needed three backslashes before the internal quotation mark.

answered 2012-03-25T07:14:01.237

Your Answer