Next: , Previous: , Up: Programs   [Contents][Index]


21.3 Defuns

In Emacs, a parenthetical grouping at the top level in the buffer is called a defun. The name derives from the fact that most top-level lists in Lisp are instances of the special form defun, but Emacs calls any top-level parenthetical grouping counts a defun regardless of its contents or the programming language. For example, in C, the body of a function definition is a defun.

C-M-a

Move to beginning of current or preceding defun (beginning-of-defun).

C-M-e

Move to end of current or following defun (end-of-defun).

C-M-h

Put region around whole current or following defun (mark-defun).

The commands to move to the beginning and end of the current defun are C-M-a (beginning-of-defun) and C-M-e (end-of-defun).

To operate on the current defun, use C-M-h (mark-defun) which puts point at the beginning and the mark at the end of the current or next defun. This is the easiest way to prepare for moving the defun to a different place. In C mode, C-M-h runs the function mark-c-function, which is almost the same as mark-defun, but which backs up over the argument declarations, function name, and returned data type so that the entire C function is inside the region.

To compile and evaluate the current defun, use M-x compile-defun. This function prints the results in the minibuffer. If you include an argument, it inserts the value in the current buffer after the defun.

Emacs assumes that any open-parenthesis found in the leftmost column is the start of a defun. Therefore, never put an open-parenthesis at the left margin in a Lisp file unless it is the start of a top level list. Never put an open-brace or other opening delimiter at the beginning of a line of C code unless it starts the body of a function. The most likely problem case is when you want an opening delimiter at the start of a line inside a string. To avoid trouble, put an escape character (‘\’ in C and Emacs Lisp, ‘/’ in some other Lisp dialects) before the opening delimiter. It will not affect the contents of the string.

The original Emacs found defuns by moving upward a level of parentheses until there were no more levels to go up. This required scanning back to the beginning of the buffer for every function. To speed this up, Emacs was changed to assume that any ‘(’ (or other character assigned the syntactic class of opening-delimiter) at the left margin is the start of a defun. This heuristic is nearly always right; however, it mandates the convention described above.


Next: , Previous: , Up: Programs   [Contents][Index]