2 Functions in Elisp

Here’s how to define a simple LISP function

1: (defun pi ()
2:   "A sample non-interactive function"
3:   3.1415
4: )

The above is a non-interactive function that simply returns 3.1415. Evaluate it (C-x C-e, remember?) and you will see the word pi appear in the echo area. Try M-x pi, though, and Emacs won’t find the function. If you want to be able to call a function using M-x, you have to make it interactive, as follows.

1: (defun print-pi()
2:     "Insert an approximation to pi"
3:     (interactive)
4:     (insert "3.1415")
5: )

So why would you want a non-interactive function? Perhaps because you want it to be called from another function, as follows:

1: (defun circumference-of-circle()
2:     (interactive)
3:     (message "The circumference of a circle diameter 3 is %f" (* pi 3))
4: )

Before evaluating the above function, make sure that you have evaluated the non-interactive function pi.

There are lots of different types of interactive functions. The next interactive function is more useful in that it prompts for the diameter to be input (the n at the start of “nInput diameter of circle:” is what tells Emacs to prompt for a number)

1: (defun circumference-of-circle(diameter)
2:     "Calculate the circumference of a circle given the diameter"
3:     (interactive "nInput diameter of circle:")
4:     (message "The circumference of a circle diameter %d is %f" diameter (* 3.1415 diameter))
5: )

Here’s the same function but this time set up to receive the parameter from the universal argument. That is to say, in the form C-u 4 M-x circumference-of-circle.

1: (defun circumference-of-circle(diameter)
2: (interactive "p")
3: (message "The circumference of a circle diameter %d is %f" diameter (* 3.1415 diameter))
4: )

Here’s an example of a function that reads strings and tests your knowledge of capital cities.

1: (defun capital-of-france(answer)
2:     "Simple quiz example."
3:     (interactive "sWhat's the Capital of France?")
4:     (if (string= answer "paris") (message "Correct!") (message "Wrong!"))
5: )

Argument codes for interactive functions can be found here http://www.gnu.org/software/emacs/manual/html_node/elisp/Interactive-Codes.html#Interactive-Codes

Next: Interactive Functions that work on Regions

Leave a Reply

Your email address will not be published. Required fields are marked *