Go to the first, previous, next, last section, table of contents.


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 a Lisp file are instances of the special form defun, but any top-level parenthetical grouping counts as a defun in Emacs parlance regardless of what its contents are, and regardless of the programming language in use. 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).

If you wish to operate on the current defun, use C-M-h (mark-defun) which puts point at the beginning and mark at the end of the current or next defun. For example, this is the easiest way to get ready to move the defun to a different place in the text. In C mode, C-M-h runs the function c-mark-function, which is almost the same as mark-defun; the difference is that it backs up over the argument declarations, function name and returned data type so that the entire C function is inside the region. See section Commands to Mark Textual Objects.

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.

In the remotest past, the original Emacs found defuns by moving upward a level of parentheses until there were no more levels to go up. This always required scanning all the way back to the beginning of the buffer, even for a small function. To speed up the operation, 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 and avoids the costly scan; however, it mandates the convention described above.


Go to the first, previous, next, last section, table of contents.