Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

emacs

lisp

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)))
like image 310
Adobe Avatar asked Jun 18 '11 12:06

Adobe


2 Answers

Luke's answer almost does the job but not quite. The original poster wanted all the text that was enclosed in parenthesis converted to upper case while Luke's code converts the code to upper case AND ALSO removes the parenthesis. A slight modification to the regex provides the correct solution:

(defun upcs ()
(interactive)
(goto-char 1)
    (while (search-forward-regexp "\\([^\\)]+\\)" nil t) 
        (replace-match (upcase (match-string 1)) t nil)))
like image 99
zev Avatar answered Oct 23 '22 01:10

zev


First of all, you're using search-forward in your first function. This takes a string literal rather than a regular expression. You should be using search-forward-regexp, as you do in your second function.

Secondly, while this code is valid as a replace value for query-replace-regexp, I don't think you can pass it to replace-match:

(\\,(upcase \\1))

You can get the value of the match found by search-forward-regexp using the match-string function.

Finally, I'm not sure your search regular expression is correct.

I think you need something along these lines:

(defun upcs ()
    (interactive)
    (goto-char 1)
        (while (search-forward-regexp "(\\([^\\)]+\\))" nil t) 
            (replace-match (upcase (match-string 1)) t nil)))
like image 6
Luke Girvin Avatar answered Oct 23 '22 01:10

Luke Girvin