Before listing the full set of clauses that are allowed, let's
look at a few example loops just to get a feel for the
(cl-loop for buf in (buffer-list) collect (buffer-file-name buf))
This loop iterates over all Emacs buffers, using the list
buffer-list. For each buffer buf,
buffer-file-name and collects the results into
a list, which is then returned from the
The result is a list of the file names of all the buffers in
Emacs's memory. The words
are reserved words in the
(cl-loop repeat 20 do (insert "Yowsa\n"))
This loop inserts the phrase “Yowsa” twenty times in the current buffer.
(cl-loop until (eobp) do (munch-line) (forward-line 1))
This loop calls
munch-line on every line until the end
of the buffer. If point is already at the end of the buffer,
the loop exits immediately.
(cl-loop do (munch-line) until (eobp) do (forward-line 1))
This loop is similar to the above one, except that
is always called at least once.
(cl-loop for x from 1 to 100 for y = (* x x) until (>= y 729) finally return (list x (= y 729)))
This more complicated loop searches for a number
square is 729. For safety's sake it only examines
values up to 100; dropping the phrase ‘to 100’ would
cause the loop to count upwards with no limit. The second
for clause defines
y to be the square of
within the loop; the expression after the
= sign is
reevaluated each time through the loop. The
clause gives a condition for terminating the loop, and the
finally clause says what to do when the loop finishes.
(This particular example was written less concisely than it
could have been, just for the sake of illustration.)
Note that even though this loop contains three clauses (two
fors and an
until) that would have been enough to
define loops all by themselves, it still creates a single loop
rather than some sort of triple-nested loop. You must explicitly
cl-loop constructs if you want nested loops.