1

There are plenty of ways to count lines, words, and characters in Emacs. For instance, invoking M-= (AKA count-words-region) does that very thing on a given region. However, I am having trouble finding a way to do this for paragraphs. By paragraph, I mean the same pattern that is used for forward-paragraph and backward-paragraph. I see no easy or straightforward way to count the number of paragraphs in a region or buffer without using regexps or similar. I'm sure that I'm not the first person to face this problem, so I must be missing something. If someone could provide an easy, straightforward way to count the paragraphs in a region or buffer, I would be glad.

2 Answers 2

2

Here is how the builtin count-lines works:

(- (buffer-size) (forward-line (buffer-size)))

The following changes forward-line to forward-paragraph to implement the function.

(defun count-paragraphs (start end)
  "Return number of paragraphs between START and END."
  (save-excursion
    (save-restriction
      (narrow-to-region start end)
      (goto-char (point-min))
      (- (buffer-size) (forward-paragraph (buffer-size))))))

(defun count-paragraphs-region-or-buffer ()
  "Report number of paragraphs in the region (if it's active) or the entire buffer."
  (declare (interactive-only count-paragraphs))
  (interactive)
  (let ((paragraphs (if (use-region-p)
                        (count-paragraphs (region-beginning) (region-end))
                        (count-paragraphs (point-min) (point-max)))))
    (message "%s has %d paragraph%s"
             (if (use-region-p) "Region" "Buffer")
             paragraphs
             (if (> paragraphs 1) "s" ""))))
1
  • Thank you very much! This is well-written Elisp and I appreciate the explanation at the beginning. It does what I want quite well, and it has both an interactive & non-interactive version to boot! I think I will make good use out of this in the future. Thanks again!
    – GDP2
    Oct 26, 2018 at 3:11
2

Does this do the right thing?

(count-matches paragraph-start)
1
  • Unfortunately, it doesn't work for paragraphs which are split by newlines, such as with fill-paragraph. You can see the flaw in a Help buffer or when composing an email in Message mode. The paragraphs in those buffers are often not just one line, for formatting's sake, and so there are many false positives. But I'll give you an upvote for simplicity! Thanks anyway!
    – GDP2
    Oct 26, 2018 at 3:14

Your Answer

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

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