;;;;This is in reference to
;;;mastodon.sdf.org/@[email protected]/109367737370448977

(setq *read-eval* nil)

(defun field-from-end (stream column) "
(field-from-end stream column)
Reads characters from the end of the stream,
chomps up to one trailing newline.
When a newline is found, READs the columnth last tab position.
"
(let ((length (file-length stream)))
 (let ((char-reader
        (let ((last-position length))
         (when (char= #\newline (progn (file-position stream (1- length))
                                      (read-char stream)))
              (decf last-position))
         (lambda ()
                (unless (zerop last-position)
                 (values (progn (file-position stream (decf last-position))
                               (read-char stream))
                        last-position))))))
  (let ((tabs-found (list)))
   (loop (multiple-value-bind (char position) (funcall char-reader)
          (cond ((null char) (error "Beginning of file reached"))
                ((char= #\tab char) (push position tabs-found))
                ((char= #\newline char) (push position tabs-found)
                                       (file-position stream
                                                     (nth column
                                                         (progn tabs-found)))
                                       (return-from field-from-end (read stream)))
                ((characterp char))
                (t (error "Something else happened")))))))))

(defun eg () "
(eg)
clobbers a file named test.txt.
Uses that file to exhibit last-row column seeks.
"
(with-open-file (out #p"test.txt" :direction :output
                                 :if-exists :Supersede
                                 :if-does-not-exist :create)
 (format out "foo      bar     baz
buz     bizaz   biz
frob    ulus    ly
featherless     biped   charlie"))
(with-open-file (in #p"test.txt")
 (prin1 (field-from-end in 0))
 (prin1 (field-from-end in 1))
 (prin1 (field-from-end in 2)))
(terpri))

(time (eg))

(quit)