Node:Complete forward-sentence, Next:, Previous:forward-sentence, Up:forward-sentence



Complete forward-sentence function definition

Here is the code for forward-sentence:

(defun forward-sentence (&optional arg)
  "Move forward to next sentence-end.  With argument, repeat.
With negative argument, move backward repeatedly to sentence-beginning.
Sentence ends are identified by the value of sentence-end
treated as a regular expression.  Also, every paragraph boundary
terminates sentences as well."
  (interactive "p")
  (or arg (setq arg 1))
  (while (< arg 0)
    (let ((par-beg
           (save-excursion (start-of-paragraph-text) (point))))
      (if (re-search-backward
           (concat sentence-end "[^ \t\n]") par-beg t)
          (goto-char (1- (match-end 0)))
        (goto-char par-beg)))
    (setq arg (1+ arg)))
  (while (> arg 0)
    (let ((par-end
           (save-excursion (end-of-paragraph-text) (point))))
      (if (re-search-forward sentence-end par-end t)
          (skip-chars-backward " \t\n")
        (goto-char par-end)))
    (setq arg (1- arg))))

The function looks long at first sight and it is best to look at its skeleton first, and then its muscle. The way to see the skeleton is to look at the expressions that start in the left-most columns:

(defun forward-sentence (&optional arg)
  "documentation..."
  (interactive "p")
  (or arg (setq arg 1))
  (while (< arg 0)
    body-of-while-loop
  (while (> arg 0)
    body-of-while-loop

This looks much simpler! The function definition consists of documentation, an interactive expression, an or expression, and while loops.

Let's look at each of these parts in turn.

We note that the documentation is thorough and understandable.

The function has an interactive "p" declaration. This means that the processed prefix argument, if any, is passed to the function as its argument. (This will be a number.) If the function is not passed an argument (it is optional) then the argument arg will be bound to 1. When forward-sentence is called non-interactively without an argument, arg is bound to nil.

The or expression handles the prefix argument. What it does is either leave the value of arg as it is, but only if arg is bound to a value; or it sets the value of arg to 1, in the case when arg is bound to nil.