4

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.

Drew
  • 75,699
  • 9
  • 109
  • 225
ceving
  • 1,308
  • 1
  • 14
  • 28

2 Answers2

10

A slightly more idiomatic example:

(goto-char (point-min))
(while (not (eobp))
  ...
  (forward-line 1))
wasamasa
  • 21,803
  • 1
  • 65
  • 97
6

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.

Tyler
  • 21,719
  • 1
  • 52
  • 92