[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]


From: Stephen Berman
Subject: count-words-region
Date: Sat, 13 Nov 2010 14:02:05 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.0.50 (gnu/linux)

The newly installed count-words-region differs from the shell command wc
in certain cases, for example, in this sentence: "How many words does
count-words-region say this sentence has?"  I think wc delimits words by
white space.  This may sometimes be better than word syntax, but
sometimes worse (e.g. if a comment string like ";;" is counted).  It
could be useful to allow a command for counting words to be flexible
with respect to what delimits words.  Here's an implementation that does

(defun count-words (&optional syntax)
  "Count words in region if it exists, else in visible buffer.
What counts as a word depends on the syntax class, solicited by
prefix argument SYNTAX; the default is to use white space to
delimit words, like the shell command wc."
  (interactive "P")
  (let ((syn (if syntax (read-from-minibuffer "Syntax code: ") " "))
        (beg (if (mark t) (region-beginning) (point-min)))
        (end (if (mark t) (region-end) (point-max)))
        (count 0))
      (goto-char beg)
      ;; don't count initial white space
      (and (string= syn " ") (skip-syntax-forward syn)) 
      (while (< (point) end)
        (skip-syntax-forward (concat "^" syn))
        (unless (>= (point) end) (skip-syntax-forward syn))
        (setq count (1+ count))))
    (message "%d words in %s"
             count (if (> (buffer-size) (- end beg)) "region" "buffer"))))

Steve Berman

reply via email to

[Prev in Thread] Current Thread [Next in Thread]