2

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?

NickD
  • 27,023
  • 3
  • 23
  • 42
kdb
  • 1,561
  • 12
  • 21
  • This sounds like an X-Y question to me: what are you really trying to do? Would something like `byte-compile-from-buffer` do what you want? – NickD Nov 15 '21 at 04:16
  • @NickD I want to read all forms from a file containing Emacs lisp, whether it is a source file for analysis or a data file with e.g. cached data. Just using `(while (not (eobp)) (push (read (current-buffer)) output-list)` doesn't work, because it will for most files signal `end-of-file', since `read` leaves the point at the end of the form. – kdb Nov 15 '21 at 10:34

0 Answers0