If you've just typed or modified the function and you want to (re)define it, press C-M-x
(eval-defun
) with the cursor anywhere in the definition.
To run the function, use M-:
(eval-expression
) and type (count-words-buffer)
then RET
. If the function needed arguments, you'd need to add them after the function name, e.g. (my-function "first argument" 'second-argument)
.
Alternatively, go to the *scratch*
buffer and type your code (e.g. (count-word-buffers)
). You can either use C-M-x
or press C-j
at the end of a line to execute that line of code (or more precisely, the Lisp expression that ends at the cursor). C-j
additionally inserts the return value into the buffer. This only lets you execute the function in the *scratch*
buffer, you need to use the M-:
method to run it from another buffer.
The way you've defined the function, it isn't a command that can be called interactively. To make it one, add an interactive specification to the function definition.
(defun count-words-buffer ()
(interactive "@")
…)
Then you can run the command with M-x count-words-buffer RET
, you can bind it to a key, etc.
To be able to use the function from Elisp as well, it should return the number of words rather than print it as a message. You can either make a non-interactive function for lisp use and a separate command that just calls the non-interactive function and calls message
on the result, or combine the two and just omit the message
call if the function is not called interactively.
(defun count-words-buffer ()
(interactive "@")
(let ((count 0))
(goto-char (point-min))
(while (< (point) (point-max))
(forward-word 1)
(setq count (1+ count)))
(if (called-interactively-p)
(message "buffer contains %d words." count)
count))
This function already exists in Emacs, with the added bonus that if the region is active, it counts the words in the region. It's called (unsurprisingly) count-words
and you can look at how it's coded.
(count-words-buffer)
. To debug it you useM-x debug-on-entry count-words-buffer
and then call it. – Drew Sep 5 '19 at 15:56