Emacs Lisp Functions Optional Parameters

Advertise Here

, 2010-04-25

A little tip on emacs function's parameter features and syntax. If you don't know the basic of elisp, you should read Emacs Lisp Basics first.

Use “&optional” for Optional Parameters

Emacs's function parameter's features and syntax is very basic. It is simply a list of items. If you want optional parameters, just add &optional. Any parameter after that will be optional. Here is a example:

;; defining a function with 2 optional params named cc and dd
(defun myfun (aa bb &optional cc dd)
;)

When you call this function, aa and bb are required, cc and dd are optional. When a optional parameter is not given, its value is “nil”. If you want to give a argument to some optional parameters but not all, use “nil” for those you don't care. For example, to call “myfun” in the above with a argument for “dd” but you don't care for “cc”, like this:

;; calling a function with 3rd parameter omitted
(myfun "myaa" "mybb" nil "mydd")

If a function received a “nil” as argument for one of its optional parameter, there is no way for a function to know if it is specified by user or omitted.

Emacs lisp functions do not support named parameter, nor any sort of parameter type checking.

Optional Parameter in Documentation

Inline doc of a function also show optional parameters the same way. For example, call describe-function then give search-forward, and the output is:

…
(search-forward string &optional bound noerror count)
…

This means the function takes 4 arguments, and the last 3 is optional.

Same in the elisp doc. For example, call elisp-index-search , then search-forward. It shows:

 -- Command: search-forward string &optional limit noerror repeat
     This function searches forward from point for an exact match for
     STRING.  If successful, it sets point to the end of the occurrence
     found, and returns the new value of point.  If no match is found,
     the value and side effects depend on NOERROR (see below).

(info "(elisp) String Search")

“&rest” for Unspecified Number of Arguments

Elisp also support the need for unspecified number of arguments. For example, for functions like “+”, message, concat. It is done by adding &rest similar to &optional. You can have both &optional and &rest, in that order.

(info "(elisp) Argument List")

blog comments powered by Disqus