help-gnu-emacs
[Top][All Lists]
Advanced

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

Re: how to interactive to emacs


From: Harald Hanche-Olsen
Subject: Re: how to interactive to emacs
Date: Sun, 19 Mar 2006 21:00:59 +0100
User-agent: Gnus/5.11 (Gnus v5.11) Emacs/23.0.0 (berkeley-unix)

+ "hallen" <longhrs@gmail.com>:

|  remove the p
| ---------------------
| (defun count-word-buffer()
|   "couont the number of words in the current buffer;
|  priny a message in the minibuffer with the result"
|   (interactive )
|   (save-excursion
|    (let ((count 0))
|      (goto-char (point-min))
|      (while (< (point) (point-max))
|        (forward-word 1)
|        (setq count(1+ count)))
|      (message "This buffer total contains %d words" count)))
|
| ====================
| when i  type M-x count-word-buffer
| also can not found that function 
| messaged  "no match"

What David Kastrup is driving at is that you must make emacs know this
definition.  Interactively, the easiest way is to place the cursor
after the entire defun form and type C-x C-e.  (Or in the *scratch*
buffer, type C-j.)  Once you're satisfied that the function works
right, copy it to your .emacs so it will be available in future
sessions.

As has also been pointed out, you have a lack of closing parentheses.

Here is (perhaps) a better version of your function:
Note the save-restriction and widen, which are needed in case you have
narrowed the buffer.  And my solution takes advantage of the fact that
(forward-word 1) returns t, unless it hits the end of the file, in
which case it returns nil.  So you don't need to test for the end of
the buffer yourself.

(require 'cl) ; needed in order to use incf

(defun count-word-buffer ()
  (interactive )
  (save-excursion
    (save-restriction
      (widen)
      (goto-char (point-min))
      (let ((count 0))
        (while (forward-word 1) (incf count))
        (message "This buffer total contains %d words" count)))))

A different solution is the following (assuming you're on unix):

(defun word-count-buffer ()
  (interactive)
  (save-restriction
    (widen)
    (shell-command-on-region (point-min) (point-max) "wc -w")))

The two functions may yield slightly different results, due to
differences in what is considered to be a word.

-- 
* Harald Hanche-Olsen     <URL:http://www.math.ntnu.no/~hanche/>
- It is undesirable to believe a proposition
  when there is no ground whatsoever for supposing it is true.
  -- Bertrand Russell


reply via email to

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