Function: string-lines

string-lines is a byte-compiled function defined in subr.el.gz.

Signature

(string-lines STRING &optional OMIT-NULLS KEEP-NEWLINES)

Documentation

Split STRING into a list of lines.

If OMIT-NULLS, empty lines will be removed from the results. If KEEP-NEWLINES, don't strip trailing newlines from the result lines.

Other relevant functions are documented in the string group.

View in manual

Probably introduced at or before Emacs version 28.1.

Shortdoc

;; string
(string-lines "foo\n\nbar")
    => ("foo" "" "bar")
  (string-lines "foo\n\nbar" t)
    => ("foo" "bar")

Source Code

;; Defined in /usr/src/emacs/lisp/subr.el.gz
(defun string-lines (string &optional omit-nulls keep-newlines)
  "Split STRING into a list of lines.
If OMIT-NULLS, empty lines will be removed from the results.
If KEEP-NEWLINES, don't strip trailing newlines from the result
lines."
  (if (equal string "")
      (if omit-nulls
          nil
        (list ""))
    (let ((lines nil)
          (start 0))
      (while (< start (length string))
        (let ((newline (string-search "\n" string start)))
          (if newline
              (progn
                (when (or (not omit-nulls)
                          (not (= start newline)))
                  (let ((line (substring string start
                                         (if keep-newlines
                                             (1+ newline)
                                           newline))))
                    (when (not (and keep-newlines omit-nulls
                                    (equal line "\n")))
                      (push line lines))))
                (setq start (1+ newline)))
            ;; No newline in the remaining part.
            (if (zerop start)
                ;; Avoid a string copy if there are no newlines at all.
                (push string lines)
              (push (substring string start) lines))
            (setq start (length string)))))
      (nreverse lines))))