1

Simple question, I think: How can I calculate the length of a line in emacs lisp? It seems like there should be a function for this, but I can't find it. What I'm using right now is something like this:

(-
 (progn
   (end-of-line)
   (current-column))
 (progn
   (beginning-of-line)
   (current-column)))

But this feels clumsy.

So is there a standard way to do this? And are there any subtleties I should be aware of (i.e. regarding encoding, tabs, or anything like that)?

Actually for my purposes, it would be just as handy to simply calculate if a line is empty. Is there a function for that?

Whatever method I use, it needs to be pretty fast. I need to calculate this for every line in a buffer on a pretty regular basis without interrupting flow.

Drew
  • 77,472
  • 10
  • 114
  • 243
abingham
  • 927
  • 6
  • 18

1 Answers1

3
(defun line-length (n)
  "Length of the Nth line."
  (save-excursion
    (goto-char (point-min))
    (if (zerop (forward-line (1- n)))
        (- (line-end-position)
           (line-beginning-position)))))

or calculate the length of all lines in current-buffer (or of the accessible portion):

(defun line-lengths ()
  (let (lengths)
    (save-excursion
      (goto-char (point-min))
      (while (not (eobp))
        (push (- (line-end-position)
                 (line-beginning-position))
              lengths)
        (forward-line)))
    (nreverse lengths)))
xuchunyang
  • 14,527
  • 1
  • 19
  • 39