emacs-devel
[Top][All Lists]
Advanced

[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: Tue, 05 Feb 2019 06:57:52 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux)

Stefan Monnier <address@hidden> writes:

>>> Why two functions instead of just one?
>> You mean by copying the region from the source buffer to the temporary
>> buffer, and then a single function could act just in there?
>
> No, a function which directly returns the text to insert in the form
> of a string (or a buffer, I guess).

Like so?

--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---

In the `json-pretty-print' scenario, that would indeed be even easier
(because `json-encode' returns a string anyway):

--8<---------------cut here---------------start------------->8---
(defun json-pretty-print (begin end)
  "Pretty-print selected region."
  (interactive "r")
  (let ((json-encoding-pretty-print t)
        ;; Distinguish an empty objects from 'null'
        (json-null :json-null)
        ;; Ensure that ordering is maintained
        (json-object-type 'alist))
    (replace-region-contents
     begin end
     (lambda () (json-encode (json-read))))))
--8<---------------cut here---------------end--------------->8---

I don't have a preference.  I guess Eli might argue that this version
encourages passing strings around instead of using buffers.  I'd explain
in the doc string that in the case of a string return value, we're going
thru a temporary buffer anyway, so if your REPLACE-FN ends in
(buffer-substring ...), you're clearly doing something wrong...

Bye,
Tassilo



reply via email to

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