B.2 yank

After learning about current-kill, the code for the yank function is almost easy.

The yank function does not use the kill-ring-yank-pointer variable directly. It calls insert-for-yank which calls current-kill which sets the kill-ring-yank-pointer variable.

The code looks like this:

(defun yank (&optional arg)
  "Reinsert (\"paste\") the last stretch of killed text.
More precisely, reinsert the stretch of killed text most recently
killed OR yanked.  Put point at end, and set mark at beginning.
With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
With argument N, reinsert the Nth most recently killed stretch of killed
text.

When this command inserts killed text into the buffer, it honors
`yank-excluded-properties' and `yank-handler' as described in the
doc string for `insert-for-yank-1', which see.

See also the command `yank-pop' (\\[yank-pop])."
  (interactive "*P")
  (setq yank-window-start (window-start))
  ;; If we don't get all the way thru, make last-command indicate that
  ;; for the following command.
  (setq this-command t)
  (push-mark (point))
  (insert-for-yank (current-kill (cond
                                  ((listp arg) 0)
                                  ((eq arg '-) -2)
                                  (t (1- arg)))))
  (if (consp arg)
      ;; This is like exchange-point-and-mark, but doesn't activate the mark.
      ;; It is cleaner to avoid activation, even though the command
      ;; loop would deactivate the mark because we inserted text.
      (goto-char (prog1 (mark t)
                   (set-marker (mark-marker) (point) (current-buffer)))))
  ;; If we do get all the way thru, make this-command indicate that.
  (if (eq this-command t)
      (setq this-command 'yank))
  nil)

The key expression is insert-for-yank, which inserts the string returned by current-kill, but removes some text properties from it.

However, before getting to that expression, the function sets the value of yank-window-start to the position returned by the (window-start) expression, the position at which the display currently starts. The yank function also sets this-command and pushes the mark.

After it yanks the appropriate element, if the optional argument is a CONS rather than a number or nothing, it puts point at beginning of the yanked text and mark at its end.

(The prog1 function is like progn but returns the value of its first argument rather than the value of its last argument. Its first argument is forced to return the buffer’s mark as an integer. You can see the documentation for these functions by placing point over them in this buffer and then typing C-h f (describe-function) followed by a RET; the default is the function.)

The last part of the function tells what to do when it succeeds.