I am searching for some kind of reduce function, which loops through every line of a buffer, but I can not find it. Does anybody know the name of such a function?

Something similar to Perl

while (<>) {

Or a dolist for buffer lines.


2 Answers 2


A slightly more idiomatic example:

(goto-char (point-min))
(while (not (eobp))
  (forward-line 1))

You can make a while loop using the function forward-line as your test. If forward-line reaches the end of the buffer, it returns the number of lines it wanted to move but couldn't. That leads to the following loop:

(save-excursion  ;; save our starting position
  (goto-char (point-min))    ;; go to the beginning of the buffer
  (while (< (forward-line) 1)    ;; move forward one line
                                 ;; until forward line returns a non-zero value
    (end-of-line)    ;; go to the end of the line
    (insert ";; I made it to here!")))    ;; insert a comment

The while loop continues as long as forward-line returns 0, which it does when it is able to move. It will return 1 when it can't move any further.

  • 1
    Does this skip the first line?
    – ceving
    Feb 2, 2018 at 7:56

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