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:


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.

1 Answer 1

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

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

(defun line-lengths ()
  (let (lengths)
      (goto-char (point-min))
      (while (not (eobp))
        (push (- (line-end-position)
    (nreverse lengths)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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