

18. Embedded Mode

Embedded Mode in Calc provides an alternative to copying numbers and formulas back and forth between editing buffers and the Calc stack. In Embedded Mode, your editing buffer becomes temporarily linked to the stack and this copying is taken care of automatically.

18.1 Basic Embedded Mode  
18.2 More About Embedded Mode  
18.3 Assignments in Embedded Mode  
18.4 Mode Settings in Embedded Mode  
18.5 Customizing Embedded Mode  


18.1 Basic Embedded Mode

To enter Embedded mode, position the Emacs point (cursor) on a formula in any buffer and press M-# e (calc-embedded). Note that M-# e is not to be used in the Calc stack buffer like most Calc commands, but rather in regular editing buffers that are visiting your own files.

Calc normally scans backward and forward in the buffer for the nearest opening and closing formula delimiters. The simplest delimiters are blank lines. Other delimiters that Embedded Mode understands are:

  1. The TeX and LaTeX math delimiters `$ $', `$$ $$', `\[ \]', and `\( \)';
  2. Lines beginning with `\begin' and `\end';
  3. Lines beginning with `@' (Texinfo delimiters).
  4. Lines beginning with `.EQ' and `.EN' (eqn delimiters);
  5. Lines containing a single `%' or `.\"' symbol and nothing else.

See section 18.5 Customizing Embedded Mode, to see how to make Calc recognize your own favorite delimiters. Delimiters like `$ $' can appear on their own separate lines or in-line with the formula.

If you give a positive or negative numeric prefix argument, Calc instead uses the current point as one end of the formula, and moves forward or backward (respectively) by that many lines to find the other end. Explicit delimiters are not necessary in this case.

With a prefix argument of zero, Calc uses the current region (delimited by point and mark) instead of formula delimiters.

With a prefix argument of C-u only, Calc scans for the first non-numeric character (i.e., the first character that is not a digit, sign, decimal point, or upper- or lower-case `e') forward and backward to delimit the formula. M-# w (calc-embedded-word) is equivalent to C-u M-# e.

When you enable Embedded mode for a formula, Calc reads the text between the delimiters and tries to interpret it as a Calc formula. It's best if the current Calc language mode is correct for the formula, but Calc can generally identify TeX formulas and Big-style formulas even if the language mode is wrong. If Calc can't make sense of the formula, it beeps and refuses to enter Embedded mode. But if the current language is wrong, Calc can sometimes parse the formula successfully (but incorrectly); for example, the C expression `atan(a[1])' can be parsed in Normal language mode, but the atan won't correspond to the built-in arctan function, and the `a[1]' will be interpreted as `a' times the vector `[1]'!

If you press M-# e or M-# w to activate an embedded formula which is blank, say with the cursor on the space between the two delimiters `$ $', Calc will immediately prompt for an algebraic entry.

Only one formula in one buffer can be enabled at a time. If you move to another area of the current buffer and give Calc commands, Calc turns Embedded mode off for the old formula and then tries to restart Embedded mode at the new position. Other buffers are not affected by Embedded mode.

When Embedded mode begins, Calc pushes the current formula onto the stack. No Calc stack window is created; however, Calc copies the top-of-stack position into the original buffer at all times. You can create a Calc window by hand with M-# o if you find you need to see the entire stack.

For example, typing M-# e while somewhere in the formula `n>2' in the following line enables Embedded mode on that inequality:

We define $F_n = F_(n-1)+F_(n-2)$ for all $n>2$.

The formula n>2 will be pushed onto the Calc stack, and the top of stack will be copied back into the editing buffer. This means that spaces will appear around the `>' symbol to match Calc's usual display style:


No spaces have appeared around the `+' sign because it's in a different formula, one which we have not yet touched with Embedded mode.

Now that Embedded mode is enabled, keys you type in this buffer are interpreted as Calc commands. At this point we might use the "commute" command j C to reverse the inequality. This is a selection-based command for which we first need to move the cursor onto the operator (`>' in this case) that needs to be commuted.

We define $F_n = F_(n-1)+F_(n-2)$ for all $2 < n$.

The M-# o command is a useful way to open a Calc window without actually selecting that window. Giving this command verifies that `2 < n' is also on the Calc stack. Typing 17 RET would produce:

We define $F_n = F_(n-1)+F_(n-2)$ for all $17$.

with `2 < n' and `17' on the stack; typing TAB at this point will exchange the two stack values and restore `2 < n' to the embedded formula. Even though you can't normally see the stack in Embedded mode, it is still there and it still operates in the same way. But, as with old-fashioned RPN calculators, you can only see the value at the top of the stack at any given time (unless you use M-# o).

Typing M-# e again turns Embedded mode off. The Calc window reveals that the formula `2 < n' is automatically removed from the stack, but the `17' is not. Entering Embedded mode always pushes one thing onto the stack, and leaving Embedded mode always removes one thing. Anything else that happens on the stack is entirely your business as far as Embedded mode is concerned.

If you press M-# e in the wrong place by accident, it is possible that Calc will be able to parse the nearby text as a formula and will mangle that text in an attempt to redisplay it "properly" in the current language mode. If this happens, press M-# e again to exit Embedded mode, then give the regular Emacs "undo" command (C-_ or C-x u) to put the text back the way it was before Calc edited it. Note that Calc's own Undo command (typed before you turn Embedded mode back off) will not do you any good, because as far as Calc is concerned you haven't done anything with this formula yet.


18.2 More About Embedded Mode

When Embedded mode "activates" a formula, i.e., when it examines the formula for the first time since the buffer was created or loaded, Calc tries to sense the language in which the formula was written. If the formula contains any TeX-like `\' sequences, it is parsed (i.e., read) in TeX mode. If the formula appears to be written in multi-line Big mode, it is parsed in Big mode. Otherwise, it is parsed according to the current language mode.

Note that Calc does not change the current language mode according to what it finds. Even though it can read a TeX formula when not in TeX mode, it will immediately rewrite this formula using whatever language mode is in effect. You must then type d T to switch Calc permanently into TeX mode if that is what you desire.


Plain formulas are preceded and followed by `%%%' signs by default. This notation has the advantage that the `%' character begins a comment in TeX, so if your formula is embedded in a TeX document its plain version will be invisible in the final printed copy. See section 18.5 Customizing Embedded Mode, to see how to change the "plain" formula delimiters, say to something that eqn or some other formatter will treat as a comment.

There are several notations which Calc's parser for "big" formatted formulas can't yet recognize. In particular, it can't read the large symbols for sum, prod, and integ, and it can't handle `=>' with the righthand argument omitted. Also, Calc won't recognize special formats you have defined with the Z C command (see section User-Defined Compositions). In these cases it is important to use "plain" mode to make sure Calc will be able to read your formula later.

Another example where "plain" mode is important is if you have specified a float mode with few digits of precision. Normally any digits that are computed but not displayed will simply be lost when you save and re-load your embedded buffer, but "plain" mode allows you to make sure that the complete number is present in the file as well as the rounded-down number.



The derivative of



                  (the derivative of ln(ln(x)))

whose value at x = 2 is

                            (the value)

and at x = 3 is

                            (the value)

The M-# d (calc-embedded-duplicate) command is a handy way to make sequences like this. If you type M-# d, the formula under the cursor (which may or may not have Embedded mode enabled for it at the time) is copied immediately below and Embedded mode is then enabled for that copy.

For this example, you would start with just

The derivative of


and press M-# d with the cursor on this formula. The result is

The derivative of



with the second copy of the formula enabled in Embedded mode. You can now press a d x RET to take the derivative, and M-# d M-# d to make two more copies of the derivative. To complete the computations, type 3 s l x RET to evaluate the last formula, then move up to the second-to-last formula and type 2 s l x RET.

Finally, you would want to press M-# e to exit Embedded mode, then go up and insert the necessary text in between the various formulas and numbers.

The M-# f (calc-embedded-new-formula) command creates a new embedded formula at the current point. It inserts some default delimiters, which are usually just blank lines, and then does an algebraic entry to get the formula (which is then enabled for Embedded mode). This is just shorthand for typing the delimiters yourself, positioning the cursor between the new delimiters, and pressing M-# e. The key sequence M-# ' is equivalent to M-# f.

The M-# n (calc-embedded-next) and M-# p (calc-embedded-previous) commands move the cursor to the next or previous active embedded formula in the buffer. They can take positive or negative prefix arguments to move by several formulas. Note that these commands do not actually examine the text of the buffer looking for formulas; they only see formulas which have previously been activated in Embedded mode. In fact, M-# n and M-# p are a useful way to tell which embedded formulas are currently active. Also, note that these commands do not enable Embedded mode on the next or previous formula, they just move the cursor. (By the way, M-# n is not as awkward to type as it may seem, because M-# ignores Shift and Meta on the second keystroke: M-# M-N can be typed by holding down Shift and Meta and alternately typing two keys.)

The M-# ` (calc-embedded-edit) command edits the embedded formula at the current point as if by ` (calc-edit). Embedded mode does not have to be enabled for this to work. Press M-# M-# to finish the edit, or M-# x to cancel.


18.3 Assignments in Embedded Mode

The `:=' (assignment) and `=>' ("evaluates-to") operators are especially useful in Embedded mode. They allow you to make a definition in one formula, then refer to that definition in other formulas embedded in the same buffer.

An embedded formula which is an assignment to a variable, as in

foo := 5

records 5 as the stored value of foo for the purposes of Embedded mode operations in the current buffer. It does not actually store 5 as the "global" value of foo, however. Regular Calc operations, and Embedded formulas in other buffers, will not see this assignment.

One way to use this assigned value is simply to create an Embedded formula elsewhere that refers to foo, and to press = in that formula. However, this permanently replaces the foo in the formula with its current value. More interesting is to use `=>' elsewhere:

foo + 7 => 12

See section 14.5 The Evaluates-To Operator, for a general discussion of `=>'.

If you move back and change the assignment to foo, any `=>' formulas which refer to it are automatically updated.

foo := 17

foo + 7 => 24

The obvious question then is, how can one easily change the assignment to foo? If you simply select the formula in Embedded mode and type 17, the assignment itself will be replaced by the 17. The effect on the other formula will be that the variable foo becomes unassigned:


foo + 7 => foo + 7

The right thing to do is first to use a selection command (j 2 will do the trick) to select the righthand side of the assignment. Then, 17 TAB DEL will swap the 17 into place (see section 12.1 Selecting Sub-Formulas, to see how this works).

The M-# j (calc-embedded-select) command provides an easy way to operate on assigments. It is just like M-# e, except that if the enabled formula is an assignment, it uses j 2 to select the righthand side. If the enabled formula is an evaluates-to, it uses j 1 to select the lefthand side. A formula can also be a combination of both:

bar := foo + 3 => 20

in which case M-# j will select the middle part (`foo + 3').

The formula is automatically deselected when you leave Embedded mode.

Another way to change the assignment to foo would simply be to edit the number using regular Emacs editing rather than Embedded mode. Then, we have to find a way to get Embedded mode to notice the change. The M-# u or M-# = (calc-embedded-update-formula) command is a convenient way to do this.

foo := 6

foo + 7 => 13

Pressing M-# u is much like pressing M-# e = M-# e, that is, temporarily enabling Embedded mode for the formula under the cursor and then evaluating it with =. But M-# u does not actually use M-# e, and in fact another formula somewhere else can be enabled in Embedded mode while you use M-# u and that formula will not be disturbed.

With a numeric prefix argument, M-# u updates all active `=>' formulas in the buffer. Formulas which have not yet been activated in Embedded mode, and formulas which do not have `=>' as their top-level operator, are not affected by this. (This is useful only if you have used m C; see below.)

With a plain C-u prefix, C-u M-# u updates only in the region between mark and point rather than in the whole buffer.

M-# u is also a handy way to activate a formula, such as an `=>' formula that has freshly been typed in or loaded from a file.

The M-# a (calc-embedded-activate) command scans through the current buffer and activates all embedded formulas that contain `:=' or `=>' symbols. This does not mean that Embedded mode is actually turned on, but only that the formulas' positions are registered with Embedded mode so that the `=>' values can be properly updated as assignments are changed.

It is a good idea to type M-# a right after loading a file that uses embedded `=>' operators. Emacs includes a nifty "buffer-local variables" feature that you can use to do this automatically. The idea is to place near the end of your file a few lines that look like this:

--- Local Variables: ---
--- eval:(calc-embedded-activate) ---
--- End: ---

where the leading and trailing `---' can be replaced by any suitable strings (which must be the same on all three lines) or omitted altogether; in a TeX file, `%' would be a good leading string and no trailing string would be necessary. In a C program, `/*' and `*/' would be good leading and trailing strings.

When Emacs loads a file into memory, it checks for a Local Variables section like this one at the end of the file. If it finds this section, it does the specified things (in this case, running M-# a automatically) before editing of the file begins. The Local Variables section must be within 3000 characters of the end of the file for Emacs to find it, and it must be in the last page of the file if the file has any page separators. See section `Local Variables in Files' in the Emacs manual.

Note that M-# a does not update the formulas it finds. To do this, type, say, M-1 M-# u after M-# a. Generally this should not be a problem, though, because the formulas will have been up-to-date already when the file was saved.

Normally, M-# a activates all the formulas it finds, but any previous active formulas remain active as well. With a positive numeric prefix argument, M-# a first deactivates all current active formulas, then actives the ones it finds in its scan of the buffer. With a negative prefix argument, M-# a simply deactivates all formulas.

Embedded mode has two symbols, `Active' and `~Active', which it puts next to the major mode name in a buffer's mode line. It puts `Active' if it has reason to believe that all formulas in the buffer are active, because you have typed M-# a and Calc has not since had to deactivate any formulas (which can happen if Calc goes to update an `=>' formula somewhere because a variable changed, and finds that the formula is no longer there due to some kind of editing outside of Embedded mode). Calc puts `~Active' in the mode line if some, but probably not all, formulas in the buffer are active. This happens if you activate a few formulas one at a time but never use M-# a, or if you used M-# a but then Calc had to deactivate a formula because it lost track of it. If neither of these symbols appears in the mode line, no embedded formulas are active in the buffer (e.g., before Embedded mode has been used, or after a M-- M-# a).

Embedded formulas can refer to assignments both before and after them in the buffer. If there are several assignments to a variable, the nearest preceding assignment is used if there is one, otherwise the following assignment is used.

x => 1

x := 1

x => 1

x := 2

x => 2

As well as simple variables, you can also assign to subscript expressions of the form `var_number' (as in x_0), or `var_var' (as in x_max). Assignments to other kinds of objects can be represented by Calc, but the automatic linkage between assignments and references works only for plain variables and these two kinds of subscript expressions.

If there are no assignments to a given variable, the global stored value for the variable is used (see section 14.1 Storing Variables), or, if no value is stored, the variable is left in symbolic form. Note that global stored values will be lost when the file is saved and loaded in a later Emacs session, unless you have used the s p (calc-permanent-variable) command to save them; see section 14.3 Other Operations on Variables.

The m C (calc-auto-recompute) command turns automatic recomputation of `=>' forms on and off. If you turn automatic recomputation off, you will have to use M-# u to update these formulas manually after an assignment has been changed. If you plan to change several assignments at once, it may be more efficient to type m C, change all the assignments, then use M-1 M-# u to update the entire buffer afterwards. The m C command also controls `=>' formulas on the stack; see section 14.5 The Evaluates-To Operator. When you turn automatic recomputation back on, the stack will be updated but the Embedded buffer will not; you must use M-# u to update the buffer by hand.


18.4 Mode Settings in Embedded Mode

Embedded Mode has a rather complicated mechanism for handling mode settings in Embedded formulas. It is possible to put annotations in the file that specify mode settings either global to the entire file or local to a particular formula or formulas. In the latter case, different modes can be specified for use when a formula is the enabled Embedded Mode formula.

When you give any mode-setting command, like m f (for fraction mode) or d s (for scientific notation), Embedded Mode adds a line like the following one to the file just before the opening delimiter of the formula.

% [calc-mode: fractions: t]
% [calc-mode: float-format: (sci 0)]

When Calc interprets an embedded formula, it scans the text before the formula for mode-setting annotations like these and sets the Calc buffer to match these modes. Modes not explicitly described in the file are not changed. Calc scans all the way to the top of the file, or up to a line of the form

% [calc-defaults]

which you can insert at strategic places in the file if this backward scan is getting too slow, or just to provide a barrier between one "zone" of mode settings and another.

If the file contains several annotations for the same mode, the closest one before the formula is used. Annotations after the formula are never used (except for global annotations, described below).

The scan does not look for the leading `% ', only for the square brackets and the text they enclose. You can edit the mode annotations to a style that works better in context if you wish. See section 18.5 Customizing Embedded Mode, to see how to change the style that Calc uses when it generates the annotations. You can write mode annotations into the file yourself if you know the syntax; the easiest way to find the syntax for a given mode is to let Calc write the annotation for it once and see what it does.

If you give a mode-changing command for a mode that already has a suitable annotation just above the current formula, Calc will modify that annotation rather than generating a new, conflicting one.

Mode annotations have three parts, separated by colons. (Spaces after the colons are optional.) The first identifies the kind of mode setting, the second is a name for the mode itself, and the third is the value in the form of a Lisp symbol, number, or list. Annotations with unrecognizable text in the first or second parts are ignored. The third part is not checked to make sure the value is of a legal type or range; if you write an annotation by hand, be sure to give a proper value or results will be unpredictable. Mode-setting annotations are case-sensitive.

While Embedded Mode is enabled, the word Local appears in the mode line. This is to show that mode setting commands generate annotations that are "local" to the current formula or set of formulas. The m R (calc-mode-record-mode) command causes Calc to generate different kinds of annotations. Pressing m R repeatedly cycles through the possible modes.

LocEdit and LocPerm modes generate annotations that look like this, respectively:

% [calc-edit-mode: float-format: (sci 0)]
% [calc-perm-mode: float-format: (sci 5)]

The first kind of annotation will be used only while a formula is enabled in Embedded Mode. The second kind will be used only when the formula is not enabled. (Whether the formula is "active" or not, i.e., whether Calc has seen this formula yet, is not relevant here.)

Global mode generates an annotation like this at the end of the file:

% [calc-global-mode: fractions t]

Global mode annotations affect all formulas throughout the file, and may appear anywhere in the file. This allows you to tuck your mode annotations somewhere out of the way, say, on a new page of the file, as long as those mode settings are suitable for all formulas in the file.

Enabling a formula with M-# e causes a fresh scan for local mode annotations; you will have to use this after adding annotations above a formula by hand to get the formula to notice them. Updating a formula with M-# u will also re-scan the local modes, but global modes are only re-scanned by M-# a.

Another way that modes can get out of date is if you add a local mode annotation to a formula that has another formula after it. In this example, we have used the d s command while the first of the two embedded formulas is active. But the second formula has not changed its style to match, even though by the rules of reading annotations the `(sci 0)' applies to it, too.



We would have to go down to the other formula and press M-# u on it in order to get it to notice the new annotation.

Two more mode-recording modes selectable by m R are Save (which works even outside of Embedded Mode), in which mode settings are recorded permanently in your Emacs startup file `~/.emacs' rather than by annotating the current document, and no-recording mode (where there is no symbol like Save or Local in the mode line), in which mode-changing commands do not leave any annotations at all.

When Embedded Mode is not enabled, mode-recording modes except for Save have no effect.


18.5 Customizing Embedded Mode

You can modify Embedded Mode's behavior by setting various Lisp variables described here. Use M-x set-variable or M-x edit-options to adjust a variable on the fly, or put a suitable setq statement in your `~/.emacs' file to set a variable permanently. (Another possibility would be to use a file-local variable annotation at the end of the file; see section `Local Variables in Files' in the Emacs manual.)

While none of these variables will be buffer-local by default, you can make any of them local to any embedded-mode buffer. (Their values in the `*Calculator*' buffer are never used.)

The calc-embedded-open-formula variable holds a regular expression for the opening delimiter of a formula. See section `Regular Expression Search' in the Emacs manual, to see how regular expressions work. Basically, a regular expression is a pattern that Calc can search for. A regular expression that considers blank lines, `$', and `$$' to be opening delimiters is "\\`\\|^\n\\|\\$\\$?". Just in case the meaning of this regular expression is not completely plain, let's go through it in detail.

The surrounding `" "' marks quote the text between them as a Lisp string. If you left them off, set-variable or edit-options would try to read the regular expression as a Lisp program.


Regular expressions also consider pairs beginning with backslash to have special meanings. Sometimes the backslash is used to quote a character that otherwise would have a special meaning in a regular expression, like `$', which normally means "end-of-line," or `?', which means that the preceding item is optional. So `\$\$?' matches either one or two dollar signs.

The other codes in this regular expression are `^', which matches "beginning-of-line," `\|', which means "or," and `\`', which matches "beginning-of-buffer." So the whole pattern means that a formula begins at the beginning of the buffer, or on a newline that occurs at the beginning of a line (i.e., a blank line), or at one or two dollar signs.


By the way, the reason to use `^\n' rather than `^$' or `\n\n', which also would appear to match blank lines, is that the former expression actually "consumes" only one newline character as part of the delimiter, whereas the latter expressions consume zero or two newlines, respectively. The former choice gives the most natural behavior when Calc must operate on a whole formula including its delimiters.

See the Emacs manual for complete details on regular expressions. But just for your convenience, here is a list of all characters which must be quoted with backslash (like `\$') to avoid some special interpretation: `. * + ? [ ] ^ $ \'. (Note the backslash in this list; for example, to match `\[' you must use "\\\\\\[". An exercise for the reader is to account for each of these six backslashes!)

The calc-embedded-close-formula variable holds a regular expression for the closing delimiter of a formula. A closing regular expression to match the above example would be "\\'\\|\n$\\|\\$\\$?". This is almost the same as the other one, except it now uses `\'' ("end-of-buffer") and `\n$' (newline occurring at end of line, yet another way of describing a blank line that is more appropriate for this case).

The calc-embedded-open-word and calc-embedded-close-word variables are similar expressions used when you type M-# w instead of M-# e to enable Embedded mode.

The calc-embedded-open-plain variable is a string which begins a "plain" formula written in front of the formatted formula when d p mode is turned on. Note that this is an actual string, not a regular expression, because Calc must be able to write this string into a buffer as well as to recognize it. The default string is "%%% " (note the trailing space).

The calc-embedded-close-plain variable is a string which ends a "plain" formula. The default is " %%%\n". Without the trailing newline here, the first line of a "big" mode formula that followed might be shifted over with respect to the other lines.

The calc-embedded-open-new-formula variable is a string which is inserted at the front of a new formula when you type M-# f. Its default value is "\n\n". If this string begins with a newline character and the M-# f is typed at the beginning of a line, M-# f will skip this first newline to avoid introducing unnecessary blank lines in the file.

The calc-embedded-close-new-formula variable is the corresponding string which is inserted at the end of a new formula. Its default value is also "\n\n". The final newline is omitted by M-# f if typed at the end of a line. (It follows that if M-# f is typed on a blank line, both a leading opening newline and a trailing closing newline are omitted.)

The calc-embedded-announce-formula variable is a regular expression which is sure to be followed by an embedded formula. The M-# a command searches for this pattern as well as for `=>' and `:=' operators. Note that M-# a will not activate just anything surrounded by formula delimiters; after all, blank lines are considered formula delimiters by default! But if your language includes a delimiter which can only occur actually in front of a formula, you can take advantage of it here. The default pattern is "%Embed\n\\(% .*\n\\)*", which checks for `%Embed' followed by any number of lines beginning with `%' and a space. This last is important to make Calc consider mode annotations part of the pattern, so that the formula's opening delimiter really is sure to follow the pattern.


The calc-embedded-close-mode variable is a string which follows a mode annotation written by Calc. Its default value is simply a newline, "\n". If you change this, it is a good idea still to end with a newline so that mode annotations will appear on lines by themselves.

