Reputation: 1084
I don't understand how to re-use an interactive command in a command I'm writing myself.
I want to make a command that always uses the same arguments to replace-regexp
. It's a shortcut, really.
So I tried to mimic in a function what I'd done interactively on a selected region, namely:
M-x replace-regexp RET ^\(\s *\)\(.*\)\s *$ RET \1 + '\2'
I mimicked it by writing this function:
(defun myH2js ()
"Converts html to an (incomplete) JavaScript String concatenation."
(interactive)
(let (p1 p2)
(setq p1 "^\(\s *\)\(.*\)\s *$" )
(setq p2 "\1 + '\2'" )
(replace-regexp p1 p2 )
)
)
But my function "replaces zero occurrences" of the selected region whereas my interaction rewrites everything exactly as I want.
What am I doing wrong?
Upvotes: 1
Views: 338
Reputation: 781210
You need to double the backslashes in the strings, because backslash is both the string and regular expression escape character:
(defun myH2js (start end)
"Converts html to an (incomplete) JavaScript String concatenation."
(interactive "r")
(let ((p1 "^\\(\\s *\\)\\(.*\\)\\s *$")
(p2 "\\1 + '\\2'"))
(replace-regexp p1 p2 nil start end)
)
)
Note that replace-regexp
is not recommended for use inside programs; the online documentation says:
This function is usually the wrong thing to use in a Lisp program. What you probably want is a loop like this:
(while (re-search-forward regexp nil t) (replace-match to-string nil nil))
which will run faster and will not set the mark or print anything.
Upvotes: 1