[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [RFC]: replace-region-contents

From: Tassilo Horn
Subject: Re: [RFC]: replace-region-contents
Date: Wed, 06 Feb 2019 12:10:21 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux)

Marcin Borkowski <address@hidden> writes:

>>>> --8<---------------cut here---------------start------------->8---
>>>> (defun replace-region-contents (beg end replace-fn)
>>>>   (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)
>>>>      (let ((source-buffer (current-buffer)))
>>>>        (with-temp-buffer
>>>>          (insert repl)
>>>>          (let ((tmp-buffer (current-buffer)))
>>>>            (set-buffer source-buffer)
>>>>            (replace-buffer-contents tmp-buffer)))))))))
>>>> --8<---------------cut here---------------end--------------->8---
>>> LGTM
>> How would I actually use that version with a replace-fn returning a
>> buffer and not a string?  It looks to me that I need to do the whole
>> ceremony of creating a temporary buffer, setting buffers, and ensuring
>> that the temporary buffer is killed even in the case of an abnormal exit
>> myself.  That's the hassle my original version tried to eliminate in the
>> first place...
> I did not follow the whole thread, but why wouldn't `with-temp-buffer'
> be a suitable candidate to conduct exactly the ceremony you mentioned?

You cannot use `with-temp-buffer' inside replace-fn and then return that
temp buffer, because it'll be killed as soon as control flow escapes it.
So you need to define your replace-fn in the lexical scope of an already
established `with-temp-buffer' form.  But since you will need to access
the source buffer, you need to manually arrange in which buffer to
operate what.

> Also, at least sometimes, buffers are better than strings to perform
> e.g. replacements.

Yes, sure, although replacements could be performed in the source buffer


reply via email to

[Prev in Thread] Current Thread [Next in Thread]