Node:copy-to-buffer, Next:, Previous:More Complex, Up:More Complex

5.1 The Definition of copy-to-buffer

After understanding how append-to-buffer works, it is easy to understand copy-to-buffer. This function copies text into a buffer, but instead of adding to the second buffer, it replaces the previous text in the second buffer. The code for the copy-to-buffer function is almost the same as the code for append-to-buffer, except that erase-buffer and a second save-excursion are used. (See The Definition of append-to-buffer, for the description of append-to-buffer.)

The body of copy-to-buffer looks like this

(interactive "BCopy to buffer: \nr")
  (let ((oldbuf (current-buffer)))
      (set-buffer (get-buffer-create buffer))
        (insert-buffer-substring oldbuf start end)))))

This code is similar to the code in append-to-buffer: it is only after changing to the buffer to which the text will be copied that the definition for this function diverges from the definition for append-to-buffer: the copy-to-buffer function erases the buffer's former contents. (This is what is meant by `replacement'; to replace text, Emacs erases the previous text and then inserts new text.) After erasing the previous contents of the buffer, save-excursion is used for a second time and the new text is inserted.

Why is save-excursion used twice? Consider again what the function does.

In outline, the body of copy-to-buffer looks like this:

(let (bind-oldbuf-to-value-of-current-buffer)
  (save-excursion         ; First use of save-excursion.
      (save-excursion     ; Second use of save-excursion.

The first use of save-excursion returns Emacs to the buffer from which the text is being copied. That is clear, and is just like its use in append-to-buffer. Why the second use? The reason is that insert-buffer-substring always leaves point at the end of the region being inserted. The second save-excursion causes Emacs to leave point at the beginning of the text being inserted. In most circumstances, users prefer to find point at the beginning of inserted text. (Of course, the copy-to-buffer function returns the user to the original buffer when done--but if the user then switches to the copied-to buffer, point will go to the beginning of the text. Thus, this use of a second save-excursion is a little nicety.)