What is the correct way to use (read (current-buffer))
to read from a buffer until the end of the file is reached?
When no forms remain in a buffer, Emacs signals an error:
(with-temp-buffer
(save-excursion
(insert "(first) (second) ;; end")
(goto-char (point-min))
(list (read (current-buffer))
(read (current-buffer))
(condition-case err
(read (current-buffer))
(error err)))))
;; -> ((first) (second) (end-of-file))
However, the same error is signaled, when encountering unbalanced parentheses, e.g. in
(with-temp-buffer
(save-excursion
(insert "(first) (second) (unfinished form")
(goto-char (point-min))
(list (read (current-buffer))
(read (current-buffer))
(condition-case err
(read (current-buffer))
(error err)))))
;; -> ((first) (second) (end-of-file))
On the other hand, the form
(read (concat "(" (buffer-string) "\n)"))
will return end-of-file
, if there are unclosed parentheses, but will incorrectly accept unopened parentheses.
What would be the preferred way to read lisp forms from a file, while detecting broken syntax?