;; count-words-region and count-words-buffer originally from ;; http://www.gnu.org/software/emacs/emacs-lisp-intro/ ;; count-words-document v0.1 (defun count-words-region (beginning end &optional count-buffer) "Print number of words in the region." (interactive "r\nP") (message "Counting words in region ... ") ;;; 1. Set up appropriate conditions. (save-excursion (let ((count 0)) (goto-char beginning) ;;; 2. Run the while loop. (while (and (< (point) end) (re-search-forward "\\w+\\W*" end t)) (setq count (1+ count))) ;;; 3. Send a message to the user. (cond ((zerop count) (message "The region does NOT have any words.")) ((= 1 count) (message "The region has 1 word.")) (t (if count-buffer (message "The buffer has %d words." count) (message "The region has %d words." count))))))) ;; Count the words in the entire document (defun count-words-buffer () "Count all the words in the buffer" (interactive) (count-words-region (point-min) (point-max) t)) (defun count-words-document (&optional arg begin end) "Without ARG, count all the words in the {document} environment if ARG exists, count words in region." (interactive "P\nr") (if arg (count-words-region (prefix-numeric-value begin) (prefix-numeric-value end)) ;; else-part, default: ;; would probably make sense to make the default start and end ;; points customizable, but for now the `end{singlespace}' is the ;; default start position, and `begin{document}' is the backup ;; start position. They both end at `end{document}', and both of ;; those ends are independent of each other as you can probably ;; guess. Change them to your hearts content, just remember that ;; in emacs regexes, curly-braces need to be escaped `{' != ;; `\{'. Only the `\{' is right. (save-excursion (goto-char (point-min)) (if (search-forward "end\{singlespace\}" nil t) (count-words-region (point) (progn (search-forward "end\{document\}") (goto-char (match-beginning 0)))) (progn (goto-char (point-min)) (if (search-forward "begin\{document\}" nil t) (count-words-region (point) (progn (search-forward "end\{document\}") (goto-char (match-beginning 0)))) (count-words-region (point-min) (point-max) t)))))))