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

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

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

Instead, I want to write defun that will do this:

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

but it will not work! Although the following works (it adds foo and bar to the texts in brackets):

 (defun HOOK () (interactive) (goto-char 1) (while (search-forward-regexp "(\\(.+?\\))" nil t) (replace-match "(foo \\1 bar)" t nil))) 
+6
source share
4 answers

Thus, 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 their help.

+2
source

Luke's answer almost does the job, but not quite. The original poster wanted all the text enclosed in brackets to be uppercase, while the Luke code converts the code to uppercase AND ALSO deletes the brackets. A small modification to the regular expression provides the correct solution:

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

First of all, you use search-forward in your first function. This takes a string literal, not a regular expression. You should use search-forward-regexp , as in the second function.

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

(\\,(upcase \\1))

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

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

I think you need something like that:

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

It was very helpful, thanks everyone.

In the interest of providing more examples on the Internet, I went from this:

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

(which did not work, but which used regular expressions that worked interactively)

:

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

I needed three backslashes in front of the inner quotation mark.

0
source

Source: https://habr.com/ru/post/890814/


All Articles