Emacs Lisp - Example

Example

Here follows a simple example of an Emacs extension written in Emacs Lisp. In Emacs, the editing area can be split into separate areas called windows, each displaying a different buffer. A buffer is a region of text loaded into Emacs' memory (possibly from a file) which can be saved into a text document.

Users issue the "C-x 2" command to open a new window. This runs the Emacs Lisp function split-window-vertically. Normally, when the new window appears, it displays the same buffer as the previous one. Suppose we wish to make it display the next available buffer. In order to do this, the user writes the following Emacs Lisp code, in either an existing Emacs Lisp source file or an empty Emacs buffer:

(defun my-split-window-func (interactive) (split-window-vertically) (set-window-buffer (next-window) (other-buffer))) (global-set-key "\C-x2" 'my-split-window-func )

The first statement, (defun ...), defines a new function, my-split-window-func, which calls split-window-vertically (the old window-splitting function), then tells the new window to display another (new) buffer. The second statement, (global-set-key ...) re-binds the key sequence "C-x 2" to the new function.

However, an easier way exists to write this. Emacs Lisp has a powerful feature called advice, which allows the user to create wrappers around existing functions instead of defining their own. Using advice, the above code can be reimplemented as follows:

(defadvice split-window-vertically (after my-window-splitting-advice first activate) (set-window-buffer (next-window) (other-buffer)))

This instructs split-window-vertically to execute the user-supplied code whenever it is called, before executing the rest of the function.

These changes take effect at code evaluation time, using (for instance) the command "M-x eval-buffer" flag. It is not necessary to recompile or even restart Emacs. If the code is saved into the Emacs "init file" (usually a file named ".emacs" in the user's home directory), then Emacs will load the extension the next time it starts. Otherwise, the changes will be lost when the user exits Emacs.

Read more about this topic:  Emacs Lisp

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)