Formula syntax for Lisp (The Org Manual)

Next: Durations and time values, Previous: Formula syntax for Calc, Up: The Spreadsheet [Contents][Index]

#### 3.5.3 Emacs Lisp forms as formulas

It is also possible to write a formula in Emacs Lisp. This can be useful for string manipulation and control structures, if Calc’s functionality is not enough.

If a formula starts with a single-quote followed by an opening parenthesis, then it is evaluated as a Lisp form. The evaluation should return either a string or a number. Just as with Calc formulas, you can specify modes and a `printf` format after a semicolon.

With Emacs Lisp forms, you need to be conscious about the way field references are interpolated into the form. By default, a reference is interpolated as a Lisp string (in double-quotes) containing the field. If you provide the ‘`N`’ mode switch, all referenced elements are numbers—non-number fields will be zero—and interpolated as Lisp numbers, without quotes. If you provide the ‘`L`’ flag, all fields are interpolated literally, without quotes. For example, if you want a reference to be interpreted as a string by the Lisp form, enclose the reference operator itself in double-quotes, like ‘`"$3"`’. Ranges are inserted as space-separated fields, so you can embed them in list or vector syntax.

Here are a few examples—note how the ‘`N`’ mode is used when we do computations in Lisp:

‘`'(concat (substring $1 1 2) (substring $1 0 1) (substring $1 2))`’

  Swap the first two characters of the content of column 1.

‘`'(+ $1 $2);N`’

  Add columns 1 and 2, equivalent to Calc’s ‘`$1+$2`’.

‘`'(apply '+ '($1..$4));N`’

  Compute the sum of columns 1 to 4, like Calc’s ‘`vsum($1..$4)`’.

Next: Durations and time values, Previous: Formula syntax for Calc, Up: The Spreadsheet [Contents][Index]