I want to search and replace a block of text with a "query-like" approach all at once.
For example, if I have
\emph{``Foo $\bar$ baz''}
to be replaced by
\emph{Foo $\bar$ baz}
using a "query-like" approach all at once, how could I do?
I have tried something like this:
(defun foo ()
(interactive)
;; \emph{``Foo''} --> \emph{Foo}
(goto-char (point-min))
(while (re-search-forward "\\\\emph{``" nil t)
(save-excursion
(let* ((pos1 (copy-marker (match-beginning 0)))
(pos2 (copy-marker (progn
(goto-char (- (match-end 0) 3))
(forward-pexp)
(point))))
(text (buffer-substring-no-properties (+ pos1 8) (- pos2 3))))
(query-replace-regexp (concat "\\\\emph{``"
text
"''}")
(concat "\\\\emph{"
(regexp-quote text)
"}")
nil pos1 pos2)))))
but it does not work if there are chars to be escaped (text
could be everything, even chars to be escaped, like \
in LaTeX
macro or [ ]
or $...$
or other).
It works if there are no chars to be escaped.
I have just found a solution for this example with a "query-like" approach, i.e.
(query-replace-regexp "\\\\emph{``"
"\\\\emph{" nil pos1 pos2)
(query-replace-regexp "''}"
"}" nil (- pos2 3) pos2)
but it is not all at once. I would like to have only one call to query-replace-regexp
.
Note
In this answer I have found a solution to be used for solving this question.