Function: replace-region-contents
replace-region-contents is a byte-compiled function defined in
subr-x.el.gz.
Signature
(replace-region-contents BEG END REPLACE-FN &optional MAX-SECS MAX-COSTS)
Documentation
Replace the region between BEG and END using REPLACE-FN.
REPLACE-FN runs on the current buffer narrowed to the region. It should return either a string or a buffer replacing the region.
The replacement is performed using replace-buffer-contents
which also describes the MAX-SECS and MAX-COSTS arguments and the
return value.
Note: If the replacement is a string, it'll be placed in a
temporary buffer so that replace-buffer-contents can operate on
it. Therefore, if you already have the replacement in a buffer,
it makes no sense to convert it to a string using
buffer-substring or similar.
Probably introduced at or before Emacs version 27.1.
Source Code
;; Defined in /usr/src/emacs/lisp/emacs-lisp/subr-x.el.gz
(defun replace-region-contents (beg end replace-fn
&optional max-secs max-costs)
"Replace the region between BEG and END using REPLACE-FN.
REPLACE-FN runs on the current buffer narrowed to the region. It
should return either a string or a buffer replacing the region.
The replacement is performed using `replace-buffer-contents'
which also describes the MAX-SECS and MAX-COSTS arguments and the
return value.
Note: If the replacement is a string, it'll be placed in a
temporary buffer so that `replace-buffer-contents' can operate on
it. Therefore, if you already have the replacement in a buffer,
it makes no sense to convert it to a string using
`buffer-substring' or similar."
(save-excursion
(save-restriction
(narrow-to-region beg end)
(goto-char (point-min))
(let ((repl (funcall replace-fn)))
(if (bufferp repl)
(replace-buffer-contents repl max-secs max-costs)
(let ((source-buffer (current-buffer)))
(with-temp-buffer
(insert repl)
(let ((tmp-buffer (current-buffer)))
(set-buffer source-buffer)
(replace-buffer-contents tmp-buffer max-secs max-costs)))))))))