daveg@csvax.caltech.edu (David Gillespie) (06/06/90)
Posting-number: Volume 13, Issue 43 Submitted-by: daveg@csvax.caltech.edu (David Gillespie) Archive-name: gmcalc/part17 ---- Cut Here and unpack ---- #!/bin/sh # this is part 17 of a multipart archive # do not concatenate these parts, unpack them in order with /bin/sh # file calc.texinfo continued # CurArch=17 if test ! -r s2_seq_.tmp then echo "Please unpack part 1 first!" exit 1; fi ( read Scheck if test "$Scheck" != $CurArch then echo "Please unpack part $Scheck next!" exit 1; else exit 0; fi ) < s2_seq_.tmp || exit 1 echo "x - Continuing file calc.texinfo" sed 's/^X//' << 'SHAR_EOF' >> calc.texinfo Xuse these rules often, we could define the above sequence of keystrokes Xas a keyboard macro. We could then assign this macro to a single Xkey sequence which effectively means, ``simplify all calls to the function X@samp{f} on top-of-stack.'' @xref{Keyboard Macros}.@refill X X@node Logical Operations, Calculus, Rewrite Rules, Algebra X@section Logical Operations X XThe following commands and algebraic functions return true/false values, Xwhere 1 represents ``true'' and 0 represents ``false.'' In cases where Xa truth value is required (such as for the condition part of a rewrite Xrule), any nonzero number is accepted to mean ``true.'' X X@kindex a = X@pindex calc-equal-to X@tindex eq XThe @kbd{a =} (@code{calc-equal-to}) command, or @samp{eq(a,b)} function X(which can also be written @samp{a = b} or @samp{a == b} in an algebraic Xformula) is true if @samp{a} and @samp{b} are equal, either because they Xare identical expressions, or because they are numbers which are Xnumerically equal. (Thus the integer 1 is considered equal to the float X1.0.) If the equality of @samp{a} and @samp{b} cannot be determined, Xthe comparison is left in symbolic form. Note that as a command, this Xoperation pops two values from the stack and pushes back either a 1 or Xa 0, or a formula @samp{a = b} if the values' equality cannot be determined. X XNote that @kbd{C-u 3 a =} or @samp{a = b = c} does not return true if X@samp{a}, @samp{b}, and @samp{c} are equal. (It is interpreted as X@samp{(a = b) = c}, and returns true if @samp{c} is 1 when @samp{a} and X@samp{b} are equal, or 0 when they are unequal.) Only negative prefix Xarguments are likely to be useful with @kbd{a =} (@pxref{Prefix Arguments}). XThe same is true of the other relational operators described below. X X@kindex a # X@pindex calc-not-equal-to X@tindex neq XThe @kbd{a #} (@code{calc-not-equal-to}) command, or @samp{neq(a,b)} or X@samp{a != b} function, is true if @samp{a} and @samp{b} are not equal. X X@kindex a < X@kindex a > X@kindex a [ X@kindex a ] X@pindex calc-less-than X@pindex calc-greater-than X@pindex calc-less-equal X@pindex calc-greater-equal X@tindex lt X@tindex gt X@tindex leq X@tindex geq XThe @kbd{a <} (@code{calc-less-than}) [@samp{lt(a,b)} or @samp{a < b}] Xoperation is true if @samp{a} is less than @samp{b}. Similar functions Xare @kbd{a >} (@code{calc-greater-than}) [@samp{gt(a,b)} or @samp{a > b}], X@kbd{a [} (@code{calc-less-equal}) [@samp{leq(a,b)} or @samp{a <= b}], and X@kbd{a ]} (@code{calc-greater-equal}) [@samp{geq(a,b)} or @samp{a >= b}]. X X@kindex a & X@pindex calc-logical-and X@tindex land XThe @kbd{a &} (@code{calc-logical-and}) [@samp{land(a,b)} or @samp{a && b}] Xfunction is true if both of its arguments are true, i.e., are Xnon-zero numbers. In this case, the result will be either @samp{a} or X@samp{b}, chosen arbitrarily. If either argument is zero, the result is Xzero. Otherwise, the formula is left in symbolic form. X X@kindex a | X@pindex calc-logical-or X@tindex lor XThe @kbd{a |} (@code{calc-logical-or}) [@samp{lor(a,b)} or @samp{a || b}] Xfunction is true if either of its arguments is true (nonzero). The Xresult is whichever argument was nonzero, choosing arbitrarily if both Xare nonzero. If both @samp{a} and @samp{b} are zero, the result is Xzero. X X@kindex a ! X@pindex calc-logical-not X@tindex lnot XThe @kbd{a !} (@code{calc-logical-not}) [@samp{lnot(a)} or @samp{! a}] Xfunction is true if @samp{a} is false (zero), or false if @samp{a} is Xtrue (nonzero). It is left in symbolic form if @samp{a} is not a Xnumber. X X@tindex if XThe @samp{if(a,b,c)} or @samp{a ? b : c} function is equal to either X@samp{b} or @samp{c} if @samp{a} is a nonzero number or zero, respectively. XIf @samp{a} is not a number, the test is left in symbolic form and Xneither @samp{b} nor @samp{c} is evaluated in any way. This is the Xonly Calc function whose arguments are not automatically evaluated Xwhen the function itself is evaluated. X X@kindex a @{ X@pindex calc-in-set X@tindex in XThe @kbd{a @{} (@code{calc-in-set}) [@samp{in(a,b)}] function is true if Xthe number @samp{a} is in the set of numbers represented by @samp{b}. XIf @samp{b} is an interval form, @samp{a} must be one of the values Xencompassed by the interval. If @samp{b} is a vector, @samp{a} must be Xequal to one of the elements of the vector. (If any vector elements are Xintervals, @samp{a} must be in any of the intervals.) If @samp{b} is a Xplain number, @samp{a} must be numerically equal to @samp{b}. X X@tindex typeof XThe @samp{typeof(a)} function produces an integer or variable which Xcharacterizes @samp{a}. If @samp{a} is a number, vector, or variable, Xthe result will be one of the following numbers: X X@example X 1 Integer X 2 Fraction X 3 Floating-point number X 4 HMS form X 5 Rectangular complex number X 6 Polar complex number X 7 Error form X 8 Interval form X 9 Modulo form X100 Variable X101 Vector (but not a matrix) X102 Matrix X@end example X XOtherwise, @samp{a} is a formula, and the result is a variable which Xrepresents name of the top-level function call. X X@tindex integer X@tindex real X@tindex constant XThe @samp{integer(a)} function returns true if @samp{a} is an integer. XThis is shorthand for @samp{typeof(a) = 1}. The @samp{real(a)} function Xis true if @samp{a} is a real number, either integer, fraction, or Xfloat. The @samp{constant(a)} function returns true if @samp{a} is Xany of the objects for which @code{typeof} would produce an integer Xcode result except for variables, and provided that the components of Xan object like a vector or error form are themselves constant. X X@tindex refers XThe @samp{refers(a,b)} function is true if the variable (or sub-expression) X@samp{b} appears in @samp{a}, or false otherwise. Unlike the other Xtests described here, this function returns a definite ``no'' answer Xeven if its arguments are still in symbolic form. The only case where X@code{refers} will be left unevaluated is if @samp{a} is a plain Xvariable (different from @samp{b}). X X@node Calculus, , Logical Operations, Algebra X@section Calculus X XThe following calculus commands do not automatically simplify their Xinputs or outputs using @code{calc-simplify}. You may find it helps Xto do this by hand by typing @kbd{a s} or @kbd{a e}. It may also help Xto use @kbd{a x} and/or @kbd{a c} to arrange a result in the most Xreadable way. X X@kindex a d X@kindex H a d X@pindex calc-derivative X@tindex deriv X@tindex tderiv XThe @kbd{a d} (@code{calc-derivative}) [@code{deriv}] command computes Xthe derivative of the expression on the top of the stack with respect to Xsome variable, which it will prompt you to enter. Normally, variables Xin the formula other than the specified differentiation variable are Xconsidered constant, i.e., @samp{deriv(y,x)} is reduced to zero. With Xthe Hyperbolic flag, the @code{tderiv} (total derivative) operation is used Xinstead, in which derivatives of variables are not reduced to zero. X XIf you use the @code{deriv} function directly in an algebraic formula, Xyou can also write @samp{deriv(f,x,x0)} which represents the derivative Xof @code{f} with respect to @code{x}, evaluated at the point @samp{x=x0}. X XIf the formula being differentiated contains functions which Calc does Xnot know, the derivatives of those functions are produced by adding Xprimes (apostrophe characters). For example, @samp{deriv(f(2x), x)} Xproduces @samp{2 f'(2 x)}, where the function @code{f'} represents the Xderivative of @code{f}. If you enter a definition for @code{f'}, for Xexample using the @kbd{Z F} (@code{calc-user-define-formula}) command, Xthe Calculator will use it. @xref{Algebraic Definitions}. X XFor multi-argument functions @samp{f(x,y,z)}, the derivative with respect Xto the first argument is written @samp{f'(x,y,z)}; derivatives with Xrespect to the other arguments are @samp{f'2(x,y,z)} and @samp{f'3(x,y,z)}. XVarious higher-order derivatives can be formed in the obvious way, e.g., X@samp{f'@var{}'(x)} (the second derivative of @code{f}) or X@samp{f'@var{}'2'3(x,y,z)} (@code{f} differentiated with respect to each Xargument once).@refill X X@kindex a i X@pindex calc-integral X@tindex integ XThe @kbd{a i} (@code{calc-integral}) [@code{integ}] command computes the Xindefinite integral of the expression on the top of the stack with Xrespect to a variable. The integrator is not guaranteed to work for Xall integrable functions, but it will work for any polynomial and for Xmost simple functions. X XIf you use the @code{integ} function directly in an algebraic formula, Xyou can also write @samp{integ(f,x,v)} which expresses the resulting Xindefinite integral in terms of variable @code{v} instead of @code{x}, Xor @samp{integ(f,x,a,b)}, which represents a definite integral from X@code{a} to @code{b}. X XThe Calculator remembers all the integrals it has done. If conditions Xchange in a way that would invalidate the old integrals, they will be Xthrown out. If you suspect this is not happening when it should, Xuse the @code{calc-flush-caches} command; @pxref{Caches}. X X@kindex a I X@pindex calc-integral-limit XThe @kbd{a I} (@code{calc-integral-limit}) command displays or, with a Xnumeric prefix argument, sets the current ``integration nesting limit.'' XThis is the depth to which Calc will pursue integration by substitution Xor integration by parts before abandoning an approach as fruitless. XThe default value is 3. If the integrator is taking too long, you Xmight consider lowering this limit. However, the lower this limit is, Xthe greater the chance that Calc will be unable to integrate a function Xit could otherwise handle. Raising this limit allows the Calculator to Xsolve more integrals, though the time it takes may grow exponentially. XYou can monitor the integrator's actions by creating an Emacs buffer called X@code{*Trace*}. If such a buffer exists, the @kbd{a i} command will write Xa log of its actions there. X X@kindex a t X@pindex calc-taylor X@tindex taylor XThe @kbd{a t} (@code{calc-taylor}) [@code{taylor}] command computes a Xpower series expansion or Taylor series of a function. You specify the Xvariable and the desired number of terms. You may give an expression of Xthe form @samp{@var{var} = @var{a}} or @samp{@var{var} - @var{a}} to Xproduce a Taylor expansion about the point @var{a}. You may specify the Xnumber of terms with a numeric prefix argument; otherwise the command Xwill prompt you for the number of terms. Note that many series Xexpansions have coefficients of zero for some terms, so you may appear Xto get fewer terms than you asked for.@refill X XIf the @kbd{a i} command is unable to find a symbolic integral for a Xfunction, you can get an approximation by integrating the function's XTaylor series. X X@kindex a S X@pindex calc-solve-for X@tindex solve XThe @kbd{a S} (@code{calc-solve-for}) [@code{solve}] command rearranges Xan equation to solve for a specific variable. An equation is an Xexpression of the form @samp{L = R}. If the input is not an equation, Xit is treated like an equation of the form @samp{X = 0}. For example, Xthe command @kbd{a S x} will rearrange @samp{y = 3x + 6} to the form, X@samp{x = y/3 - 2}. X X@kindex H a S X@tindex fsolve XSome equations have more than one solution. The Hyperbolic flag X(@code{H a S}) [@code{fsolve}] tells the solver to report the fully Xgeneral family of solutions. It will invent variables @code{n1}, X@code{n2}, @dots{}, which represent independent arbitrary integers, and X@code{s1}, @code{s2}, @dots{}, which represent independent arbitrary Xsigns (either @samp{+1} or @samp{-1}). If you don't use the Hyperbolic Xflag, Calc will use zero in place of all arbitrary integers, and plus Xone in place of all arbitrary signs. Note that variables like @code{n1} Xand @code{s1} are not given any special interpretation in Calc except by X@code{calc-solve-for} itself. As usual, you can use the @code{calc-let} Xcommand to obtain solutions for various actual values of these Xvariables. X X@kindex I a S X@kindex H I a S X@tindex finv X@tindex ffinv XWith the Inverse flag, @kbd{I a S} [@code{finv}] treats the expression Xon top of the stack as a function of the specified variable and solves Xto find the inverse function, written in terms of the same variable. XFor example, @kbd{I a S x} inverts @samp{2x + 6} to @samp{x/2 - 3}. XYou can use both Inverse and Hyperbolic [@code{ffinv}] to obtain a Xfully general inverse, as described above. X X@node Units, Store and Recall, Algebra, Top X@chapter Operating on Units X XOne special interpretation of formulas is as numbers with units. XFor example, the formula @samp{5 m / s^2} can be read ``five meters Xper second squared.'' The commands in this chapter help you Xmanipulate units expressions in this form. Units-related commands Xbegin with the @kbd{u} prefix key. X X@menu X* Basic Operations on Units:: X* The Units Table:: X* Predefined Units:: X* User-Defined Units:: X@end menu X X@node Basic Operations on Units, The Units Table, Units, Units X@section Basic Operations on Units X XA @dfn{units expression} is a formula which is basically a number Xmultiplied and/or divided by one or more @dfn{unit names}, which may Xoptionally be raised to powers. Actually, the value part need not be Xa number; any product or quotient involving unit names is a unit Xexpression. Many of the units commands will also accept any formula, Xwhere the command applies to all units expressions which appear in the Xformula. X XA unit name is a variable whose name appears in the @dfn{unit table}, Xor a variable whose name is a prefix character like @samp{k} (for ``kilo'') Xor @samp{u} (for ``micro'') followed by a name from the unit table. XA substantial table of built-in units is provided with Calc; X@pxref{Predefined Units}. You can also define your own unit names; X@pxref{User-Defined Units}.@refill X XNote that if the value part of a units expression is exactly @samp{1}, Xit will be removed by the Calculator's automatic algebra routines: The Xformula @samp{1 mm} is ``simplified'' to @samp{mm}. This is only a Xdisplay anomaly, however; @samp{mm} will work just fine as a Xrepresentation of one millimeter.@refill X XYou may find that Algebraic Mode (@pxref{Algebraic Entry}) makes working Xwith units expressions easier. Otherwise, you will have to remember Xto hit the apostrophe key every time you wish to enter units. X X@kindex u s X@pindex calc-simplify-units XThe @kbd{u s} (@code{calc-simplify-units}) command simplifies a units Xexpression. It uses @kbd{a s} (@code{calc-simplify}) to simplify the Xexpression first as a regular algebraic formula; it then looks for Xfeatures that can be further simplified by converting one object's units Xto be compatible with another's. For example, @samp{5 m + 23 mm} will Xsimplify to @samp{5.023 m}. When different but compatible units are Xadded, the righthand term's units are converted to match those of the Xlefthand term. @xref{Simplification Modes}, for a way to have this done Xautomatically at all times. X XUnits simplification also handles quotients of two units with the same Xdimensionality, as in @samp{2 in s/L cm} to @samp{5.08 s/L}; fractional Xpowers of unit expressions, as in @samp{sqrt(9 mm^2)} to @samp{3 mm} and X@samp{sqrt(9 acre)} to a quantity in meters; and @code{floor}, X@code{ceil}, @code{round}, @code{trunc}, @code{float}, @code{frac}, X@code{abs}, and @code{clean} applied to units expressions, in which case Xthe operation in question is applied only to the numeric part of the Xexpression. Finally, trigonometric functions of quantities with units Xof angle are evaluated, regardless of the current angular mode.@refill X X@kindex u c X@pindex calc-convert-units XThe @kbd{u c} (@code{calc-convert-units}) command converts a units Xexpression to new, compatible units. For example, given the units Xexpression @samp{55 mph}, typing @kbd{u c m/s @key{RET}} produces X@samp{24.5872 m/s}. If the units you request are inconsistent with Xthe original units, the number will be converted into your units Xtimes whatever ``remainder'' units are left over. For example, Xconverting @samp{55 mph} into acres produces @samp{6.08e-3 acre / m s}. X(Recall that multiplication binds more strongly than division in Calc Xformulas, so the units here are acres per meter-second.) Remainder Xunits are expressed in terms of ``fundamental'' units like @samp{m} and X@samp{s}, regardless of the input units. X XYou can use explicit unit conversion instead of the @kbd{u s} command Xto gain more control over the units of the result of an expression. XFor example, given @samp{5 m + 23 mm}, you can type @kbd{u c m} or X@kbd{u c mm} to express the result in either meters or millimeters. X(For that matter, you could type @kbd{u c fath} to express the result Xin fathoms, if you preferred!) X XIn place of a specific set of units, you can also enter one of the Xunits system names @code{si}, @code{mks} (equivalent), or @code{cgs}. XFor example, @kbd{u c si @key{RET}} converts the expression into XInternational System of Units (SI) base units. Also, @code{base} Xconverts to Calc's base units, which are the same as @code{si} units Xexcept that @code{base} uses @samp{g} as the fundamental unit of mass Xwhereas @code{si} uses @samp{kg}. X XIf the value on the stack does not contain any units, @kbd{u c} will Xprompt first for the old units which this value should be considered Xto have, then for the new units. X X@kindex u b X@pindex calc-base-units XThe @kbd{u b} (@code{calc-base-units}) command is shorthand for X@kbd{u c base}; it converts the units expression on the top of the Xstack into @code{base} units. If @kbd{u s} does not simplify a Xunits expression as far as you would like, try @kbd{u b}. X XThe @kbd{u c} and @kbd{u b} commands treat temperature units (like X@samp{degC} and @samp{K}) as relative temperatures. For example, X@kbd{u c} converts @samp{10 degC} to @samp{18 degF}: A change of 10 Xdegrees Celsius corresponds to a change of 18 degrees Fahrenheit. X X@kindex u t X@pindex calc-convert-temperature X@cindex Temperature conversion XThe @kbd{u t} (@code{calc-convert-temperature}) command converts Xabsolute temperatures. The value on the stack must be a simple units Xexpression with units of temperature only. This command would convert X@samp{10 degC} to @samp{50 degF}, the equivalent temperature on the XFahrenheit scale.@refill X X@kindex u r X@pindex calc-remove-units X@kindex u x X@pindex calc-extract-units XThe @kbd{u r} (@code{calc-remove-units}) command removes units from the Xformula at the top of the stack. The @kbd{u x} X(@code{calc-extract-units}) command extracts only the units portion of a Xformula. These commands essentially replace every term of the formula Xthat does or doesn't (respectively) look like a unit name by the Xconstant 1, then resimplify the formula.@refill X X@node The Units Table, Predefined Units, Basic Operations on Units, Units X@section The Units Table X X@kindex u v X@pindex calc-enter-units-table XThe @kbd{u v} (@code{calc-enter-units-table}) command displays the units table Xin another buffer called @code{*Units Table*}. Each entry in this table Xgives the unit name as it would appear in an expression, the definition Xof the unit in terms of simpler units, and a full name or description of Xthe unit. Fundamental units are defined as themselves; these are the Xunits produced by the @kbd{u b} command. The fundamental units are Xmeters, seconds, grams, kelvins, amperes, candelas, moles, radians, Xand steradians. X XThe Units Table buffer also displays the Unit Prefix Table. Note that Xtwo prefixes, ``kilo'' and ``hecto,'' accept either upper- or lower-case Xprefix letters. @samp{Meg} is also accepted as a synonym for the @samp{M} Xprefix. Whenever a unit name can be interpreted as either a built-in name Xor a prefix followed by another built-in name, the former interpretation Xwins. For example, @samp{2 pt} means two pints, not two pico-tons. X XThe Units Table buffer, once created, is not rebuilt unless you define Xnew units. To force the buffer to be rebuilt, give any numeric prefix Xargument to @kbd{u v}. X X@kindex u V X@pindex calc-view-units-table XThe @kbd{u V} (@code{calc-enter-units-table}) command is like @kbd{u v} except Xthat the cursor is not moved into the Units Table buffer. To return Xfrom the Units Table buffer after a @kbd{u v}, type @kbd{M-x calc} Xagain or use the regular Emacs @kbd{C-x o} (@code{other-window}) Xcommand. You can also kill the buffer with @kbd{C-x k} if you wish; Xthe actual units table is safely stored inside the Calculator. X X@kindex u g X@pindex calc-get-unit-definition XThe @kbd{u g} (@code{calc-get-unit-definition}) command retrieves a unit's Xdefining expression and pushes it onto the Calculator stack. For example, X@kbd{u g in} will produce the expression @samp{2.54 cm}. This is the Xsame definition for the unit that would appear in the Units Table buffer. XNote that this command works only for actual unit names; @kbd{u g km} Xwill report that no such unit exists, for example, because @code{km} is Xreally the unit @code{m} with a @code{k} (``kilo'') prefix. To see a Xdefinition of a unit in terms of base units, it is easier to push the Xunit name on the stack and then reduce it to base units with @kbd{u b}. X X@kindex u e X@pindex calc-explain-units XThe @kbd{u e} (@code{calc-explain-units}) command displays an English Xdescription of the units of the expression on the stack. For example, Xfor the expression @samp{62 km^2 g / s^2 mol K}, the description is X``Square-Kilometer Gram per (Second-squared Mole Degree-Kelvin).'' This Xcommand uses the English descriptions that appear in the righthand Xcolumn of the Units Table. X X@node Predefined Units, User-Defined Units, The Units Table, Units X@section Predefined Units X XSince the exact definitions of many kinds of units have evolved over the Xyears, and since certain countries sometimes have local differences in Xtheir definitions, it is a good idea to examine Calc's definition of a Xunit before depending on its exact value. For example, there are three Xdifferent units for gallons, corresponding to the US, Canadian, and XBritish definitions. Also, note that @code{oz} is a standard ounce of Xmass, @code{ozt} is a Troy ounce, and @code{ozfl} is a fluid ounce. X XThe temperature units corresponding to degrees Kelvin and Centigrade X(Celsius) are the same in this table, since most units commands treat Xtemperatures as being relative. The @code{calc-convert-temperature} Xcommand has special rules for handling the different absolute magnitudes Xof the various temperature scales. X XSome ``units'' are really physical constants; for example, @code{c} Xrepresents the speed of light, and @code{h} represents Planck's Xconstant. You can use these just like other units: converting X@samp{.5 c} to @samp{m/s} expresses one-half the speed of light in Xmeters per second. You can also use this merely as a handy reference; Xthe @kbd{u g} command gets the definition of one of these constants Xin its normal terms, and @kbd{u b} expresses the definition in base Xunits. X XTwo units, @code{pi} and @code{fsc} (the fine structure constant) are Xdimensionless. The units simplification commands simply treat these Xnames as equivalent to their corresponding values. However you can, for Xexample, use @kbd{u c} to convert a pure number into multiples of the Xfine structure constant, or @kbd{u b} to convert this back into a pure Xnumber. (When @kbd{u c} prompts for the ``old units,'' just enter a Xblank line to signify that the value really is unitless.) X X@c Describe angular units, luminosity vs. steradians problem. X X@node User-Defined Units, , Predefined Units, Units X@section User-Defined Units X X@kindex u d X@pindex calc-define-unit X@cindex User-defined units XThe @kbd{u d} (@code{calc-define-unit}) command records the units Xexpression on the top of the stack as the definition for a new, Xuser-defined unit. For example, putting @samp{16.5 ft} on the stack and Xtyping @kbd{u d rod} defines the new unit @samp{rod} to be equivalent to X16.5 feet. The unit conversion and simplification commands will now Xtreat @code{rod} just like any other unit of length. You will also be Xprompted for an optional English description of the unit, which will Xappear in the Units Table. X X@kindex u u X@pindex calc-undefine-unit XThe @kbd{u u} (@code{calc-undefine-unit}) command removes a user-defined Xunit. It is not possible to remove one of the predefined units, Xhowever. X XIf you define a unit with an existing unit name, your new definition Xwill replace the original definition of that unit. If the unit was a Xpredefined unit, the old definition will not be replaced, only X``shadowed.'' The built-in definition will reappear if you later use X@kbd{u u} to remove the shadowing definition. X XTo create a new fundamental unit, use either 1 or the unit name itself Xas the defining expression. Otherwise the expression can involve any Xother units that you like. The next unit operation like @kbd{u c} or @kbd{u v} Xwill rebuild the internal unit table incorporating your modifications. XNote that erroneous definitions (such as two units defined in terms of Xeach other) will not be detected until the unit table is next rebuilt; X@kbd{u v} is a convenient way to cause this to happen. X XTemperature units are treated specially inside the Calculator; it is not Xpossible to create user-defined temperature units. X X@kindex u p X@pindex calc-permanent-units X@cindex @file{.emacs} file, user-defined units XThe @kbd{u p} (@code{calc-permanent-units}) command stores the user-defined Xunits in your @file{.emacs} file, so that the units will still be Xavailable in subsequent Emacs sessions. If there was already a set of Xuser-defined units in your @file{.emacs} file, it is replaced by the Xnew set. X X@node Store and Recall, Kill and Yank, Units, Top X@chapter Storing and Recalling Variables X XCalculator variables are really just Lisp variables that contain numbers Xor formulas in a form that Calc can understand. The commands in this Xsection allow you to manipulate variables conveniently. X X@menu X* Storing Variables:: X* Recalling Variables:: X* Let Command:: X@end menu X X@node Storing Variables, Recalling Variables, Store and Recall, Store and Recall X@section Storing Variables X X@kindex s X@pindex calc-store X@cindex Storing variables X@cindex Quick variables XThe @kbd{s} (@code{calc-store}) command stores the value at the top of Xthe stack into a specified variable. It prompts you to enter the Xname of the variable. If you press a single digit, the value is stored Ximmediately in one of the ``quick'' variables @code{var-0} through X@code{var-9}. Or you can enter any variable name. The prefix @samp{var-} Xis supplied for you; when a name appears in a formula (as in @samp{a+b}) Xthe prefix @samp{var-} is also supplied there, so normally you can simply Xforget about @samp{var-} everywhere. Its only purpose is to enable you to Xuse Calc variables without fear of accidentally clobbering some variable in Xanother program. If you really want to store in an arbitrary Lisp variable, Xjust backspace over the @samp{var-}. X XThe value stored generally replaces any old contents of the variable, Xand also remains on the stack. (The @key{DEL} key can then be used to Xremove it from the stack if you wish.) If you press one of the operator Xkeys @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/}, @kbd{^}, or @kbd{|} before Xentering the variable name, the value on the top of the stack is added Xto, subtracted from, multiplied or divided into, used as a power for, or Xconcatenated to the value already in the specified variable. (The new Xvalue of the variable is reported in the @samp{*Calc Trail*} buffer for Xyour information.)@refill X X@pindex calc-unstore X@cindex Void variables X@cindex Un-storing variables XUntil you store a value in them, variables are ``void,'' that is, they Xcontain no value at all. If they appear in an algebraic formula they Xwill be left alone even if you press @kbd{=} (@code{calc-evaluate}). XTo return a variable to the void state, use @code{calc-unstore}. An Xeasy keyboard shortcut for this command is @kbd{s} (@code{calc-store}) Xwith any numeric prefix argument: @kbd{C-u s foo @key{RET}} XThis form does not use the value on Xthe top of the stack; it simply removes any value that may already be Xdefined for the specified variable.@refill X X@kindex Z V X@pindex calc-permanent-variable X@cindex Storing variables X@cindex Permanent variables X@cindex @file{.emacs} file, veriables XThe shift-@kbd{Z V} (@code{calc-permanent-variable}) command saves a Xvariable's value permanently in your @file{.emacs} file, so that its Xvalue will still be available in future Emacs sessions. You can Xre-execute @kbd{Z V} later on to update the saved value, but the Xonly way to remove a saved variable is to edit your @file{.emacs} file Xby hand. (The shift-@kbd{Z} prefix key is mainly for defining user Xcommands; @pxref{Programming}.) X XThe only variables with predefined values are the ``special constants'' X@code{var-pi}, @code{var-e}, and @code{var-i}. You are free to unstore these Xvariables or to store a new value over them if you like, although some Xof the algebraic-manipulation functions may assume these variables Xrepresent their standard values. X X@node Recalling Variables, Let Command, Storing Variables, Store and Recall X@section Recalling Variables X X@kindex r X@pindex calc-recall X@cindex Recalling variables XThe most straightforward way to extract the stored value from a variable Xis to use the @kbd{r} (@code{calc-recall}) command. This command prompts Xfor a variable name (similarly to @code{calc-store}), looks up the value Xof the specified variable, and pushes that value onto the stack. It is Xan error to try to recall a void variable. X XIt is also possible to recall the value from a variable by evaluating a Xformula containing that variable. For example, @kbd{' a @key{RET} =} is Xthe same as @kbd{r a @key{RET}} except that if the variable is void, the Xformer will simply leave the formula @samp{a} on the stack whereas the Xlatter will produce an error message. X X@node Let Command, , Recalling Variables, Store and Recall X@section The Let Command X X@kindex l X@pindex calc-let X@cindex Variables, temporary assignment X@cindex Temporary assignment to variables XIf you have an expression like @samp{a+b^2} on the stack and you wish to Xcompute its value where @samp{b=3}, you can simply store 3 in @samp{b} and Xthen press @kbd{=} to reevaluate the formula. This has the side-effect Xof storing the value 3 in @samp{b} for future operations. X XThe lowercase-@kbd{l} (@code{calc-let}) command evaluates a formula under Xa @emph{temporary} assignment of a variable. It stores the value on the Xtop of the stack into the specified variable, then evaluates the Xsecond-to-top stack entry, then restores the orginal value (or lack Xof one) in the variable. Thus after @kbd{' a+b^2 @key{RET} 3 l b @key{RET}}, Xthe stack will contain the formula @samp{a + 9}. The subsequent command X@kbd{5 l a @key{RET}} will replace this formula with the number 14. The Xvariables @samp{a} and @samp{b} are not permanently affected in any way Xby these commands. X X@node Kill and Yank, Programming, Store and Recall, Top X@chapter Kill and Yank Functions X XThe commands in this chapter move information between the Calculator and Xother Emacs editing buffers. X X@menu X* Killing From Stack:: X* Yanking Into Stack:: X* Grabbing From Buffers:: X* Yanking Into Buffers:: X* Editing Stack Entries:: X@end menu X X@node Killing From Stack, Yanking Into Stack, Kill and Yank, Kill and Yank X@section Killing from the Stack X X@kindex C-k X@pindex calc-kill X@kindex M-k X@pindex calc-copy-as-kill X@kindex C-w X@pindex calc-kill-region X@kindex M-w X@pindex calc-copy-region-as-kill X@cindex Kill ring X@dfn{Kill} commands are Emacs commands that insert text into the X``kill ring,'' from which it can later be ``yanked'' by a @kbd{C-y} Xcommand. Three common kill commands in normal Emacs are @kbd{C-k}, which Xkills one line, @kbd{C-w}, which kills the region between mark and point, Xand @kbd{M-w}, which puts the region into the kill ring without actually Xdeleting it. All of these commands work in the Calculator, too. Also, X@kbd{M-k} has been provided to complete the set; it puts the current line Xinto the kill ring without deleting anything. X XThe kill commands are unusual in that they pay attention to the location Xof the cursor in the Calculator buffer. If the cursor is on or below the Xbottom line, the kill commands operate on the top of the stack. Otherwise, Xthey operate on whatever stack element the cursor is on. Calc's kill Xcommands always operate on whole stack entries. (They act the same as their Xstandard Emacs cousins except they ``round up'' the specified region to Xencompass full lines.) The text is copied into the kill ring exactly as Xit appears on the screen, including line numbers if they are enabled. X XA numeric prefix argument to @kbd{C-k} or @kbd{M-k} affects the number Xof lines killed. A positive argument kills the current line and @samp{n-1} Xlines below it. A negative argument kills the @samp{-n} lines above the Xcurrent line. Again this mirrors the behavior of the standard Emacs X@kbd{C-k} command. Although a whole line is always deleted, @kbd{C-k} Xwith no argument copies only the number itself into the kill ring, whereas X@kbd{C-k} with a prefix argument of 1 copies the number with its trailing Xnewline. X X@node Yanking Into Stack, Grabbing From Buffers, Killing From Stack, Kill and Yank X@section Yanking into the Stack X X@kindex C-y X@pindex calc-yank XThe @kbd{C-y} command yanks the most recently killed text back into the XCalculator. It pushes this value onto the top of the stack regardless of Xthe cursor position. In general it re-parses the killed text as a number Xor formula (or list of these seperated by commas or newlines). However if Xthe thing being yanked is something that was just killed from the Calculator Xitself, its full internal structure is yanked. For example, if you have Xset the floating-point display mode to show only four significant digits, Xthen killing and re-yanking 3.14159 (which displays as 3.142) will yank the Xfull 3.14159, even though yanking it into any other buffer would yank the Xnumber in its displayed form, 3.142. (Since the default display modes Xshow all objects to their full precision, this feature normally makes no Xdifference.) X X@node Grabbing From Buffers, Yanking Into Buffers, Yanking Into Stack, Kill and Yank X@section Grabbing from Other Buffers X X@kindex M-# (calc-grab-region) X@pindex calc-grab-region XThe @code{calc-grab-region} command takes the text between point and mark Xin the current buffer and attempts to parse it as a matrix. If point and Xmark are both in the leftmost column, the lines in between are parsed in Xtheir entirety. Otherwise, point and mark define the corners of a rectangle Xwhose contents are parsed. Note that, unlike all other @samp{calc-} Xcommands, @code{calc-grab-region} is intended to be used in a normal Xediting buffer, @emph{not} from inside the Calculator buffer! If the Xcommand works successfully, it does an automatic @kbd{M-x calc} to enter Xthe Calculator buffer. X XThe @kbd{M-#} key with a negative prefix argument (@kbd{M-- M-#}) is Xequivalent to @code{calc-grab-region}. X XEach line of the grabbed area must contain one or more numbers, Xseparated by spaces and/or commas. Leading and trailing square Xbrackets, curly braces and commas on the line are ignored. Leading Xline numbers (as found in the Calc stack) are also ignored. Thus, this Xcommand can generally read anything from a column of numbers in a Xspreadsheet to a matrix in one of Calc's own display formats. The Xgrabbed values may actually be any Calc formulas, except that spaces Xnot enclosed in parentheses will be interpreted as separating two Xseparate formulas.@refill X XIf a different language has been specified (@pxref{Language Modes}), Xthe grabbed text will be interpreted according to the that language. X XEach line becomes a row of the matrix. The result will actually be a Xvector of vectors, which Calc will treat as a matrix only if every row Xcontains the same number of values. @xref{Matrix Functions}, to see how Xto pull the matrix apart into its constituent rows and columns. (If it Xis a 1x1 matrix, just hit @kbd{v u} (@code{calc-unpack}) twice.) X XFor example, suppose we have a column of numbers in a file which we Xwish to sum. Go to one corner of the column and press @kbd{C-@@} to Xset the mark; go to the other corner and type @kbd{M-x calc-grab-region}. XThis will grab the column of numbers into the calculator in the form Xof column matrix. Press @kbd{v t} to transpose this into a row matrix. XPress @kbd{v u} to unpack this into a simple vector. (Recall, a one-row Xmatrix is a vector of a single vector.) Then, type @kbd{V R +} to Xcompute the sum. X X@node Yanking Into Buffers, Editing Stack Entries, Grabbing From Buffers, Kill and Yank X@section Yanking into Other Buffers X X@kindex y X@pindex calc-copy-to-buffer XThe plain @kbd{y} (@code{calc-copy-to-buffer}) command inserts the number Xat the top of the stack into the most recently used normal editing buffer. X(More specifically, this is the most recently used buffer which is displayed Xin a window and whose name does not begin with @samp{*}. If there is no Xsuch buffer, this is the most recently used buffer except for Calculator Xand Calc Trail buffers.) The number is inserted exactly as it appears and Xwithout a newline. (If line-numbering is enabled, the line number is Xnormally not included.) The number is @emph{not} removed from the stack. X XWith a prefix argument, @kbd{y} inserts several numbers, one per line. XA positive argument inserts the specified number of values from the top Xof the stack. A negative argument inserts the @samp{n}th value from the Xtop of the stack. An argument of zero inserts the entire stack. Note Xthat @kbd{y} with an argument of 1 is different from @kbd{y} with no Xargument; the former always copies exactly what appears in the stack Xdisplay, whereas the latter strips off the line number and trailing Xnewline. X XWith a lone @kbd{C-u} as a prefix argument, @kbd{y} @emph{replaces} the Xregion in the other buffer with the yanked text, then quits the Calculator, Xleaving you in that buffer. A typical use would be to run X@code{calc-grab-region} to read a matrix of data into the Calculator, Xoperate on the data to produce a new matrix, then type @kbd{C-u y} to Xreplace the original matrix with the new one. One would normally disable Xline-numbering (with @kbd{d l}) before doing this, and possibly also alter Xthe matrix display style (@pxref{Vector and Matrix Formats}) or change the Xcurrent display language (@pxref{Language Modes}). Also, note Xthat this command replaces a linear region of text, not a rectangle.@refill X X@node Editing Stack Entries, , Yanking Into Buffers, Kill and Yank X@section Editing Stack Entries X X@kindex ` X@pindex calc-edit X@kindex C-c C-c (Edit Mode) X@pindex calc-edit-finish X@cindex Editing the stack with Emacs XThe backquote, @kbd{`} (@code{calc-edit}) command creates a temporary Xbuffer (@samp{*Calc Edit*}) for editing the top-of-stack value using Xregular Emacs commands. With a numeric prefix argument, it edits the Xspecified number of stack entries at once. (An argument of zero edits Xthe entire stack.) When you press @key{RET}, @key{LFD}, or @kbd{C-c C-c} X(all bound to @code{calc-edit-finish}), the Calculator parses the Xlines of text in this buffer as numbers or formulas, replaces the Xoriginal stack elements in the original buffer with these new values, Xthen kills the @samp{*Calc Edit*} buffer. The original Calculator buffer Xcontinues to exist during editing, but for best results you should be Xcareful not to change it until you have finished the edit. You can Xalso cancel the edit simply by killing the @samp{*Calc Edit*} buffer Xwith @kbd{C-x k} (@code{kill-buffer}). X X@node Programming, Installation, Kill and Yank, Top X@chapter Programming the Calculator X XThere are several ways to ``program'' the Emacs Calculator, depending Xon the nature of the problem you need to solve. X X@enumerate X@item X@dfn{Keyboard macros} allow you to record a sequence of keystrokes Xand play them back at a later time. This is just the standard Emacs Xkeyboard macro mechanism, dressed up with a few more features such Xas loops and conditionals. X@item X@dfn{Algebraic definitions} allow you to use any formula to define a Xnew function. This function can then be used in algebraic formulas or Xas an interactive command. X@item X@dfn{Rewrite rules} are discussed in the section on algebra commands. XYou can use them for programming by creating a command (say, using Xkeyboard macros) that applies the rules that define your function's Xbehavior. @xref{Rewrite Rules}. X@item X@dfn{Lisp} is the programming language that Calc (and most of Emacs) Xis written in. If the above techniques aren't powerful enough, you Xcan write Lisp functions to do anything that built-in Calc commands Xcan do. Lisp code is also somewhat faster than keyboard macros. X@end enumerate X XProgramming features are available through the @kbd{z} and @kbd{Z} Xprefix keys. New commands that you define are two-key sequences Xbeginning with @kbd{z}. Commands for managing these definitions Xuse the shift-@kbd{Z} prefix. (The @kbd{Z V} (@code{calc-permanent-variable}) Xcommand is described elsewhere; @pxref{Storing Variables}.) X X@menu X* Creating User Keys:: X* Keyboard Macros:: X* Algebraic Definitions:: X* Lisp Definitions:: X@end menu X X@node Creating User Keys, Keyboard Macros, Programming, Programming X@section Creating User Keys X X@kindex Z D X@pindex calc-user-define XAny Calculator command may be bound to a key using the @kbd{Z D} X(@code{calc-user-define}) command. Actually, it is bound to a two-key Xsequence beginning with the @kbd{z} prefix. (Note that the commands Xfor programming begin with shift-@kbd{Z}, and your own commands begin Xwith unshifted @kbd{z}.) X XThe @kbd{Z D} command first prompts for the key to define. For example, Xpress @kbd{Z D a} to define the new key sequence @kbd{z a}. You are then Xprompted for the name of the Calculator command that this key should Xrun. For example, the @code{calc-hypot} (hypotenuse) command is not normally Xavailable on a key. Typing @kbd{Z D h hypot @key{RET}} programs the X@kbd{z h} key sequence to run @code{calc-hypot}. This definition will remain Xin effect for the rest of this Emacs session, or until you redefine X@kbd{z h} to be something else. X XYou can actually bind any Emacs command to a @kbd{z} key sequence by Xbackspacing over the @samp{calc-} when you are prompted for the command name. X XAs with any other prefix key, you can type @kbd{z ?} to see a list of Xall the two-key sequences you have defined that start with @kbd{z}. XInitially, no @kbd{z} sequences (except @kbd{z ?} itself) are defined. X XUser keys are typically letters, but may in fact use any key. X(@key{META}-keys are not permitted, nor are a terminal's special Xfunction keys which generate multi-character sequences when pressed.) XYou can define different commands on the shifted and unshifted versions Xof a letter if you wish. X X@kindex Z U X@pindex calc-user-undefine XThe @kbd{Z U} (@code{calc-user-undefine}) command unbinds a user key. XFor example, the key sequence @kbd{Z U h} will undefine the @code{hypot} Xkey we defined above. X X@kindex Z P X@pindex calc-user-define-permanent X@cindex Storing user definitions X@cindex Permanent user definitions X@cindex @file{.emacs} file, user-defined commands XThe @kbd{Z P} (@code{calc-user-define-permanent}) command makes a key Xbinding permanent so that it will remain in effect even in future Emacs Xsessions. (It does this by adding a suitable bit of Lisp code into Xyour @file{.emacs} file.) For example, @kbd{Z P h} would register Xour @code{hypot} command permanently. If you later wish to unregister Xthis command you must edit your @file{.emacs} file by hand. X X@kindex Z E X@pindex calc-user-define-edit X@cindex Editing user definitions XThe @kbd{Z E} (@code{calc-user-define-edit}) command edits the definition Xof a user key. This works for keys that have been defined by either Xkeyboard macros or formulas; further details are contained in the relevant Xfollowing sections. X X@node Keyboard Macros, Algebraic Definitions, Creating User Keys, Programming X@section Programming with Keyboard Macros X X@kindex K X@cindex Programming with keyboard macros X@cindex Keyboard macros XThe easiest way to ``program'' the Emacs Calculator is to use standard Xkeyboard macros. Press @kbd{C-x (} to begin recording a macro. From Xthis point on, keystrokes you type will be saved away as well as Xperforming their usual functions. Press @kbd{C-x )} to end recording. XPress shift-@kbd{K} (or the standard Emacs key sequence @kbd{C-x e}) to Xexecute your keyboard macro by replaying the recorded keystrokes. X@xref{Keyboard Macros, , , emacs, the Emacs manual}, for further Xinformation.@refill X XWhen you use @kbd{K} to invoke a keyboard macro, the entire macro is Xtreated as a single command by the undo and trail features. The stack Xdisplay buffer is not updated during macro execution, but is instead Xfixed up once the macro completes. Thus, commands defined with keyboard Xmacros are convenient and efficient. The @kbd{C-x e} command, on the Xother hand, invokes the keyboard macro with no special treatment: Each Xcommand in the macro will record its own undo information and trail Xentry, and update stack buffer accordingly. If your macro uses features Xoutside of Calc's control to operate on the contents of the Calc stack Xbuffer, or if it includes Undo, Redo, or Last X commands, you must use X@kbd{C-x e} to make sure the buffer and undo list are up-to-date at all Xtimes. X XCalc extends the standard Emacs keyboard macros in several ways. XKeyboard macros can be used to create user-defined commands. Keyboard Xmacros can include conditional and iteration structures, somewhat Xanalogous to those provided by a traditional programmable calculator. X X@menu X* Naming Keyboard Macros:: X* Conditionals in Macros:: X* Loops in Macros:: X* Local Values in Macros:: X* Queries in Macros:: X@end menu X X@node Naming Keyboard Macros, Conditionals in Macros, Keyboard Macros, Keyboard Macros X@subsection Naming Keyboard Macros X X@kindex Z K X@pindex calc-user-define-kbd-macro XOnce you have defined a keyboard macro, you can bind it to a @kbd{z} Xkey sequence with the @kbd{Z K} (@code{calc-user-define-kbd-macro}) command. XThis command prompts first for a key, then for a command name. For Xexample, if you type @kbd{C-x ( n @key{TAB} n @key{TAB} C-x )} you will Xdefine a keyboard macro which negates the top two numbers on the stack X(@key{TAB} swaps the top two stack elements). Now you can type X@kbd{Z K n @key{RET}} to define this keyboard macro onto the @kbd{z n} key Xsequence. The default command name (if you answer the second prompt with Xjust the @key{RET} key as in this example) will be something like X@samp{calc-User-n}. The keyboard macro will now be available as both X@kbd{z n} and @kbd{M-x calc-User-n}. You can backspace and enter a more Xdescriptive command name if you wish.@refill X XMacros defined by @kbd{Z K} act like single commands; they are executed Xin the same way as by the @kbd{K} key. If you wish to define the macro Xas a standard no-frills Emacs macro (to be executed as if by @kbd{C-x e}), Xgive a negative prefix argument to @kbd{Z K}. X XOnce you have bound your keyboard macro to a key, you can use X@kbd{Z P} to register it permanently with Emacs. @xref{Creating User Keys}. X X@cindex Keyboard macros, editing XThe @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has Xbeen defined by a keyboard macro tries to use the @code{edit-kbd-macro} Xcommand to edit the macro. This command may be found in the X@file{macedit} package, a copy of which comes with Calc. If X@code{edit-kbd-macro} is not available, or if you give a negative Xnumeric prefix argument, @kbd{Z E} uses a variant of @code{calc-edit} Xwith the contents of the buffer being the keyboard macro in ``raw'' Xform. In either case, type @kbd{C-c C-c} to finish editing and update Xthe definition stored on the key, or, to cancel the edit, just kill the Xmacro-editing buffer with @kbd{C-x k}.@refill X X@node Conditionals in Macros, Loops in Macros, Naming Keyboard Macros, Keyboard Macros X@subsection Conditionals in Keyboard Macros X X@kindex Z [ X@kindex Z : X@kindex Z | X@kindex Z ] X@pindex calc-kbd-if X@pindex calc-kbd-else X@pindex calc-kbd-else-if X@pindex calc-kbd-end-if X@cindex Conditional structures XThe @kbd{Z [} (@code{calc-kbd-if}) and @kbd{Z ]} (@code{calc-kbd-end-if}) Xcommands allow you to put simple tests in a keyboard macro. When Calc Xsees the @kbd{Z [}, it pops an object from the stack and, if the object is Xa non-zero number, continues executing keystrokes. But if the object is Xzero, or if it is not a number, Calc skips ahead to the matching @kbd{Z ]} Xkeystroke. @xref{Logical Operations}, for a set of commands for performing Xtests which conveniently produce 1 for true and 0 for false. X XFor example, @kbd{@key{RET} 0 a < Z [ n Z ]} implements an absolute-value Xfunction as a keyboard macro. To program this macro, type @kbd{C-x (}, Xtype the above sequence of keystrokes, then type @kbd{C-x )}. Note that Xthe keystrokes will be executed while you are making the definition as Xwell as when you later re-execute the macro by typing @kbd{K}. Thus you Xshould make sure a suitable number is on the stack before defining the Xmacro to make sure you don't get a stack-underflow error during the Xdefinition process. X XThe above macro duplicates the number on the top of the stack, pushes Xzero and compares using @kbd{a <} (@code{calc-less-than}), then, if Xthe number was less than zero, executes @kbd{n} (@code{calc-change-sign}). XOtherwise, the change-sign command is skipped. X XConditionals can be nested arbitrarily. However, there should be exactly Xone @kbd{Z ]} for each @kbd{Z [} in a keyboard macro. X XThe @kbd{Z :} (@code{calc-kbd-else}) command allows you to choose between Xtwo keystroke sequences. The general format is @kbd{@var{cond} Z [ X@var{then-part} Z : @var{else-part} Z ]}. If @var{cond} is true X(i.e., if the top of stack contains a non-zero number after @var{cond} Xhas been executed), the @var{then-part} will be executed and the X@var{else-part} will be skipped. Otherwise, the @var{then-part} will Xbe skipped and the @var{else-part} will be executed. X XThe @kbd{Z |} (@code{calc-kbd-else-if}) command allows you to choose Xbetween any number of alternatives. For example, X@kbd{@var{cond1} Z [ @var{part1} Z : @var{cond2} Z | @var{part2} Z : X@var{part3} Z ]} will execute @var{part1} if @var{cond1} is true, Xotherwise it will execute @var{part2} if @var{cond2} is true, otherwise Xit will execute @var{part3}. X XMore precisely, @kbd{Z [} pops a number and conditionally skips to the Xnext matching @kbd{Z :} or @kbd{Z ]} key. @kbd{Z ]} has no effect when Xactually executed. @kbd{Z :} skips to the next matching @kbd{Z ]}. X@kbd{Z |} pops a number and conditionally skips to the next matching X@kbd{Z :} or @kbd{Z ]}; thus, @kbd{Z [} and @kbd{Z |} are functionally Xequivalent except that @kbd{Z [} participates in nesting but @kbd{Z |} Xdoes not. X X@kindex Z C-g XIf Calc gets stuck while skipping characters during the definition of a Xmacro, type @kbd{Z C-g} to cancel the definition. (Typing plain @kbd{C-g} Xactually adds a @kbd{C-g} keystroke to the macro.) X X@node Loops in Macros, Local Values in Macros, Conditionals in Macros, Keyboard Macros X@subsection Loops in Keyboard Macros X X@kindex Z < X@kindex Z > X@pindex calc-kbd-repeat X@pindex calc-kbd-end-repeat X@cindex Looping structures X@cindex Iterative structures XThe @kbd{Z <} (@code{calc-kbd-repeat}) and @kbd{Z >} X(@code{calc-kbd-end-repeat}) commands pop a number from the stack, Xwhich must be an integer, then repeat the keystrokes between the brackets Xthe specified number of times. If the integer is zero or negative, the Xbody is skipped altogether. For example, @kbd{1 @key{TAB} Z < 2 * Z >} Xcomputes two to a nonnegative integer power. First, we push 1 on the Xstack and then swap the integer argument back to the top. The @kbd{Z <} Xpops that argument leaving the 1 back on top of the stack. Then, we Xrepeat a multiply-by-two step however many times.@refill X XOnce again, the keyboard macro is executed as it is being entered. XIn this case it is especially important to set up reasonable initial Xconditions before making the definition: Suppose the integer 1000 just Xhappened to be sitting on the stack before we typed the above definition! XAnother approach is to enter a harmless dummy definition for the macro, Xthen go back and edit in the real one with a @kbd{Z E} command. X X@kindex Z / X@pindex calc-break XThe @kbd{Z /} (@code{calc-kbd-break}) command allows you to break out Xof a keyboard macro loop prematurely. It pops an object from the stack; Xif that object is true (a non-zero number), control jumps out of the Xinnermost enclosing @kbd{Z <} @dots{} @kbd{Z >} loop and continues Xafter the @kbd{Z >}. If the object is false, the @kbd{Z /} has no Xeffect. Thus the effect is similar to the C language's @code{break} Xstatement with an enclosing @code{if}.@refill X X@kindex Z ( X@kindex Z ) X@pindex calc-kbd-for X@pindex calc-kbd-end-for XThe @kbd{Z (} (@code{calc-kbd-for}) and @kbd{Z )} (@code{calc-kbd-end-for}) Xcommands are similar to @kbd{Z <} and @kbd{Z >}, except that they make the Xvalue of the counter available inside the loop. The general layout is X@kbd{@var{init} @var{final} Z ( @var{body} @var{step} Z )}. The @kbd{Z (} Xcommand pops initial and final values from the stack. It then creates Xa temporary internal counter and initializes it with the value @var{init}. XThe @kbd{Z (} command then repeatedly pushes the counter value onto the Xstack and executes @var{body} and @var{step}, adding @var{step} to the Xcounter each time until the loop finishes.@refill X X@cindex Summations (by keyboard macros) XBy default, the loop finishes when the counter becomes greater than (or Xless than) @var{final}, assuming @var{initial} is less than (greater Xthan) @var{final}. If @var{initial} is equal to @var{final}, the body Xexecutes exactly once. The body of the loop always executes at least Xonce. For example, @kbd{0 1 10 Z ( 2 ^ + 1 Z )} computes the sum of the Xsquares of the integers from 1 to 10, in steps of 1. X XIf you give a numeric prefix argument of 1 to @kbd{Z (}, the loop is Xforced to use upward-counting conventions. In this case, if @var{initial} Xis greater than @var{final} the body will not be executed at all. XNote that @var{step} may still be negative in this loop; the prefix Xargument merely constrains the loop-finished test. Likewise, a prefix Xargument of -1 forces downward-counting conventions. X X@kindex Z @{ X@kindex Z @} X@pindex calc-kbd-loop X@pindex calc-kbd-end-loop XThe @kbd{Z @{} (@code{calc-kbd-loop}) and @kbd{Z @}} X(@code{calc-kbd-end-loop}) commands are similar to @kbd{Z <} and X@kbd{Z >}, except that they do not pop a count from the stack---they Xeffectively create an infinite loop. Every @kbd{Z @{} @dots{} @kbd{Z @}} Xloop ought to include at least one @kbd{Z /} to make sure the loop Xdoesn't run forever. (If any error message occurs which causes Emacs Xto beep, the keyboard macro will also be halted; this is a standard Xfeature of Emacs. You can also generally press @kbd{C-g} to halt a Xrunning keyboard macro, although not all versions of Unix support Xthis feature.) X XCalc's conditional and looping constructs work by scanning the Xkeyboard macro for occurrences of character sequences like @samp{Z:} Xand @samp{Z>}. One side-effect of this is that if you use these Xconstructs you must be careful that these character pairs do not Xoccur by accident in other parts of the macros. Since Calc doesn't Xuse shift-Z for any purpose except as a prefix character, this is Xnot likely to be a problem. Another side-effect is that it will Xnot work to define your own custom key bindings for these commands. XOnly the standard shift-Z bindings will work correctly. X XThe conditional and looping constructs are not actually tied to Xkeyboard macros, but they are most often used in that context. XFor example, the keystrokes @kbd{10 Z < 23 @key{RET} Z >} push Xten copies of 23 onto the stack. This can be typed ``live'' just Xas easily as in a macro definition. X X@node Local Values in Macros, Queries in Macros, Loops in Macros, Keyboard Macros X@subsection Local Values in Macros X X@cindex Local variables X@cindex Restoring saved modes XKeyboard macros sometimes want to operate under known conditions Xwithout affecting surrounding conditions. For example, a keyboard Xmacro may wish to turn on Fraction Mode, or set a particular Xprecision, independent of the user's normal setting for those Xmodes. X X@kindex Z ` X@kindex Z ' X@pindex calc-kbd-push X@pindex calc-kbd-pop XMacros also sometimes need to use local variables. Assignments to Xlocal variables inside the macro should not affect any variables Xoutside the macro. The @kbd{Z `} (@code{calc-kbd-push}) and @kbd{Z '} X(@code{calc-kbd-pop}) commands give you both of these capabilities. X XWhen you type @kbd{Z `} (with a backquote or accent grave character), Xthe values of various mode settings are saved away. The ten ``quick'' Xvariables @code{var-0} through @code{var-9} are also saved. When Xyou type @kbd{Z '} (with an apostrophe), these values are restored. SHAR_EOF echo "End of part 17" echo "File calc.texinfo is continued in part 18" echo "18" > s2_seq_.tmp exit 0