Function: flatten-tree

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

Signature

(flatten-tree TREE)

Documentation

Return a "flattened" copy of TREE.

In other words, return a list of the non-nil terminal nodes, or leaves, of the tree of cons cells rooted at TREE. Leaves in the returned list are in the same order as in TREE.

(flatten-tree '(1 (2 . 3) nil (4 5 (6)) 7))
=> (1 2 3 4 5 6 7)

Other relevant functions are documented in the list group.

View in manual

Probably introduced at or before Emacs version 27.1.

Shortdoc

;; list
(flatten-tree '(1 (2 3) 4))
    => (1 2 3 4)

Aliases

eshell-flatten-list (obsolete since 27.1) lpr-flatten-list (obsolete since 27.1) org--flatten-tree hif-flatten (obsolete since 27.1) org-protocol-flatten (obsolete since 9.7) allout-flatten (obsolete since 27.1) message-flatten-list (obsolete since 27.1) flatten-list

Source Code

;; Defined in /usr/src/emacs/lisp/subr.el.gz
(defun flatten-tree (tree)
  "Return a \"flattened\" copy of TREE.
In other words, return a list of the non-nil terminal nodes, or
leaves, of the tree of cons cells rooted at TREE.  Leaves in the
returned list are in the same order as in TREE.

\(flatten-tree \\='(1 (2 . 3) nil (4 5 (6)) 7))
=> (1 2 3 4 5 6 7)"
  (declare (side-effect-free error-free))
  (let (elems)
    (while (consp tree)
      (let ((elem (pop tree)))
        (while (consp elem)
          (push (cdr elem) tree)
          (setq elem (car elem)))
        (if elem (push elem elems))))
    (if tree (push tree elems))
    (nreverse elems)))