How to Define Optional Parameters in Emacs Lisp

Perm url with updates:

How to Define Optional Parameters in Emacs Lisp

Xah Lee, 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” in your parameter. Any parameter after that will be optional. Here is a example:

;; defining a function with 2 optional params 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:

(myfun "myaa" "mybb" nil "mydd")

Emacs lisp function 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, type “Alt+x 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, type “Alt+x 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” after the “&optional”.

(info "(elisp) Argument List")

Popular posts from this blog

11 Years of Writing About Emacs

does md5 creates more randomness?

Google Code shutting down, future of ErgoEmacs