Function: copy-tree

copy-tree is a byte-compiled function defined in subr.el.gz.

Signature

(copy-tree TREE &optional VECTORS-AND-RECORDS)

Documentation

Make a copy of TREE.

If TREE is a cons cell, this recursively copies both its car and its cdr. Contrast to copy-sequence, which copies only along the cdrs. With the second argument VECTORS-AND-RECORDS non-nil, this traverses and copies vectors and records as well as conses.

Other relevant functions are documented in the vector and list groups.

View in manual

Probably introduced at or before Emacs version 22.1.

Shortdoc

;; list
(copy-tree '(1 (2 3) 4))
    => (1 (2 3) 4)
;; vector
(copy-tree [1 (2 3) [4 5]] t)
    => [1 (2 3) [4 5]]

Aliases

eshell-copy-tree (obsolete since 28.1) cl-copy-tree (obsolete since 24.3) gnus-copy-sequence (obsolete since 27.1)

Source Code

;; Defined in /usr/src/emacs/lisp/subr.el.gz
(defun copy-tree (tree &optional vectors-and-records)
  "Make a copy of TREE.
If TREE is a cons cell, this recursively copies both its car and its cdr.
Contrast to `copy-sequence', which copies only along the cdrs.
With the second argument VECTORS-AND-RECORDS non-nil, this
traverses and copies vectors and records as well as conses."
  (declare (side-effect-free error-free))
  (if (consp tree)
      (let (result)
	(while (consp tree)
	  (let ((newcar (car tree)))
	    (if (or (consp (car tree))
                    (and vectors-and-records
                         (or (vectorp (car tree)) (recordp (car tree)))))
		(setq newcar (copy-tree (car tree) vectors-and-records)))
	    (push newcar result))
	  (setq tree (cdr tree)))
	(nconc (nreverse result)
               (if (and vectors-and-records (or (vectorp tree) (recordp tree)))
                   (copy-tree tree vectors-and-records)
                 tree)))
    (if (and vectors-and-records (or (vectorp tree) (recordp tree)))
	(let ((i (length (setq tree (copy-sequence tree)))))
	  (while (>= (setq i (1- i)) 0)
	    (aset tree i (copy-tree (aref tree i) vectors-and-records)))
	  tree)
      tree)))