0

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.

2
(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)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.