3

Emacs Lisp has regexp-quote to quote any string to match it literally. Apparently, there is no equivalent function to quote an arbitrary replacement string to use it literally. I mean, what could I use instead of the imaginary regexp-quote-replacement in the following contrived[1] code?

(replace-regexp (regexp-quote "^$") (regexp-quote-replacement "\\&\\?"))

This code would be meant to replace a literal ^$ with a literal \&\?.

--

[1] I know that I could use replace-string in this case to achieve the same result.

Eleno
  • 1,448
  • 11
  • 17

1 Answers1

6

Use a search and replace loop instead.

As the doc of replace-regexp indicates:

This function is for interactive use only;
in Lisp code use re-search-forward and replace-match instead.

One of the advantages of this approach is that replace-match has a LITERAL argument, which does what you're asking for.

(while (search-forward-regexp SOME-RX nil 'noerror)
  ;; This \\1 will be inserted literally as \1
  (replace-match " \\1" nil 'literal))
Malabarba
  • 23,148
  • 6
  • 79
  • 164
  • The question as posed says nothing about not wanting to use the function interactively. This does not really answer the question posed about replace-regexp at all. – Drew Dec 02 '14 at 02:55
  • @Drew (1) The question asks for something analogous to regexp-quote but which can be used for replacements. regexp-quote cannot be used interactively. (2) The example provided was not an interactive call, it was a piece of elisp code. (3) Given (1) and (2), it seems safer to assume the objective is elisp code. I'll be happy to retract if the author says otherwise. – Malabarba Dec 02 '14 at 03:18
  • I guess you're right. Funny that the OP was able to discover regexp-quote and learn about constructs such as \& in the TO-STRING, but apparently never noticed the several notes about the function not being intended for interactive use (the manual is even clearer about that than the doc string). – Drew Dec 02 '14 at 06:00