Go to the first, previous, next, last section, table of contents.


copy-region-as-kill

The copy-region-as-kill function copies a region of text from a buffer and saves it in a variable called the kill-ring.

If you call copy-region-as-kill immediately after a kill-region command, Emacs appends the newly copied text to the previously copied text. This means that if you yank back the text, you get it all, from both this and the previous operation. On the other hand, if some other command precedes the copy-region-as-kill, the function copies the text into a separate entry in the kill ring.

Here is the complete text of the version 18 copy-region-as-kill, formatted for clarity with several comments added:

(defun copy-region-as-kill (beg end)
  "Save the region as if killed, but don't kill it."
  (interactive "r")

  (if (eq last-command 'kill-region)

      ;; then-part: Combine newly copied text
      ;;   with previously copied text.
      (kill-append (buffer-substring beg end) (< end beg))

    ;; else-part: Add newly copied text as a new element
    ;;   to the kill ring and shorten the kill ring if necessary.
    (setq kill-ring
          (cons (buffer-substring beg end) kill-ring))
    (if (> (length kill-ring) kill-ring-max) 
        (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))

  (setq this-command 'kill-region)
  (setq kill-ring-yank-pointer kill-ring))

As usual, this function can be divided into its component parts:

(defun copy-region-as-kill (argument-list)
  "documentation..."
  (interactive "r")
  body...)

The arguments are beg and end and the function is interactive with "r", so the two arguments must refer to the beginning and end of the region. If you have been reading though this document from the beginning, understanding these parts of a function is almost becoming routine.

The documentation is somewhat confusing unless you remember that the word `kill' has a meaning different from its usual meaning.

The body of the function starts with an if clause. What this clause does is distinguish between two different situations: whether or not this command is executed immediately after a previous kill-region command. In the first case, the new region is appended to the previously copied text. Otherwise, it is inserted into the beginning of the kill ring as a separate piece of text from the previous piece.

The last two lines of the function are two setq expressions. One of them sets the variable this-command to kill-region and the other sets the variable kill-ring-yank-pointer to point to the kill ring.

The body of copy-region-as-kill merits discussion in detail.


Go to the first, previous, next, last section, table of contents.