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.
Move to beginning of current or preceding defun
Move to end of current or following defun (
Put region around whole current or following defun (
The commands to move to the beginning and end of the current defun are
beginning-of-defun) and C-M-e (
To operate on the current defun, use C-M-h (
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
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.