www.delorie.com/gnu/docs/elisp-manual-21/elisp_179.html   search  
 
Buy the book!


GNU Emacs Lisp Reference Manual

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

13.5 Backquote

Macros often need to construct large list structures from a mixture of constants and nonconstant parts. To make this easier, use the ``' syntax (usually called backquote).

Backquote allows you to quote a list, but selectively evaluate elements of that list. In the simplest case, it is identical to the special form quote (see section 9.3 Quoting). For example, these two forms yield identical results:

 
`(a list of (+ 2 3) elements)
     => (a list of (+ 2 3) elements)
'(a list of (+ 2 3) elements)
     => (a list of (+ 2 3) elements)

The special marker `,' inside of the argument to backquote indicates a value that isn't constant. Backquote evaluates the argument of `,' and puts the value in the list structure:

 
(list 'a 'list 'of (+ 2 3) 'elements)
     => (a list of 5 elements)
`(a list of ,(+ 2 3) elements)
     => (a list of 5 elements)

Substitution with `,' is allowed at deeper levels of the list structure also. For example:

 
(defmacro t-becomes-nil (variable)
  `(if (eq ,variable t)
       (setq ,variable nil)))

(t-becomes-nil foo)
     == (if (eq foo t) (setq foo nil))

You can also splice an evaluated value into the resulting list, using the special marker `,@'. The elements of the spliced list become elements at the same level as the other elements of the resulting list. The equivalent code without using ``' is often unreadable. Here are some examples:

 
(setq some-list '(2 3))
     => (2 3)
(cons 1 (append some-list '(4) some-list))
     => (1 2 3 4 2 3)
`(1 ,@some-list 4 ,@some-list)
     => (1 2 3 4 2 3)

(setq list '(hack foo bar))
     => (hack foo bar)
(cons 'use
  (cons 'the
    (cons 'words (append (cdr list) '(as elements)))))
     => (use the words foo bar as elements)
`(use the words ,@(cdr list) as elements)
     => (use the words foo bar as elements)

In old Emacs versions, before version 19.29, ``' used a different syntax which required an extra level of parentheses around the entire backquote construct. Likewise, each `,' or `,@' substitution required an extra level of parentheses surrounding both the `,' or `,@' and the following expression. The old syntax required whitespace between the ``', `,' or `,@' and the following expression.

This syntax is still accepted, for compatibility with old Emacs versions, but we recommend not using it in new programs.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster   donations   bookstore     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003