I want to do simple replacements in a LaTeX source using something like that:
;; test-1
(query-replace-regexp (regexp-quote FOO)
(concat "Foo "
FOO
".")
nil (point-min) (point-max))
;; test-2
(query-replace-regexp (regexp-quote VAR-1)
(concat "Foo "
VAR-2
".")
nil (point-min) (point-max))
FOO
, VAR-1
and VAR-2
could be everything and so I have to keep emacs from complaining about Invalid use of ‘\\’ in replacement text
.
I have tried to use regexp-quote
in the "replacement" part, but it doesn't always work because emacs sometimes complains about invalid use of \\
.
I give my solutions here, but beyond whether the code works, I'm interested in understanding what is the correct way to use FOO
and VAR-2
in the second argument of query-replace-regexp
.
For test-1
I have two solutions:
(query-replace-regexp (concat "\\("
(regexp-quote FOO)
"\\)")
"Foo \\1." nil (point-min) (point-max))
(query-replace-regexp (regexp-quote FOO)
(concat "Foo "
(replace-regexp-in-string "\\\\"
"\\\\\\\\"
(replace-regexp-in-string "\\["
"["
(replace-regexp-in-string "\\]"
"]"
FOO)))
".")
nil (point-min) (point-max))
For test2
I have one solution:
(query-replace-regexp (regexp-quote VAR-1)
(concat "Foo "
(replace-regexp-in-string "\\\\"
"\\\\\\\\"
(replace-regexp-in-string "\\["
"["
(replace-regexp-in-string "\\]"
"]"
VAR-2)))
".")
nil (point-min) (point-max))
These solutions seem very clunky to me, especially the one that resorts to using replace-regexp-in-string
. I can't believe emacs doesn't allow you to do simple replacements like these, so for that I'd like to figure out the correct way to do it.