It seems that replace-regexp
has a different behavior if called interactively and not, but I do not understand why, and how to get the wanted behavior.
What I want is the non-interactive equivalent of:
M-x replace-regexp RET foo1 RET foo\#
which, if called on buffer
foo1
foo1
foo1
creates
foo0
foo1
foo2
Now, non-interactively, the naive
(replace-regexp "foo1" "foo\\#")
yields
"Invalid use of '\' in replacement text"
The same happens with
(funcall-interactive "foo1" "foo\\#")
And singling or doubling the backslashes give the expected (unwanted) results:
(replace-regexp "foo1" "foo\#")
;; foo#
;; foo#
;; foo#
(replace-regexp "foo1" "foo\\\\#")
;; foo\#
;; foo\#
;; foo\#
Of course, running call-interactively
works, but in my use-case the regexp and replacement string will be crafted by elisp code.
Running a loop searching and replacing would probably work, but is it really the only solution? It seems hard to believe.
replace-regexp
. It is essentially(query-replace-compile-replacement "foo\\#" t)
which returns(replace-eval-replacement concat "foo" (number-to-string replace-count))
(resolved over several function calls). The documentation ofreplace-regexp
says quite clearly that\#
only works in interactive calls and that you should usere-search-forward
andreplace-match
instead in emacs-lisp code.(query-replace-compile-replacement to-string t)
seems to suit my purposes perfectly. Are there any pitfalls that I don't see yet? And in any case, would you mind turning your comment with its great explanation into an answer?query-replace-compile-replacement
is a documented function fromreplace.el
. There are no double-slashes in the name and the code is not marked as internal. Therefore, usage of the function should be safe. Have fun!