Revision: miles@gnu.org--gnu-2004/emacs--cvs-trunk--0--patch-679
[bpt/emacs.git] / lisp / calc / calc.el
CommitLineData
7054901c 1;;; calc.el --- the GNU Emacs calculator
f269b73e 2
6a3ed064 3;; Copyright (C) 1990, 1991, 1992, 1993, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
f269b73e
CW
4
5;; Author: David Gillespie <daveg@synaptics.com>
32d5360a 6;; Maintainer: Jay Belanger <belanger@truman.edu>
f269b73e 7;; Keywords: convenience, extensions
7054901c 8;; Version: 2.02g
136211a9
EZ
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is distributed in the hope that it will be useful,
13;; but WITHOUT ANY WARRANTY. No author or distributor
14;; accepts responsibility to anyone for the consequences of using it
15;; or for whether it serves any particular purpose or works at all,
16;; unless he says so in writing. Refer to the GNU Emacs General Public
17;; License for full details.
18
19;; Everyone is granted permission to copy, modify and redistribute
20;; GNU Emacs, but only under the conditions described in the
21;; GNU Emacs General Public License. A copy of this license is
22;; supposed to have been given to you along with GNU Emacs so you
23;; can know your rights and responsibilities. It should be in a
24;; file named COPYING. Among other things, the copyright notice
25;; and this notice must be preserved on all copies.
26
f269b73e 27;;; Commentary:
136211a9 28
906bd0ef
CW
29;; Calc is split into many files. This file is the main entry point.
30;; This file includes autoload commands for various other basic Calc
31;; facilities. The more advanced features are based in calc-ext, which
32;; in turn contains autoloads for the rest of the Calc files. This
33;; odd set of interactions is designed to make Calc's loading time
34;; be as short as possible when only simple calculations are needed.
35
36;; Original author's address:
37;; Dave Gillespie, daveg@synaptics.com, uunet!synaptx!daveg.
38;; Synaptics, Inc., 2698 Orchard Parkway, San Jose, CA 95134.
39;;
40;; The old address daveg@csvax.cs.caltech.edu will continue to
41;; work for the foreseeable future.
42;;
43;; Bug reports and suggestions are always welcome! (Type M-x
44;; report-calc-bug to send them).
45
46;; All functions, macros, and Lisp variables defined here begin with one
47;; of the prefixes "math", "Math", or "calc", with the exceptions of
48;; "full-calc", "full-calc-keypad", "another-calc", "quick-calc",
49;; "report-calc-bug", and "defmath". User-accessible variables begin
50;; with "var-".
51
52;;; TODO:
53
54;; Fix rewrite mechanism to do less gratuitous rearrangement of terms.
55;; Implement a pattern-based "refers" predicate.
56;;
57;; Make it possible to Undo a selection command.
58;; Figure out how to allow selecting rows of matrices.
59;; If cursor was in selection before, move it after j n, j p, j L, etc.
60;; Consider reimplementing calc-delete-selection using rewrites.
61;;
62;; Implement line-breaking in non-flat compositions (is this desirable?).
63;; Implement matrix formatting with multi-line components.
64;;
65;; Have "Z R" define a user command based on a set of rewrite rules.
66;; Support "incf" and "decf" in defmath definitions.
67;; Have defmath generate calls to calc-binary-op or calc-unary-op.
68;; Make some way to define algebraic functions using keyboard macros.
69;;
70;; Allow calc-word-size=0 => Common Lisp-style signed bitwise arithmetic.
71;; Consider digamma function (and thus arb. prec. Euler's gamma constant).
72;; May as well make continued-fractions stuff available to the user.
73;;
74;; How about matrix eigenvalues, SVD, pseudo-inverse, etc.?
75;; Should cache matrix inverses as well as decompositions.
76;; If dividing by a non-square matrix, use least-squares automatically.
77;; Consider supporting matrix exponentials.
78;;
79;; Have ninteg detect and work around singularities at the endpoints.
80;; Use an adaptive subdivision algorithm for ninteg.
81;; Provide nsum and nprod to go along with ninteg.
82;;
83;; Handle TeX-mode parsing of \matrix{ ... } where ... contains braces.
84;; Support AmS-TeX's \{d,t,}frac, \{d,t,}binom notations.
85;; Format and parse sums and products in Eqn and Math modes.
86;;
87;; Get math-read-big-expr to read sums, products, etc.
88;; Change calc-grab-region to use math-read-big-expr.
89;; Have a way to define functions using := in Embedded Mode.
90;;
91;; Support polar plotting with GNUPLOT.
92;; Make a calc-graph-histogram function.
93;;
94;; Replace hokey formulas for complex functions with formulas designed
95;; to minimize roundoff while maintaining the proper branch cuts.
96;; Test accuracy of advanced math functions over whole complex plane.
97;; Extend Bessel functions to provide arbitrary precision.
98;; Extend advanced math functions to handle error forms and intervals.
99;; Provide a better implementation for math-sin-cos-raw.
100;; Provide a better implementation for math-hypot.
101;; Provide a better implementation for math-make-frac.
102;; Provide a better implementation for calcFunc-prfac.
103;; Provide a better implementation for calcFunc-factor.
104;;
105;; Provide more examples in the tutorial section of the manual.
106;; Cover in the tutorial: simplification modes, declarations,
107;; bitwise stuff, selections, matrix mapping, financial functions.
108;; Provide more Lisp programming examples in the manual.
109;; Finish the Internals section of the manual (and bring it up to date).
110;;
111;; Tim suggests adding spreadsheet-like features.
112;; Implement language modes for Gnuplot, Lisp, Ada, APL, ...?
113;;
114;; For atan series, if x > tan(pi/12) (about 0.268) reduce using the identity
115;; atan(x) = atan((x * sqrt(3) - 1) / (sqrt(3) + x)) + pi/6.
116;;
117;; A better integration algorithm:
118;; Use breadth-first instead of depth-first search, as follows:
119;; The integral cache allows unfinished integrals in symbolic notation
120;; on the righthand side. An entry with no unfinished integrals on the
121;; RHS is "complete"; references to it elsewhere are replaced by the
122;; integrated value. More than one cache entry for the same integral
123;; may exist, though if one becomes complete, the others may be deleted.
124;; The integrator works by using every applicable rule (such as
125;; substitution, parts, linearity, etc.) to generate possible righthand
126;; sides, all of which are entered into the cache. Now, as long as the
127;; target integral is not complete (and the time limit has not run out)
128;; choose an incomplete integral from the cache and, for every integral
129;; appearing in its RHS's, add those integrals to the cache using the
130;; same substitition, parts, etc. rules. The cache should be organized
131;; as a priority queue, choosing the "simplest" incomplete integral at
132;; each step, or choosing randomly among equally simple integrals.
133;; Simplicity equals small size, and few steps removed from the original
134;; target integral. Note that when the integrator finishes, incomplete
135;; integrals can be left in the cache, so the algorithm can start where
136;; it left off if another similar integral is later requested.
137;; Breadth-first search would avoid the nagging problem of, e.g., whether
138;; to use parts or substitution first, and which decomposition is best.
139;; All are tried, and any path that diverges will quickly be put on the
140;; back burner by the priority queue.
141;; Note: Probably a good idea to call math-simplify-extended before
142;; measuring a formula's simplicity.
143
144;; From: "Robert J. Chassell" <bob@rattlesnake.com>
145;; Subject: Re: fix for `Cannot open load file: calc-alg-3'
146;; To: walters@debian.org
147;; Date: Sat, 24 Nov 2001 21:44:21 +0000 (UTC)
a1506d29 148;;
906bd0ef 149;; Could you add logistic curve fitting to the current list?
a1506d29 150;;
906bd0ef
CW
151;; (I guess the key binding for a logistic curve would have to be `s'
152;; since a logistic curve is an `s' curve; both `l' and `L' are already
153;; taken for logarithms.)
a1506d29 154;;
906bd0ef 155;; Here is the current list for curve fitting;
a1506d29 156;;
906bd0ef
CW
157;; `1'
158;; Linear or multilinear. a + b x + c y + d z.
a1506d29 159;;
906bd0ef
CW
160;; `2-9'
161;; Polynomials. a + b x + c x^2 + d x^3.
a1506d29 162;;
906bd0ef
CW
163;; `e'
164;; Exponential. a exp(b x) exp(c y).
a1506d29 165;;
906bd0ef
CW
166;; `E'
167;; Base-10 exponential. a 10^(b x) 10^(c y).
a1506d29 168;;
906bd0ef
CW
169;; `x'
170;; Exponential (alternate notation). exp(a + b x + c y).
a1506d29 171;;
906bd0ef
CW
172;; `X'
173;; Base-10 exponential (alternate). 10^(a + b x + c y).
a1506d29 174;;
906bd0ef
CW
175;; `l'
176;; Logarithmic. a + b ln(x) + c ln(y).
a1506d29 177;;
906bd0ef
CW
178;; `L'
179;; Base-10 logarithmic. a + b log10(x) + c log10(y).
a1506d29 180;;
906bd0ef
CW
181;; `^'
182;; General exponential. a b^x c^y.
a1506d29 183;;
906bd0ef
CW
184;; `p'
185;; Power law. a x^b y^c.
a1506d29 186;;
906bd0ef
CW
187;; `q'
188;; Quadratic. a + b (x-c)^2 + d (x-e)^2.
a1506d29 189;;
906bd0ef
CW
190;; `g'
191;; Gaussian. (a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2).
a1506d29
JB
192;;
193;;
906bd0ef
CW
194;; Logistic curves are used a great deal in ecology, and in predicting
195;; human actions, such as use of different kinds of energy in a country
196;; (wood, coal, oil, natural gas, etc.) or the number of scientific
197;; papers a person publishes, or the number of movies made.
a1506d29 198;;
906bd0ef
CW
199;; (The less information on which to base the curve, the higher the error
200;; rate. Theodore Modis ran some Monte Carlo simulations and produced
201;; what may be useful set of confidence levels for different amounts of
202;; initial information.)
136211a9 203
f269b73e 204;;; Code:
136211a9 205
136211a9 206(provide 'calc)
91e51f9a 207(require 'calc-macs)
136211a9 208
136211a9
EZ
209;;; The "###autoload" comment will be used by Emacs version 19 for
210;;; maintaining the loaddefs.el file automatically.
211
212;;;###autoload
213(defvar calc-info-filename "calc.info"
214 "*File name in which to look for the Calculator's Info documentation.")
215
216;;;###autoload
f269b73e
CW
217(defvar calc-settings-file user-init-file
218 "*File in which to record permanent settings; default is `user-init-file'.")
136211a9
EZ
219
220;;;###autoload
221(defvar calc-autoload-directory nil
222 "Name of directory from which additional \".elc\" files for Calc should be
223loaded. Should include a trailing \"/\".
224If nil, use original installation directory.
225This can safely be nil as long as the Calc files are on the load-path.")
226
227;;;###autoload
228(defvar calc-gnuplot-name "gnuplot"
229 "*Name of GNUPLOT program, for calc-graph features.")
230
231;;;###autoload
232(defvar calc-gnuplot-plot-command nil
233 "*Name of command for displaying GNUPLOT output; %s = file name to print.")
234
235;;;###autoload
236(defvar calc-gnuplot-print-command "lp %s"
237 "*Name of command for printing GNUPLOT output; %s = file name to print.")
238
32d5360a 239(defvar calc-bug-address "belanger@truman.edu"
730576f3 240 "Address of the author of Calc, for use by `report-calc-bug'.")
136211a9 241
730576f3
CW
242(defvar calc-scan-for-dels t
243 "If t, scan keymaps to find all DEL-like keys.
244if nil, only DEL itself is mapped to calc-pop.")
136211a9 245
136211a9
EZ
246(defvar calc-extensions-loaded nil)
247
730576f3
CW
248(defvar calc-stack '((top-of-stack 1 nil))
249 "Calculator stack.
250Entries are 3-lists: Formula, Height (in lines), Selection (or nil).")
136211a9 251
1501f4f6
MB
252(defvar calc-show-banner t
253 "*If non-nil, show a friendly greeting above the stack.")
254
730576f3
CW
255(defvar calc-stack-top 1
256 "Index into `calc-stack' of \"top\" of stack.
257This is 1 unless `calc-truncate-stack' has been used.")
136211a9 258
7b2cda38
JB
259(defvar calc-display-sci-high 0
260 "Floating-point numbers with this positive exponent or higher above the
261current precision are displayed in scientific notation in calc-mode.")
262
263(defvar calc-display-sci-low -3
264 "Floating-point numbers with this negative exponent or lower are displayed
265scientific notation in calc-mode.")
266
267(defvar calc-other-modes nil
268 "List of used-defined strings to append to Calculator mode line.")
136211a9 269
7b2cda38
JB
270(defvar calc-Y-help-msgs nil
271 "List of strings for Y prefix help.")
136211a9 272
7b2cda38
JB
273(defvar calc-loaded-settings-file nil
274 "t if `calc-settings-file' has been loaded yet.")
136211a9 275
7b2cda38
JB
276(defvar calc-always-load-extensions)
277(defvar calc-line-numbering)
278(defvar calc-line-breaking)
279(defvar calc-display-just)
280(defvar calc-display-origin)
281(defvar calc-number-radix)
282(defvar calc-leading-zeros)
283(defvar calc-group-digits)
284(defvar calc-group-char)
285(defvar calc-point-char)
286(defvar calc-frac-format)
287(defvar calc-prefer-frac)
288(defvar calc-hms-format)
289(defvar calc-date-format)
290(defvar calc-float-format)
291(defvar calc-full-float-format)
292(defvar calc-complex-format)
293(defvar calc-complex-mode)
294(defvar calc-infinite-mode)
295(defvar calc-display-strings)
296(defvar calc-matrix-just)
297(defvar calc-break-vectors)
298(defvar calc-full-vectors)
299(defvar calc-full-trail-vectors)
300(defvar calc-vector-commas)
301(defvar calc-vector-brackets)
302(defvar calc-matrix-brackets)
303(defvar calc-language)
304(defvar calc-language-option)
305(defvar calc-left-label)
306(defvar calc-right-label)
307(defvar calc-word-size)
308(defvar calc-previous-modulo)
309(defvar calc-simplify-mode)
310(defvar calc-auto-recompute)
311(defvar calc-display-raw)
312(defvar calc-internal-prec)
313(defvar calc-angle-mode)
314(defvar calc-algebraic-mode)
315(defvar calc-incomplete-algebraic-mode)
316(defvar calc-symbolic-mode)
317(defvar calc-matrix-mode)
318(defvar calc-shift-prefix)
319(defvar calc-window-height)
320(defvar calc-display-trail)
321(defvar calc-show-selections)
322(defvar calc-use-selections)
323(defvar calc-assoc-selections)
324(defvar calc-display-working-message)
325(defvar calc-auto-why)
326(defvar calc-timing)
327(defvar calc-mode-save-mode)
328(defvar calc-standard-date-formats)
329(defvar calc-autorange-units)
330(defvar calc-was-keypad-mode)
331(defvar calc-full-mode)
332(defvar calc-user-parse-tables)
333(defvar calc-gnuplot-default-device)
334(defvar calc-gnuplot-default-output)
335(defvar calc-gnuplot-print-device)
336(defvar calc-gnuplot-print-output)
337(defvar calc-gnuplot-geometry)
338(defvar calc-graph-default-resolution)
339(defvar calc-graph-default-resolution-3d)
340(defvar calc-invocation-macro)
341(defvar calc-show-banner)
342
343(defconst calc-mode-var-list '(
344 (calc-always-load-extensions nil
345 "If non-nil, load the calc-ext module automatically when calc is loaded.")
346
347 (calc-line-numbering t
348 "If non-nil, display line numbers in Calculator stack.")
349
350 (calc-line-breaking t
351 "If non-nil, break long values across multiple lines in Calculator stack.")
352
353 (calc-display-just nil
354 "If nil, stack display is left-justified.
730576f3
CW
355If `right', stack display is right-justified.
356If `center', stack display is centered.")
136211a9 357
7b2cda38
JB
358 (calc-display-origin nil
359 "Horizontal origin of displayed stack entries.
730576f3
CW
360In left-justified mode, this is effectively indentation. (Default 0).
361In right-justified mode, this is effectively window width.
362In centered mode, center of stack entry is placed here.")
363
7b2cda38
JB
364 (calc-number-radix 10
365 "Radix for entry and display of numbers in calc-mode, 2-36.")
730576f3 366
7b2cda38
JB
367 (calc-leading-zeros nil
368 "If non-nil, leading zeros are provided to pad integers to calc-word-size.")
730576f3 369
7b2cda38
JB
370 (calc-group-digits nil
371 "If non-nil, group digits in large displayed integers by inserting spaces.
730576f3
CW
372If an integer, group that many digits at a time.
373If t, use 4 for binary and hex, 3 otherwise.")
374
7b2cda38
JB
375 (calc-group-char ","
376 "The character (in the form of a string) to be used for grouping digits.
730576f3
CW
377This is used only when calc-group-digits mode is on.")
378
7b2cda38
JB
379 (calc-point-char "."
380 "The character (in the form of a string) to be used as a decimal point.")
381
382 (calc-frac-format (":" nil)
383 "Format of displayed fractions; a string of one or two of \":\" or \"/\".")
730576f3 384
7b2cda38
JB
385 (calc-prefer-frac nil
386 "If non-nil, prefer fractional over floating-point results.")
730576f3 387
7b2cda38
JB
388 (calc-hms-format "%s@ %s' %s\""
389 "Format of displayed hours-minutes-seconds angles, a format string.
730576f3
CW
390String must contain three %s marks for hours, minutes, seconds respectively.")
391
7b2cda38
JB
392 (calc-date-format ((H ":" mm C SS pp " ")
393 Www " " Mmm " " D ", " YYYY)
394 "Format of displayed date forms.")
730576f3 395
7b2cda38
JB
396 (calc-float-format (float 0)
397 "Format to use for display of floating-point numbers in calc-mode.
730576f3
CW
398Must be a list of one of the following forms:
399 (float 0) Floating point format, display full precision.
400 (float N) N > 0: Floating point format, at most N significant figures.
401 (float -N) -N < 0: Floating point format, calc-internal-prec - N figs.
402 (fix N) N >= 0: Fixed point format, N places after decimal point.
403 (sci 0) Scientific notation, full precision.
404 (sci N) N > 0: Scientific notation, N significant figures.
405 (sci -N) -N < 0: Scientific notation, calc-internal-prec - N figs.
406 (eng 0) Engineering notation, full precision.
407 (eng N) N > 0: Engineering notation, N significant figures.
408 (eng -N) -N < 0: Engineering notation, calc-internal-prec - N figs.")
409
7b2cda38
JB
410 (calc-full-float-format (float 0)
411 "Format to use when full precision must be displayed.")
730576f3 412
7b2cda38
JB
413 (calc-complex-format nil
414 "Format to use for display of complex numbers in calc-mode. Must be one of:
730576f3
CW
415 nil Use (x, y) form.
416 i Use x + yi form.
417 j Use x + yj form.")
418
7b2cda38
JB
419 (calc-complex-mode cplx
420 "Preferred form, either `cplx' or `polar', for complex numbers.")
136211a9 421
7b2cda38
JB
422 (calc-infinite-mode nil
423 "If nil, 1 / 0 is left unsimplified.
730576f3
CW
424If 0, 1 / 0 is changed to inf (zeros are considered positive).
425Otherwise, 1 / 0 is changed to uinf (undirected infinity).")
426
7b2cda38
JB
427 (calc-display-strings nil
428 "If non-nil, display vectors of byte-sized integers as strings.")
136211a9 429
cde090ee 430 (calc-matrix-just center
7b2cda38 431 "If nil, vector elements are left-justified.
730576f3
CW
432If `right', vector elements are right-justified.
433If `center', vector elements are centered.")
434
7b2cda38
JB
435 (calc-break-vectors nil
436 "If non-nil, display vectors one element per line.")
136211a9 437
7b2cda38
JB
438 (calc-full-vectors t
439 "If non-nil, display long vectors in full. If nil, use abbreviated form.")
730576f3 440
7b2cda38
JB
441 (calc-full-trail-vectors t
442 "If non-nil, display long vectors in full in the trail.")
136211a9 443
7b2cda38
JB
444 (calc-vector-commas ","
445 "If non-nil, separate elements of displayed vectors with this string.")
730576f3 446
7b2cda38
JB
447 (calc-vector-brackets "[]"
448 "If non-nil, surround displayed vectors with these characters.")
730576f3 449
def71c18 450 (calc-matrix-brackets (R O)
7b2cda38 451 "A list of code-letter symbols that control \"big\" matrix display.
730576f3
CW
452If `R' is present, display inner brackets for matrices.
453If `O' is present, display outer brackets for matrices (above/below).
454If `C' is present, display outer brackets for matrices (centered).")
455
7b2cda38
JB
456 (calc-language nil
457 "Language or format for entry and display of stack values. Must be one of:
730576f3
CW
458 nil Use standard Calc notation.
459 flat Use standard Calc notation, one-line format.
460 big Display formulas in 2-d notation (enter w/std notation).
461 unform Use unformatted display: add(a, mul(b,c)).
462 c Use C language notation.
463 pascal Use Pascal language notation.
464 fortran Use Fortran language notation.
465 tex Use TeX notation.
466 eqn Use eqn notation.
467 math Use Mathematica(tm) notation.
468 maple Use Maple notation.")
136211a9 469
7b2cda38
JB
470 (calc-language-option nil
471 "Numeric prefix argument for the command that set `calc-language'.")
136211a9 472
7b2cda38
JB
473 (calc-left-label ""
474 "Label to display at left of formula.")
136211a9 475
7b2cda38
JB
476 (calc-right-label ""
477 "Label to display at right of formula.")
136211a9 478
7b2cda38
JB
479 (calc-word-size 32
480 "Minimum number of bits per word, if any, for binary operations in calc-mode.")
136211a9 481
7b2cda38
JB
482 (calc-previous-modulo nil
483 "Most recently used value of M in a modulo form.")
136211a9 484
7b2cda38
JB
485 (calc-simplify-mode nil
486 "Type of simplification applied to results.
730576f3
CW
487If `none', results are not simplified when pushed on the stack.
488If `num', functions are simplified only when args are constant.
489If nil, only fast simplifications are applied.
490If `binary', `math-clip' is applied if appropriate.
491If `alg', `math-simplify' is applied.
492If `ext', `math-simplify-extended' is applied.
493If `units', `math-simplify-units' is applied.")
136211a9 494
7b2cda38
JB
495 (calc-auto-recompute t
496 "If non-nil, recompute evalto's automatically when necessary.")
136211a9 497
7b2cda38
JB
498 (calc-display-raw nil
499 "If non-nil, display shows unformatted Lisp exprs. (For debugging)")
136211a9 500
7b2cda38
JB
501 (calc-internal-prec 12
502 "Number of digits of internal precision for calc-mode calculations.")
136211a9 503
7b2cda38
JB
504 (calc-angle-mode deg
505 "If deg, angles are in degrees; if rad, angles are in radians.
730576f3 506If hms, angles are in degrees-minutes-seconds.")
136211a9 507
7b2cda38
JB
508 (calc-algebraic-mode nil
509 "If non-nil, numeric entry accepts whole algebraic expressions.
730576f3 510If nil, algebraic expressions must be preceded by \"'\".")
136211a9 511
7b2cda38
JB
512 (calc-incomplete-algebraic-mode nil
513 "Like calc-algebraic-mode except only affects ( and [ keys.")
730576f3 514
7b2cda38
JB
515 (calc-symbolic-mode nil
516 "If non-nil, inexact numeric computations like sqrt(2) are postponed.
730576f3
CW
517If nil, computations on numbers always yield numbers where possible.")
518
7b2cda38
JB
519 (calc-matrix-mode nil
520 "If `matrix', variables are assumed to be matrix-valued.
730576f3
CW
521If a number, variables are assumed to be NxN matrices.
522If `scalar', variables are assumed to be scalar-valued.
523If nil, symbolic math routines make no assumptions about variables.")
524
7b2cda38
JB
525 (calc-shift-prefix nil
526 "If non-nil, shifted letter keys are prefix keys rather than normal meanings.")
730576f3 527
7b2cda38
JB
528 (calc-window-height 7
529 "Initial height of Calculator window.")
730576f3 530
7b2cda38
JB
531 (calc-display-trail t
532 "If non-nil, M-x calc creates a window to display Calculator trail.")
730576f3 533
7b2cda38
JB
534 (calc-show-selections t
535 "If non-nil, selected sub-formulas are shown by obscuring rest of formula.
730576f3
CW
536If nil, selected sub-formulas are highlighted by obscuring the sub-formulas.")
537
7b2cda38
JB
538 (calc-use-selections t
539 "If non-nil, commands operate only on selected portions of formulas.
730576f3
CW
540If nil, selections displayed but ignored.")
541
7b2cda38
JB
542 (calc-assoc-selections t
543 "If non-nil, selection hides deep structure of associative formulas.")
730576f3 544
cde090ee 545 (calc-display-working-message lots
7b2cda38 546 "If non-nil, display \"Working...\" for potentially slow Calculator commands.")
730576f3 547
cde090ee 548 (calc-auto-why maybe
7b2cda38 549 "If non-nil, automatically execute a \"why\" command to explain odd results.")
730576f3 550
7b2cda38
JB
551 (calc-timing nil
552 "If non-nil, display timing information on each slow command.")
730576f3 553
7b2cda38 554 (calc-mode-save-mode local)
730576f3 555
7b2cda38 556 (calc-standard-date-formats
cde090ee
JB
557 ("N"
558 "<H:mm:SSpp >Www Mmm D, YYYY"
559 "D Mmm YYYY<, h:mm:SS>"
560 "Www Mmm BD< hh:mm:ss> YYYY"
561 "M/D/Y< H:mm:SSpp>"
562 "D.M.Y< h:mm:SS>"
563 "M-D-Y< H:mm:SSpp>"
564 "D-M-Y< h:mm:SS>"
565 "j<, h:mm:SS>"
566 "YYddd< hh:mm:ss>"))
730576f3 567
7b2cda38
JB
568 (calc-autorange-units nil)
569
570 (calc-was-keypad-mode nil)
571
572 (calc-full-mode nil)
730576f3 573
7b2cda38 574 (calc-user-parse-tables nil)
730576f3 575
7b2cda38 576 (calc-gnuplot-default-device "default")
730576f3 577
7b2cda38
JB
578 (calc-gnuplot-default-output "STDOUT")
579
580 (calc-gnuplot-print-device "postscript")
581
582 (calc-gnuplot-print-output "auto")
583
584 (calc-gnuplot-geometry nil)
585
586 (calc-graph-default-resolution 15)
730576f3 587
7b2cda38
JB
588 (calc-graph-default-resolution-3d 5)
589
590 (calc-invocation-macro nil)
730576f3 591
7b2cda38
JB
592 (calc-show-banner t))
593 "List of variables (and default values) used in customizing GNU Calc.")
730576f3 594
7b2cda38
JB
595(mapcar (function (lambda (v)
596 (or (boundp (car v))
597 (set (car v) (nth 1 v)))
598 (if (nth 2 v)
599 (put (car v) 'variable-documentation (nth 2 v)))))
600 calc-mode-var-list)
136211a9
EZ
601
602(defconst calc-local-var-list '(calc-stack
603 calc-stack-top
604 calc-undo-list
605 calc-redo-list
606 calc-always-load-extensions
607 calc-mode-save-mode
608 calc-display-raw
609 calc-line-numbering
610 calc-line-breaking
611 calc-display-just
612 calc-display-origin
613 calc-left-label
614 calc-right-label
615 calc-auto-why
616 calc-algebraic-mode
617 calc-incomplete-algebraic-mode
618 calc-symbolic-mode
619 calc-matrix-mode
620 calc-inverse-flag
621 calc-hyperbolic-flag
622 calc-keep-args-flag
623 calc-angle-mode
624 calc-number-radix
625 calc-leading-zeros
626 calc-group-digits
627 calc-group-char
628 calc-point-char
629 calc-frac-format
630 calc-prefer-frac
631 calc-hms-format
632 calc-date-format
633 calc-standard-date-formats
634 calc-float-format
635 calc-full-float-format
636 calc-complex-format
637 calc-matrix-just
638 calc-full-vectors
639 calc-full-trail-vectors
640 calc-break-vectors
641 calc-vector-commas
642 calc-vector-brackets
643 calc-matrix-brackets
644 calc-complex-mode
645 calc-infinite-mode
646 calc-display-strings
647 calc-simplify-mode
648 calc-auto-recompute
649 calc-autorange-units
650 calc-show-plain
651 calc-show-selections
652 calc-use-selections
653 calc-assoc-selections
654 calc-word-size
655 calc-internal-prec))
656
657
730576f3 658;; Verify that Calc is running on the right kind of system.
730576f3 659(defvar calc-emacs-type-lucid (not (not (string-match "Lucid" emacs-version))))
136211a9 660
730576f3
CW
661;; Set up the standard keystroke (M-#) to run the Calculator, if that key
662;; has not yet been bound to anything. For best results, the user should
663;; do this before Calc is even loaded, so that M-# can auto-load Calc.
664(or (global-key-binding "\e#") (global-set-key "\e#" 'calc-dispatch))
136211a9 665
730576f3
CW
666;; Set up the autoloading linkage.
667(let ((name (and (fboundp 'calc-dispatch)
136211a9
EZ
668 (eq (car-safe (symbol-function 'calc-dispatch)) 'autoload)
669 (nth 1 (symbol-function 'calc-dispatch))))
670 (p load-path))
671
672 ;; If Calc files exist on the load-path, we're all set.
673 (while (and p (not (file-exists-p
674 (expand-file-name "calc-misc.elc" (car p)))))
675 (setq p (cdr p)))
676 (or p
677
678 ;; If Calc is autoloaded using a path name, look there for Calc files.
679 ;; This works for both relative ("calc/calc.elc") and absolute paths.
680 (and name (file-name-directory name)
681 (let ((p2 load-path)
682 (name2 (concat (file-name-directory name)
683 "calc-misc.elc")))
684 (while (and p2 (not (file-exists-p
685 (expand-file-name name2 (car p2)))))
686 (setq p2 (cdr p2)))
cd012309
CW
687 (when p2
688 (setq load-path (nconc load-path
689 (list
690 (directory-file-name
691 (file-name-directory
692 (expand-file-name
693 name (car p2))))))))))
136211a9
EZ
694
695 ;; If calc-autoload-directory is given, use that (and hope it works!).
696 (and calc-autoload-directory
697 (not (equal calc-autoload-directory ""))
698 (setq load-path (nconc load-path
699 (list (directory-file-name
700 calc-autoload-directory)))))))
701
730576f3
CW
702;; The following modes use specially-formatted data.
703(put 'calc-mode 'mode-class 'special)
704(put 'calc-trail-mode 'mode-class 'special)
a1506d29 705
730576f3
CW
706;; Define "inexact-result" as an e-lisp error symbol.
707(put 'inexact-result 'error-conditions '(error inexact-result calc-error))
708(put 'inexact-result 'error-message "Calc internal error (inexact-result)")
a1506d29 709
730576f3
CW
710;; Define "math-overflow" and "math-underflow" as e-lisp error symbols.
711(put 'math-overflow 'error-conditions '(error math-overflow calc-error))
712(put 'math-overflow 'error-message "Floating-point overflow occurred")
713(put 'math-underflow 'error-conditions '(error math-underflow calc-error))
714(put 'math-underflow 'error-message "Floating-point underflow occurred")
a1506d29 715
730576f3
CW
716(defconst calc-version "2.02g")
717(defconst calc-version-date "Mon Nov 19 2001")
718(defvar calc-trail-pointer nil) ; "Current" entry in trail buffer.
719(defvar calc-trail-overlay nil) ; Value of overlay-arrow-string.
720(defvar calc-undo-list nil) ; List of previous operations for undo.
721(defvar calc-redo-list nil) ; List of recent undo operations.
722(defvar calc-main-buffer nil) ; Pointer to Calculator buffer.
723(defvar calc-trail-buffer nil) ; Pointer to Calc Trail buffer.
724(defvar calc-why nil) ; Explanations of most recent errors.
725(defvar calc-next-why nil)
7b2cda38
JB
726(defvar calc-inverse-flag nil
727 "If non-nil, next operation is Inverse.")
728(defvar calc-hyperbolic-flag nil
729 "If non-nil, next operation is Hyperbolic.")
730(defvar calc-keep-args-flag nil
731 "If non-nil, next operation should not remove its arguments from stack.")
732(defvar calc-function-open "("
733 "Open-parenthesis string for function call notation.")
734(defvar calc-function-close ")"
735 "Close-parenthesis string for function call notation.")
736(defvar calc-language-output-filter nil
737 "Function through which to pass strings after formatting.")
738(defvar calc-language-input-filter nil
739 "Function through which to pass strings before parsing.")
740(defvar calc-radix-formatter nil
741 "Formatting function used for non-decimal numbers.")
742
730576f3
CW
743(defvar calc-last-kill nil) ; Last number killed in calc-mode.
744(defvar calc-previous-alg-entry nil) ; Previous algebraic entry.
745(defvar calc-dollar-values nil) ; Values to be used for '$'.
746(defvar calc-dollar-used nil) ; Highest order of '$' that occurred.
747(defvar calc-hashes-used nil) ; Highest order of '#' that occurred.
748(defvar calc-quick-prev-results nil) ; Previous results from Quick Calc.
749(defvar calc-said-hello nil) ; Has welcome message been said yet?
750(defvar calc-executing-macro nil) ; Kbd macro executing from "K" key.
751(defvar calc-any-selections nil) ; Nil means no selections present.
752(defvar calc-help-phase 0) ; Count of consecutive "?" keystrokes.
753(defvar calc-full-help-flag nil) ; Executing calc-full-help?
754(defvar calc-refresh-count 0) ; Count of calc-refresh calls.
755(defvar calc-display-dirty nil)
756(defvar calc-prepared-composition nil)
757(defvar calc-selection-cache-default-entry nil)
758(defvar calc-embedded-info nil)
759(defvar calc-embedded-active nil)
760(defvar calc-standalone-flag nil)
761(defvar var-EvalRules nil)
762(defvar math-eval-rules-cache-tag t)
763(defvar math-radix-explicit-format t)
764(defvar math-expr-function-mapping nil)
765(defvar math-expr-variable-mapping nil)
766(defvar math-read-expr-quotes nil)
767(defvar math-working-step nil)
768(defvar math-working-step-2 nil)
769(defvar var-i '(special-const (math-imaginary 1)))
770(defvar var-pi '(special-const (math-pi)))
771(defvar var-e '(special-const (math-e)))
772(defvar var-phi '(special-const (math-phi)))
773(defvar var-gamma '(special-const (math-gamma-const)))
774(defvar var-Modes '(special-const (math-get-modes-vec)))
775
776(mapcar (lambda (v) (or (boundp v) (set v nil)))
136211a9
EZ
777 calc-local-var-list)
778
730576f3
CW
779(defvar calc-mode-map
780 (let ((map (make-keymap)))
781 (suppress-keymap map t)
782 (define-key map "+" 'calc-plus)
783 (define-key map "-" 'calc-minus)
784 (define-key map "*" 'calc-times)
785 (define-key map "/" 'calc-divide)
786 (define-key map "%" 'calc-mod)
787 (define-key map "&" 'calc-inv)
788 (define-key map "^" 'calc-power)
789 (define-key map "\M-%" 'calc-percent)
790 (define-key map "e" 'calcDigit-start)
791 (define-key map "i" 'calc-info)
792 (define-key map "n" 'calc-change-sign)
793 (define-key map "q" 'calc-quit)
794 (define-key map "Y" 'nil)
795 (define-key map "Y?" 'calc-shift-Y-prefix-help)
796 (define-key map "?" 'calc-help)
797 (define-key map " " 'calc-enter)
798 (define-key map "'" 'calc-algebraic-entry)
799 (define-key map "$" 'calc-auto-algebraic-entry)
800 (define-key map "\"" 'calc-auto-algebraic-entry)
801 (define-key map "\t" 'calc-roll-down)
802 (define-key map "\M-\t" 'calc-roll-up)
803 (define-key map "\C-m" 'calc-enter)
804 (define-key map "\M-\C-m" 'calc-last-args-stub)
805 (define-key map "\C-j" 'calc-over)
806
6a3ed064
SM
807 (mapc (lambda (x) (define-key map (char-to-string x) 'undefined))
808 "lOW")
809 (mapc (lambda (x) (define-key map (char-to-string x) 'calc-missing-key))
810 (concat "ABCDEFGHIJKLMNPQRSTUVXZabcdfghjkmoprstuvwxyz"
811 ":\\|!()[]<>{},;=~`\C-k\M-k\C-w\M-w\C-y\C-_"))
812 (mapc (lambda (x) (define-key map (char-to-string x) 'calcDigit-start))
813 "_0123456789.#@")
730576f3 814 map))
136211a9 815
730576f3
CW
816(defvar calc-digit-map
817 (let ((map (make-keymap)))
136211a9
EZ
818 (if calc-emacs-type-lucid
819 (map-keymap (function
820 (lambda (keys bind)
730576f3 821 (define-key map keys
136211a9
EZ
822 (if (eq bind 'undefined)
823 'undefined 'calcDigit-nondigit))))
824 calc-mode-map)
cecd4c20
JB
825 (let ((cmap (nth 1 calc-mode-map))
826 (dmap (nth 1 map))
136211a9
EZ
827 (i 0))
828 (while (< i 128)
829 (aset dmap i
830 (if (eq (aref cmap i) 'undefined)
831 'undefined 'calcDigit-nondigit))
832 (setq i (1+ i)))))
730576f3 833 (mapcar (lambda (x) (define-key map (char-to-string x) 'calcDigit-key))
136211a9 834 "_0123456789.e+-:n#@oh'\"mspM")
730576f3 835 (mapcar (lambda (x) (define-key map (char-to-string x) 'calcDigit-letter))
136211a9 836 "abcdfgijklqrtuvwxyzABCDEFGHIJKLNOPQRSTUVWXYZ")
730576f3
CW
837 (define-key map "'" 'calcDigit-algebraic)
838 (define-key map "`" 'calcDigit-edit)
839 (define-key map "\C-g" 'abort-recursive-edit)
840 map))
136211a9 841
730576f3 842(mapcar (lambda (x)
136211a9
EZ
843 (condition-case err
844 (progn
845 (define-key calc-digit-map x 'calcDigit-backspace)
846 (define-key calc-mode-map x 'calc-pop)
847 (define-key calc-mode-map
848 (if (vectorp x)
849 (if calc-emacs-type-lucid
850 (if (= (length x) 1)
851 (vector (if (consp (aref x 0))
852 (cons 'meta (aref x 0))
853 (list 'meta (aref x 0))))
854 "\e\C-d")
855 (vconcat "\e" x))
856 (concat "\e" x))
857 'calc-pop-above))
730576f3 858 (error nil)))
136211a9
EZ
859 (if calc-scan-for-dels
860 (append (where-is-internal 'delete-backward-char global-map)
861 (where-is-internal 'backward-delete-char global-map)
862 '("\C-d"))
863 '("\177" "\C-d")))
864
730576f3
CW
865(defvar calc-dispatch-map
866 (let ((map (make-keymap)))
867 (mapcar (lambda (x)
868 (define-key map (char-to-string (car x)) (cdr x))
cd012309
CW
869 (when (string-match "abcdefhijklnopqrstuwxyz"
870 (char-to-string (car x)))
730576f3
CW
871 (define-key map (char-to-string (- (car x) ?a -1)) (cdr x)))
872 (define-key map (format "\e%c" (car x)) (cdr x)))
136211a9
EZ
873 '( ( ?a . calc-embedded-activate )
874 ( ?b . calc-big-or-small )
875 ( ?c . calc )
876 ( ?d . calc-embedded-duplicate )
877 ( ?e . calc-embedded )
878 ( ?f . calc-embedded-new-formula )
879 ( ?g . calc-grab-region )
880 ( ?h . calc-dispatch-help )
881 ( ?i . calc-info )
882 ( ?j . calc-embedded-select )
883 ( ?k . calc-keypad )
884 ( ?l . calc-load-everything )
885 ( ?m . read-kbd-macro )
886 ( ?n . calc-embedded-next )
887 ( ?o . calc-other-window )
888 ( ?p . calc-embedded-previous )
889 ( ?q . quick-calc )
890 ( ?r . calc-grab-rectangle )
891 ( ?s . calc-info-summary )
892 ( ?t . calc-tutorial )
893 ( ?u . calc-embedded-update-formula )
894 ( ?w . calc-embedded-word )
895 ( ?x . calc-quit )
896 ( ?y . calc-copy-to-buffer )
897 ( ?z . calc-user-invocation )
898 ( ?= . calc-embedded-update-formula )
899 ( ?\' . calc-embedded-new-formula )
900 ( ?\` . calc-embedded-edit )
901 ( ?: . calc-grab-sum-down )
902 ( ?_ . calc-grab-sum-across )
903 ( ?0 . calc-reset )
904 ( ?# . calc-same-interface )
80f952a2
CW
905 ( ?? . calc-dispatch-help ) ))
906 map))
136211a9 907
730576f3
CW
908(autoload 'calc-extensions "calc-ext")
909(autoload 'calc-need-macros "calc-macs")
136211a9
EZ
910
911;;;; (Autoloads here)
730576f3
CW
912(mapcar
913 (lambda (x) (dolist (func (cdr x)) (autoload func (car x))))
136211a9
EZ
914 '(
915
916 ("calc-aent" calc-Need-calc-aent calc-alg-digit-entry calc-alg-entry
730576f3
CW
917 calc-check-user-syntax calc-do-alg-entry calc-do-calc-eval
918 calc-do-quick-calc calc-match-user-syntax math-build-parse-table
919 math-find-user-tokens math-read-expr-list math-read-exprs math-read-if
920 math-read-token math-remove-dashes)
136211a9 921
a1506d29 922 ("calc-misc" calc-Need-calc-misc
730576f3
CW
923 calc-do-handle-whys calc-do-refresh calc-num-prefix-name
924 calc-record-list calc-record-why calc-report-bug calc-roll-down-stack
925 calc-roll-up-stack calc-temp-minibuffer-message calcFunc-floor
926 calcFunc-inv calcFunc-trunc math-concat math-constp math-div2
927 math-div2-bignum math-do-working math-evenp math-fixnatnump
928 math-fixnump math-floor math-imod math-ipow math-looks-negp math-mod
929 math-negp math-posp math-pow math-read-radix-digit math-reject-arg
930 math-trunc math-zerop)))
931
932(mapcar
933 (lambda (x) (dolist (cmd (cdr x)) (autoload cmd (car x) nil t)))
136211a9
EZ
934 '(
935
936 ("calc-aent" calc-algebraic-entry calc-auto-algebraic-entry
730576f3 937 calcDigit-algebraic calcDigit-edit)
136211a9
EZ
938
939 ("calc-misc" another-calc calc-big-or-small calc-dispatch-help
9d3c486a
JB
940 calc-help calc-info calc-info-goto-node calc-info-summary calc-inv
941 calc-last-args-stub
730576f3
CW
942 calc-missing-key calc-mod calc-other-window calc-over calc-percent
943 calc-pop-above calc-power calc-roll-down calc-roll-up
944 calc-shift-Y-prefix-help calc-tutorial calcDigit-letter
945 report-calc-bug)))
136211a9
EZ
946
947
948;;;###autoload (global-set-key "\e#" 'calc-dispatch)
949
950;;;###autoload
951(defun calc-dispatch (&optional arg)
f269b73e 952 "Invoke the GNU Emacs Calculator. See `calc-dispatch-help' for details."
136211a9
EZ
953 (interactive "P")
954 (sit-for echo-keystrokes)
955 (condition-case err ; look for other keys bound to calc-dispatch
956 (let ((keys (this-command-keys)))
cd012309
CW
957 (unless (or (not (stringp keys))
958 (string-match "\\`\C-u\\|\\`\e[-0-9#]\\|`[\M--\M-0-\M-9]" keys)
959 (eq (lookup-key calc-dispatch-map keys) 'calc-same-interface))
960 (when (and (string-match "\\`[\C-@-\C-_]" keys)
961 (symbolp
962 (lookup-key calc-dispatch-map (substring keys 0 1))))
963 (define-key calc-dispatch-map (substring keys 0 1) nil))
964 (define-key calc-dispatch-map keys 'calc-same-interface)))
136211a9 965 (error nil))
bf77c646 966 (calc-do-dispatch arg))
136211a9 967
f269b73e 968(defvar calc-dispatch-help nil)
136211a9
EZ
969(defun calc-do-dispatch (arg)
970 (let ((key (calc-read-key-sequence
971 (if calc-dispatch-help
972 "Calc options: Calc, Keypad, Quick, Embed; eXit; Info, Tutorial; Grab; ?=more"
973 (format "%s (Type ? for a list of Calc options)"
974 (key-description (this-command-keys))))
975 calc-dispatch-map)))
976 (setq key (lookup-key calc-dispatch-map key))
977 (message "")
978 (if key
979 (progn
980 (or (commandp key) (calc-extensions))
981 (call-interactively key))
bf77c646 982 (beep))))
136211a9
EZ
983
984(defun calc-read-key-sequence (prompt map)
985 (let ((prompt2 (format "%s " (key-description (this-command-keys))))
986 (glob (current-global-map))
987 (loc (current-local-map)))
988 (or (input-pending-p) (message prompt))
989 (let ((key (calc-read-key t)))
990 (calc-unread-command (cdr key))
991 (unwind-protect
992 (progn
993 (use-global-map map)
994 (use-local-map nil)
995 (read-key-sequence
cecd4c20 996 (if (commandp (key-binding (vector (cdr key))))
136211a9
EZ
997 "" prompt2)))
998 (use-global-map glob)
bf77c646 999 (use-local-map loc)))))
136211a9
EZ
1000
1001
1002
1003(defun calc-mode ()
1004 "Calculator major mode.
1005
1006This is an RPN calculator featuring arbitrary-precision integer, rational,
1007floating-point, complex, matrix, and symbolic arithmetic.
1008
1009RPN calculation: 2 RET 3 + produces 5.
1010Algebraic style: ' 2+3 RET produces 5.
1011
1012Basic operators are +, -, *, /, ^, & (reciprocal), % (modulo), n (change-sign).
1013
1014Press ? repeatedly for more complete help. Press `h i' to read the
1015Calc manual on-line, `h s' to read the summary, or `h t' for the tutorial.
1016
1017Notations: 3.14e6 3.14 * 10^6
1018 _23 negative number -23 (or type `23 n')
1019 17:3 the fraction 17/3
1020 5:2:3 the fraction 5 and 2/3
1021 16#12C the integer 12C base 16 = 300 base 10
1022 8#177:100 the fraction 177:100 base 8 = 127:64 base 10
1023 (2, 4) complex number 2 + 4i
1024 (2; 4) polar complex number (r; theta)
1025 [1, 2, 3] vector ([[1, 2], [3, 4]] is a matrix)
1026 [1 .. 4) semi-open interval, 1 <= x < 4
1027 2 +/- 3 (p key) number with mean 2, standard deviation 3
1028 2 mod 3 (M key) number 2 computed modulo 3
1029 <1 jan 91> Date form (enter using ' key)
1030
1031
1032\\{calc-mode-map}
1033"
1034 (interactive)
1035 (mapcar (function
1036 (lambda (v) (set-default v (symbol-value v)))) calc-local-var-list)
1037 (kill-all-local-variables)
1038 (use-local-map (if (eq calc-algebraic-mode 'total)
1039 (progn (calc-extensions) calc-alg-map) calc-mode-map))
1040 (mapcar (function (lambda (v) (make-local-variable v))) calc-local-var-list)
1041 (make-local-variable 'overlay-arrow-position)
1042 (make-local-variable 'overlay-arrow-string)
558f9ba1 1043 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
136211a9
EZ
1044 (setq truncate-lines t)
1045 (setq buffer-read-only t)
1046 (setq major-mode 'calc-mode)
1047 (setq mode-name "Calculator")
1048 (setq calc-stack-top (length (or (memq (assq 'top-of-stack calc-stack)
1049 calc-stack)
1050 (setq calc-stack (list (list 'top-of-stack
1051 1 nil))))))
1052 (setq calc-stack-top (- (length calc-stack) calc-stack-top -1))
1053 (or calc-loaded-settings-file
f269b73e 1054 (null calc-settings-file)
a8aee43b 1055 (equal calc-settings-file user-init-file)
136211a9
EZ
1056 (progn
1057 (setq calc-loaded-settings-file t)
1058 (load calc-settings-file t))) ; t = missing-ok
1059 (if (and (eq window-system 'x) (boundp 'mouse-map))
1060 (substitute-key-definition 'x-paste-text 'calc-x-paste-text
1061 mouse-map))
1062 (let ((p command-line-args))
1063 (while p
1064 (and (equal (car p) "-f")
1065 (string-match "calc" (nth 1 p))
1066 (string-match "full" (nth 1 p))
1067 (setq calc-standalone-flag t))
1068 (setq p (cdr p))))
1069 (run-hooks 'calc-mode-hook)
1070 (calc-refresh t)
1071 (calc-set-mode-line)
1072 ;; The calc-defs variable is a relic. Use calc-define properties instead.
cd012309
CW
1073 (when (and (boundp 'calc-defs)
1074 calc-defs)
1075 (message "Evaluating calc-defs...")
1076 (calc-need-macros)
1077 (eval (cons 'progn calc-defs))
1078 (setq calc-defs nil)
1079 (calc-set-mode-line))
bf77c646 1080 (calc-check-defines))
136211a9 1081
f269b73e 1082(defvar calc-check-defines 'calc-check-defines) ; suitable for run-hooks
136211a9
EZ
1083(defun calc-check-defines ()
1084 (if (symbol-plist 'calc-define)
1085 (let ((plist (copy-sequence (symbol-plist 'calc-define))))
1086 (while (and plist (null (nth 1 plist)))
1087 (setq plist (cdr (cdr plist))))
1088 (if plist
1089 (save-excursion
1090 (calc-extensions)
1091 (calc-need-macros)
1092 (set-buffer "*Calculator*")
1093 (while plist
1094 (put 'calc-define (car plist) nil)
1095 (eval (nth 1 plist))
1096 (setq plist (cdr (cdr plist))))
1097 ;; See if this has added any more calc-define properties.
1098 (calc-check-defines))
bf77c646 1099 (setplist 'calc-define nil)))))
136211a9
EZ
1100
1101(defun calc-trail-mode (&optional buf)
1102 "Calc Trail mode.
1103This mode is used by the *Calc Trail* buffer, which records all results
1104obtained by the GNU Emacs Calculator.
1105
1106Calculator commands beginning with the `t' key are used to manipulate
1107the Trail.
1108
1109This buffer uses the same key map as the *Calculator* buffer; calculator
1110commands given here will actually operate on the *Calculator* stack."
1111 (interactive)
1112 (fundamental-mode)
1113 (use-local-map calc-mode-map)
1114 (setq major-mode 'calc-trail-mode)
1115 (setq mode-name "Calc Trail")
1116 (setq truncate-lines t)
1117 (setq buffer-read-only t)
1118 (make-local-variable 'overlay-arrow-position)
1119 (make-local-variable 'overlay-arrow-string)
cd012309
CW
1120 (set (make-local-variable 'font-lock-defaults)
1121 '(nil t nil nil nil (font-lock-core-only . t)))
1122 (when buf
1123 (set (make-local-variable 'calc-main-buffer) buf))
1124 (when (= (buffer-size) 0)
1125 (let ((buffer-read-only nil))
1126 (insert (propertize (concat "Emacs Calculator v" calc-version
1127 " by Dave Gillespie\n")
1128 'font-lock-face 'italic))))
bf77c646 1129 (run-hooks 'calc-trail-mode-hook))
136211a9
EZ
1130
1131(defun calc-create-buffer ()
1132 (set-buffer (get-buffer-create "*Calculator*"))
1133 (or (eq major-mode 'calc-mode)
1134 (calc-mode))
1135 (setq max-lisp-eval-depth (max max-lisp-eval-depth 1000))
cd012309
CW
1136 (when calc-always-load-extensions
1137 (calc-extensions))
1138 (when calc-language
1139 (calc-extensions)
1140 (calc-set-language calc-language calc-language-option t)))
136211a9
EZ
1141
1142;;;###autoload
1143(defun calc (&optional arg full-display interactive)
1144 "The Emacs Calculator. Full documentation is listed under \"calc-mode\"."
577e1b74 1145 (interactive "P\ni\np")
136211a9 1146 (if arg
cd012309
CW
1147 (unless (eq arg 0)
1148 (calc-extensions)
1149 (if (= (prefix-numeric-value arg) -1)
1150 (calc-grab-region (region-beginning) (region-end) nil)
1151 (when (= (prefix-numeric-value arg) -2)
1152 (calc-keypad))))
1153 (when (get-buffer-window "*Calc Keypad*")
1154 (calc-keypad)
1155 (set-buffer (window-buffer (selected-window))))
136211a9
EZ
1156 (if (eq major-mode 'calc-mode)
1157 (calc-quit)
1158 (let ((oldbuf (current-buffer)))
1159 (calc-create-buffer)
1160 (setq calc-was-keypad-mode nil)
1161 (if (or (eq full-display t)
1162 (and (null full-display) calc-full-mode))
1163 (switch-to-buffer (current-buffer) t)
1164 (if (get-buffer-window (current-buffer))
1165 (select-window (get-buffer-window (current-buffer)))
136211a9
EZ
1166 (if (and (boundp 'calc-window-hook) calc-window-hook)
1167 (run-hooks 'calc-window-hook)
1168 (let ((w (get-largest-window)))
1169 (if (and pop-up-windows
1170 (> (window-height w)
1171 (+ window-min-height calc-window-height 2)))
1172 (progn
136211a9
EZ
1173 (setq w (split-window w
1174 (- (window-height w)
1175 calc-window-height 2)
1176 nil))
1177 (set-window-buffer w (current-buffer))
1178 (select-window w))
1179 (pop-to-buffer (current-buffer)))))))
1180 (save-excursion
1181 (set-buffer (calc-trail-buffer))
1182 (and calc-display-trail
31b85a14 1183 (= (window-width) (frame-width))
136211a9 1184 (calc-trail-display 1 t)))
f269b73e 1185 (message "Welcome to the GNU Emacs Calculator! Press `?' or `h' for help, `q' to quit")
136211a9
EZ
1186 (run-hooks 'calc-start-hook)
1187 (and (windowp full-display)
1188 (window-point full-display)
1189 (select-window full-display))
1190 (calc-check-defines)
577e1b74 1191 (when (and calc-said-hello interactive)
cd012309
CW
1192 (sit-for 2)
1193 (message ""))
bf77c646 1194 (setq calc-said-hello t)))))
136211a9
EZ
1195
1196;;;###autoload
577e1b74 1197(defun full-calc (&optional interactive)
136211a9 1198 "Invoke the Calculator and give it a full-sized window."
577e1b74
JB
1199 (interactive "p")
1200 (calc nil t interactive))
136211a9
EZ
1201
1202(defun calc-same-interface (arg)
1203 "Invoke the Calculator using the most recent interface (calc or calc-keypad)."
1204 (interactive "P")
1205 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1206 (> (recursion-depth) 0))
1207 (exit-recursive-edit)
1208 (if (eq major-mode 'calc-edit-mode)
1209 (calc-edit-finish arg)
1210 (if (eq major-mode 'MacEdit-mode)
1211 (MacEdit-finish-edit)
1212 (if calc-was-keypad-mode
1213 (calc-keypad)
bf77c646 1214 (calc arg calc-full-mode t))))))
136211a9
EZ
1215
1216
577e1b74
JB
1217(defun calc-quit (&optional non-fatal interactive)
1218 (interactive "i\np")
136211a9
EZ
1219 (and calc-standalone-flag (not non-fatal)
1220 (save-buffers-kill-emacs nil))
1221 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1222 (> (recursion-depth) 0))
1223 (exit-recursive-edit))
1224 (if (eq major-mode 'calc-edit-mode)
1225 (calc-edit-cancel)
1226 (if (eq major-mode 'MacEdit-mode)
1227 (MacEdit-cancel-edit)
577e1b74 1228 (if (and interactive
136211a9
EZ
1229 calc-embedded-info
1230 (eq (current-buffer) (aref calc-embedded-info 0)))
1231 (calc-embedded nil)
f269b73e
CW
1232 (unless (eq major-mode 'calc-mode)
1233 (calc-create-buffer))
136211a9
EZ
1234 (run-hooks 'calc-end-hook)
1235 (setq calc-undo-list nil calc-redo-list nil)
1236 (mapcar (function (lambda (v) (set-default v (symbol-value v))))
1237 calc-local-var-list)
1238 (let ((buf (current-buffer))
1239 (win (get-buffer-window (current-buffer)))
1240 (kbuf (get-buffer "*Calc Keypad*")))
1241 (delete-windows-on (calc-trail-buffer))
1242 (if (and win
31b85a14
EZ
1243 (< (window-height win) (1- (frame-height)))
1244 (= (window-width win) (frame-width)) ; avoid calc-keypad
136211a9
EZ
1245 (not (get-buffer-window "*Calc Keypad*")))
1246 (setq calc-window-height (- (window-height win) 2)))
1cc6997c 1247 (progn
136211a9
EZ
1248 (delete-windows-on buf)
1249 (delete-windows-on kbuf))
1250 (bury-buffer buf)
1251 (bury-buffer calc-trail-buffer)
bf77c646 1252 (and kbuf (bury-buffer kbuf)))))))
136211a9
EZ
1253
1254;;;###autoload
1255(defun quick-calc ()
1256 "Do a quick calculation in the minibuffer without invoking full Calculator."
1257 (interactive)
bf77c646 1258 (calc-do-quick-calc))
136211a9
EZ
1259
1260;;;###autoload
1261(defun calc-eval (str &optional separator &rest args)
1262 "Do a quick calculation and return the result as a string.
1263Return value will either be the formatted result in string form,
1264or a list containing a character position and an error message in string form."
bf77c646 1265 (calc-do-calc-eval str separator args))
136211a9
EZ
1266
1267;;;###autoload
577e1b74 1268(defun calc-keypad (&optional interactive)
136211a9
EZ
1269 "Invoke the Calculator in \"visual keypad\" mode.
1270This is most useful in the X window system.
1271In this mode, click on the Calc \"buttons\" using the left mouse button.
1272Or, position the cursor manually and do M-x calc-keypad-press."
577e1b74 1273 (interactive "p")
136211a9 1274 (calc-extensions)
577e1b74 1275 (calc-do-keypad calc-full-mode interactive))
136211a9
EZ
1276
1277;;;###autoload
577e1b74 1278(defun full-calc-keypad (&optional interactive)
136211a9
EZ
1279 "Invoke the Calculator in full-screen \"visual keypad\" mode.
1280See calc-keypad for details."
577e1b74 1281 (interactive "p")
136211a9 1282 (calc-extensions)
577e1b74 1283 (calc-do-keypad t interactive))
136211a9
EZ
1284
1285
f269b73e
CW
1286(defvar calc-aborted-prefix nil)
1287(defvar calc-start-time nil)
730576f3
CW
1288(defvar calc-command-flags)
1289(defvar calc-final-point-line)
1290(defvar calc-final-point-column)
136211a9
EZ
1291;;; Note that modifications to this function may break calc-pass-errors.
1292(defun calc-do (do-body &optional do-slow)
1293 (calc-check-defines)
1294 (let* ((calc-command-flags nil)
1295 (calc-start-time (and calc-timing (not calc-start-time)
1296 (calc-extensions)
1297 (current-time-string)))
1298 (gc-cons-threshold (max gc-cons-threshold
730576f3
CW
1299 (if calc-timing 2000000 100000)))
1300 calc-final-point-line calc-final-point-column)
136211a9
EZ
1301 (setq calc-aborted-prefix "")
1302 (unwind-protect
1303 (condition-case err
1304 (save-excursion
1305 (if calc-embedded-info
1306 (calc-embedded-select-buffer)
1307 (calc-select-buffer))
1308 (and (eq calc-algebraic-mode 'total)
1309 (calc-extensions)
1310 (use-local-map calc-alg-map))
f269b73e
CW
1311 (when (and do-slow calc-display-working-message)
1312 (message "Working...")
1313 (calc-set-command-flag 'clear-message))
136211a9
EZ
1314 (funcall do-body)
1315 (setq calc-aborted-prefix nil)
f269b73e
CW
1316 (when (memq 'renum-stack calc-command-flags)
1317 (calc-renumber-stack))
1318 (when (memq 'clear-message calc-command-flags)
1319 (message "")))
136211a9
EZ
1320 (error
1321 (if (and (eq (car err) 'error)
1322 (stringp (nth 1 err))
1323 (string-match "max-specpdl-size\\|max-lisp-eval-depth"
1324 (nth 1 err)))
f269b73e 1325 (error "Computation got stuck or ran too long. Type `M' to increase the limit")
136211a9
EZ
1326 (setq calc-aborted-prefix nil)
1327 (signal (car err) (cdr err)))))
f269b73e
CW
1328 (when calc-aborted-prefix
1329 (calc-record "<Aborted>" calc-aborted-prefix))
136211a9
EZ
1330 (and calc-start-time
1331 (let* ((calc-internal-prec 12)
1332 (calc-date-format nil)
1333 (end-time (current-time-string))
1334 (time (if (equal calc-start-time end-time)
1335 0
1336 (math-sub
1337 (calcFunc-unixtime (math-parse-date end-time) 0)
1338 (calcFunc-unixtime (math-parse-date calc-start-time)
1339 0)))))
1340 (if (math-lessp 1 time)
1341 (calc-record time "(t)"))))
1342 (or (memq 'no-align calc-command-flags)
1343 (eq major-mode 'calc-trail-mode)
1344 (calc-align-stack-window))
1345 (and (memq 'position-point calc-command-flags)
1346 (if (eq major-mode 'calc-mode)
1347 (progn
1348 (goto-line calc-final-point-line)
1349 (move-to-column calc-final-point-column))
730576f3 1350 (save-current-buffer
136211a9
EZ
1351 (calc-select-buffer)
1352 (goto-line calc-final-point-line)
1353 (move-to-column calc-final-point-column))))
f269b73e
CW
1354 (unless (memq 'keep-flags calc-command-flags)
1355 (save-excursion
1356 (calc-select-buffer)
1357 (setq calc-inverse-flag nil
1358 calc-hyperbolic-flag nil
1359 calc-keep-args-flag nil)))
1360 (when (memq 'do-edit calc-command-flags)
1361 (switch-to-buffer (get-buffer-create "*Calc Edit*")))
136211a9 1362 (calc-set-mode-line)
f269b73e
CW
1363 (when calc-embedded-info
1364 (calc-embedded-finish-command))))
bf77c646
CW
1365 (identity nil)) ; allow a GC after timing is done
1366
136211a9
EZ
1367
1368(defun calc-set-command-flag (f)
f269b73e
CW
1369 (unless (memq f calc-command-flags)
1370 (setq calc-command-flags (cons f calc-command-flags))))
136211a9
EZ
1371
1372(defun calc-select-buffer ()
1373 (or (eq major-mode 'calc-mode)
1374 (if calc-main-buffer
1375 (set-buffer calc-main-buffer)
1376 (let ((buf (get-buffer "*Calculator*")))
1377 (if buf
1378 (set-buffer buf)
bf77c646 1379 (error "Calculator buffer not available"))))))
136211a9
EZ
1380
1381(defun calc-cursor-stack-index (&optional index)
1382 (goto-char (point-max))
bf77c646 1383 (forward-line (- (calc-substack-height (or index 1)))))
136211a9
EZ
1384
1385(defun calc-stack-size ()
bf77c646 1386 (- (length calc-stack) calc-stack-top))
136211a9
EZ
1387
1388(defun calc-substack-height (n)
1389 (let ((sum 0)
1390 (stack calc-stack))
1391 (setq n (+ n calc-stack-top))
1392 (while (and (> n 0) stack)
1393 (setq sum (+ sum (nth 1 (car stack)))
1394 n (1- n)
1395 stack (cdr stack)))
bf77c646 1396 sum))
136211a9
EZ
1397
1398(defun calc-set-mode-line ()
1399 (save-excursion
1400 (calc-select-buffer)
1401 (let* ((fmt (car calc-float-format))
1402 (figs (nth 1 calc-float-format))
1403 (new-mode-string
1404 (format "Calc%s%s: %d %s %-14s"
1405 (if calc-embedded-info "Embed" "")
1406 (if (and (> (length (buffer-name)) 12)
1407 (equal (substring (buffer-name) 0 12)
1408 "*Calculator*"))
1409 (substring (buffer-name) 12)
1410 "")
1411 calc-internal-prec
1412 (capitalize (symbol-name calc-angle-mode))
1413 (concat
1414
1415 ;; Input-related modes
1416 (if (eq calc-algebraic-mode 'total) "Alg* "
1417 (if calc-algebraic-mode "Alg "
1418 (if calc-incomplete-algebraic-mode "Alg[( " "")))
1419
1420 ;; Computational modes
1421 (if calc-symbolic-mode "Symb " "")
1422 (cond ((eq calc-matrix-mode 'matrix) "Matrix ")
1423 ((integerp calc-matrix-mode)
1424 (format "Matrix%d " calc-matrix-mode))
1425 ((eq calc-matrix-mode 'scalar) "Scalar ")
1426 (t ""))
1427 (if (eq calc-complex-mode 'polar) "Polar " "")
1428 (if calc-prefer-frac "Frac " "")
1429 (cond ((null calc-infinite-mode) "")
1430 ((eq calc-infinite-mode 1) "+Inf ")
1431 (t "Inf "))
1432 (cond ((eq calc-simplify-mode 'none) "NoSimp ")
1433 ((eq calc-simplify-mode 'num) "NumSimp ")
1434 ((eq calc-simplify-mode 'binary)
1435 (format "BinSimp%d " calc-word-size))
1436 ((eq calc-simplify-mode 'alg) "AlgSimp ")
1437 ((eq calc-simplify-mode 'ext) "ExtSimp ")
1438 ((eq calc-simplify-mode 'units) "UnitSimp ")
1439 (t ""))
1440
1441 ;; Display modes
1442 (cond ((= calc-number-radix 10) "")
1443 ((= calc-number-radix 2) "Bin ")
1444 ((= calc-number-radix 8) "Oct ")
1445 ((= calc-number-radix 16) "Hex ")
1446 (t (format "Radix%d " calc-number-radix)))
1447 (if calc-leading-zeros "Zero " "")
1448 (cond ((null calc-language) "")
1449 ((eq calc-language 'tex) "TeX ")
1450 (t (concat
1451 (capitalize (symbol-name calc-language))
1452 " ")))
1453 (cond ((eq fmt 'float)
1454 (if (zerop figs) "" (format "Norm%d " figs)))
1455 ((eq fmt 'fix) (format "Fix%d " figs))
1456 ((eq fmt 'sci)
1457 (if (zerop figs) "Sci " (format "Sci%d " figs)))
1458 ((eq fmt 'eng)
1459 (if (zerop figs) "Eng " (format "Eng%d " figs))))
1460 (cond ((not calc-display-just)
1461 (if calc-display-origin
1462 (format "Left%d " calc-display-origin) ""))
1463 ((eq calc-display-just 'right)
1464 (if calc-display-origin
1465 (format "Right%d " calc-display-origin)
1466 "Right "))
1467 (t
1468 (if calc-display-origin
1469 (format "Center%d " calc-display-origin)
1470 "Center ")))
1471 (cond ((integerp calc-line-breaking)
1472 (format "Wid%d " calc-line-breaking))
1473 (calc-line-breaking "")
1474 (t "Wide "))
1475
1476 ;; Miscellaneous other modes/indicators
1477 (if calc-assoc-selections "" "Break ")
1478 (cond ((eq calc-mode-save-mode 'save) "Save ")
1479 ((not calc-embedded-info) "")
1480 ((eq calc-mode-save-mode 'local) "Local ")
1481 ((eq calc-mode-save-mode 'edit) "LocEdit ")
1482 ((eq calc-mode-save-mode 'perm) "LocPerm ")
1483 ((eq calc-mode-save-mode 'global) "Global ")
1484 (t ""))
1485 (if calc-auto-recompute "" "Manual ")
1486 (if (and (fboundp 'calc-gnuplot-alive)
1487 (calc-gnuplot-alive)) "Graph " "")
1488 (if (and calc-embedded-info
1489 (> (calc-stack-size) 0)
1490 (calc-top 1 'sel)) "Sel " "")
1491 (if calc-display-dirty "Dirty " "")
1492 (if calc-inverse-flag "Inv " "")
1493 (if calc-hyperbolic-flag "Hyp " "")
1494 (if calc-keep-args-flag "Keep " "")
1495 (if (/= calc-stack-top 1) "Narrow " "")
1496 (apply 'concat calc-other-modes)))))
1497 (if (equal new-mode-string mode-line-buffer-identification)
1498 nil
1499 (setq mode-line-buffer-identification new-mode-string)
1500 (set-buffer-modified-p (buffer-modified-p))
bf77c646 1501 (and calc-embedded-info (calc-embedded-mode-line-change))))))
136211a9
EZ
1502
1503(defun calc-align-stack-window ()
1504 (if (eq major-mode 'calc-mode)
1505 (progn
1506 (let ((win (get-buffer-window (current-buffer))))
1507 (if win
1508 (progn
1509 (calc-cursor-stack-index 0)
1510 (vertical-motion (- 2 (window-height win)))
1511 (set-window-start win (point)))))
1512 (calc-cursor-stack-index 0)
1513 (if (looking-at " *\\.$")
1514 (goto-char (1- (match-end 0)))))
1515 (save-excursion
1516 (calc-select-buffer)
bf77c646 1517 (calc-align-stack-window))))
136211a9
EZ
1518
1519(defun calc-check-stack (n)
1520 (if (> n (calc-stack-size))
1521 (error "Too few elements on stack"))
1522 (if (< n 0)
bf77c646 1523 (error "Invalid argument")))
136211a9
EZ
1524
1525(defun calc-push-list (vals &optional m sels)
1526 (while vals
1527 (if calc-executing-macro
1528 (calc-push-list-in-macro vals m sels)
1529 (save-excursion
1530 (calc-select-buffer)
1531 (let* ((val (car vals))
1532 (entry (list val 1 (car sels)))
1533 (mm (+ (or m 1) calc-stack-top)))
1534 (calc-cursor-stack-index (1- (or m 1)))
1535 (if (> mm 1)
1536 (setcdr (nthcdr (- mm 2) calc-stack)
1537 (cons entry (nthcdr (1- mm) calc-stack)))
1538 (setq calc-stack (cons entry calc-stack)))
1539 (let ((buffer-read-only nil))
1540 (insert (math-format-stack-value entry) "\n"))
1541 (calc-record-undo (list 'push mm))
1542 (calc-set-command-flag 'renum-stack))))
1543 (setq vals (cdr vals)
bf77c646 1544 sels (cdr sels))))
136211a9
EZ
1545
1546(defun calc-pop-push-list (n vals &optional m sels)
1547 (if (and calc-any-selections (null sels))
1548 (calc-replace-selections n vals m)
1549 (calc-pop-stack n m sels)
bf77c646 1550 (calc-push-list vals m sels)))
136211a9
EZ
1551
1552(defun calc-pop-push-record-list (n prefix vals &optional m sels)
1553 (or (and (consp vals)
1554 (or (integerp (car vals))
1555 (consp (car vals))))
1556 (and vals (setq vals (list vals)
1557 sels (and sels (list sels)))))
1558 (calc-check-stack (+ n (or m 1) -1))
1559 (if prefix
1560 (if (cdr vals)
1561 (calc-record-list vals prefix)
1562 (calc-record (car vals) prefix)))
bf77c646 1563 (calc-pop-push-list n vals m sels))
136211a9
EZ
1564
1565(defun calc-enter-result (n prefix vals &optional m)
1566 (setq calc-aborted-prefix prefix)
1567 (if (and (consp vals)
1568 (or (integerp (car vals))
1569 (consp (car vals))))
1570 (setq vals (mapcar 'calc-normalize vals))
1571 (setq vals (calc-normalize vals)))
1572 (or (and (consp vals)
1573 (or (integerp (car vals))
1574 (consp (car vals))))
1575 (setq vals (list vals)))
1576 (if (equal vals '((nil)))
1577 (setq vals nil))
1578 (calc-pop-push-record-list n prefix vals m)
bf77c646 1579 (calc-handle-whys))
136211a9
EZ
1580
1581(defun calc-normalize (val)
1582 (if (memq calc-simplify-mode '(nil none num))
1583 (math-normalize val)
1584 (calc-extensions)
bf77c646 1585 (calc-normalize-fancy val)))
136211a9
EZ
1586
1587(defun calc-handle-whys ()
1588 (if calc-next-why
bf77c646 1589 (calc-do-handle-whys)))
136211a9
EZ
1590
1591
1592(defun calc-pop-stack (&optional n m sel-ok) ; pop N objs at level M of stack.
1593 (or n (setq n 1))
1594 (or m (setq m 1))
1595 (or calc-keep-args-flag
1596 (let ((mm (+ m calc-stack-top)))
1597 (if (and calc-any-selections (not sel-ok)
1598 (calc-top-selected n m))
1599 (calc-sel-error))
1600 (if calc-executing-macro
1601 (calc-pop-stack-in-macro n mm)
1602 (calc-record-undo (list 'pop mm (calc-top-list n m 'full)))
1603 (save-excursion
1604 (calc-select-buffer)
1605 (let ((buffer-read-only nil))
1606 (if (> mm 1)
1607 (progn
1608 (calc-cursor-stack-index (1- m))
1609 (let ((bot (point)))
1610 (calc-cursor-stack-index (+ n m -1))
1611 (delete-region (point) bot))
1612 (setcdr (nthcdr (- mm 2) calc-stack)
1613 (nthcdr (+ n mm -1) calc-stack)))
1614 (calc-cursor-stack-index n)
1615 (setq calc-stack (nthcdr n calc-stack))
1616 (delete-region (point) (point-max))))
bf77c646 1617 (calc-set-command-flag 'renum-stack))))))
136211a9 1618
730576f3 1619(defvar sel-mode)
136211a9
EZ
1620(defun calc-get-stack-element (x)
1621 (cond ((eq sel-mode 'entry)
1622 x)
1623 ((eq sel-mode 'sel)
1624 (nth 2 x))
1625 ((or (null (nth 2 x))
1626 (eq sel-mode 'full)
1627 (not calc-use-selections))
1628 (car x))
1629 (sel-mode
1630 (calc-sel-error))
bf77c646 1631 (t (nth 2 x))))
136211a9
EZ
1632
1633;; Get the Nth element of the stack (N=1 is the top element).
1634(defun calc-top (&optional n sel-mode)
1635 (or n (setq n 1))
1636 (calc-check-stack n)
bf77c646 1637 (calc-get-stack-element (nth (+ n calc-stack-top -1) calc-stack)))
136211a9
EZ
1638
1639(defun calc-top-n (&optional n sel-mode) ; in case precision has changed
bf77c646 1640 (math-check-complete (calc-normalize (calc-top n sel-mode))))
136211a9
EZ
1641
1642(defun calc-top-list (&optional n m sel-mode)
1643 (or n (setq n 1))
1644 (or m (setq m 1))
1645 (calc-check-stack (+ n m -1))
1646 (and (> n 0)
1647 (let ((top (copy-sequence (nthcdr (+ m calc-stack-top -1)
1648 calc-stack))))
1649 (setcdr (nthcdr (1- n) top) nil)
bf77c646 1650 (nreverse (mapcar 'calc-get-stack-element top)))))
136211a9
EZ
1651
1652(defun calc-top-list-n (&optional n m sel-mode)
1653 (mapcar 'math-check-complete
bf77c646 1654 (mapcar 'calc-normalize (calc-top-list n m sel-mode))))
136211a9
EZ
1655
1656
1657(defun calc-renumber-stack ()
1658 (if calc-line-numbering
1659 (save-excursion
1660 (calc-cursor-stack-index 0)
1661 (let ((lnum 1)
1662 (buffer-read-only nil)
1663 (stack (nthcdr calc-stack-top calc-stack)))
1664 (if (re-search-forward "^[0-9]+[:*]" nil t)
1665 (progn
1666 (beginning-of-line)
1667 (while (re-search-forward "^[0-9]+[:*]" nil t)
1668 (let ((buffer-read-only nil))
1669 (beginning-of-line)
1670 (delete-char 4)
1671 (insert " ")))
1672 (calc-cursor-stack-index 0)))
1673 (while (re-search-backward "^[0-9]+[:*]" nil t)
1674 (delete-char 4)
1675 (if (> lnum 999)
1676 (insert (format "%03d%s" (% lnum 1000)
1677 (if (and (nth 2 (car stack))
1678 calc-use-selections) "*" ":")))
1679 (let ((prefix (int-to-string lnum)))
1680 (insert prefix (if (and (nth 2 (car stack))
1681 calc-use-selections) "*" ":")
1682 (make-string (- 3 (length prefix)) 32))))
1683 (beginning-of-line)
1684 (setq lnum (1+ lnum)
1685 stack (cdr stack))))))
bf77c646 1686 (and calc-embedded-info (calc-embedded-stack-change)))
136211a9 1687
11bfbbd2 1688(defvar calc-any-evaltos nil)
136211a9
EZ
1689(defun calc-refresh (&optional align)
1690 (interactive)
1691 (and (eq major-mode 'calc-mode)
1692 (not calc-executing-macro)
1693 (let* ((buffer-read-only nil)
1694 (save-point (point))
1695 (save-mark (condition-case err (mark) (error nil)))
1696 (save-aligned (looking-at "\\.$"))
730576f3
CW
1697 (thing calc-stack)
1698 (calc-any-evaltos nil))
1699 (setq calc-any-selections nil)
136211a9 1700 (erase-buffer)
1501f4f6 1701 (when calc-show-banner
cd012309
CW
1702 (insert (propertize "--- Emacs Calculator Mode ---\n"
1703 'font-lock-face 'italic)))
136211a9
EZ
1704 (while thing
1705 (goto-char (point-min))
1501f4f6
MB
1706 (when calc-show-banner
1707 (forward-line 1))
136211a9
EZ
1708 (insert (math-format-stack-value (car thing)) "\n")
1709 (setq thing (cdr thing)))
1710 (calc-renumber-stack)
1711 (if calc-display-dirty
1712 (calc-wrapper (setq calc-display-dirty nil)))
1713 (and calc-any-evaltos calc-auto-recompute
1714 (calc-wrapper (calc-refresh-evaltos)))
1715 (if (or align save-aligned)
1716 (calc-align-stack-window)
1717 (goto-char save-point))
1718 (if save-mark (set-mark save-mark))))
1719 (and calc-embedded-info (not (eq major-mode 'calc-mode))
1720 (save-excursion
1721 (set-buffer (aref calc-embedded-info 1))
1722 (calc-refresh align)))
bf77c646 1723 (setq calc-refresh-count (1+ calc-refresh-count)))
136211a9
EZ
1724
1725
1726(defun calc-x-paste-text (arg)
1727 "Move point to mouse position and insert window system cut buffer contents.
1728If mouse is pressed in Calc window, push cut buffer contents onto the stack."
1729 (x-mouse-select arg)
1730 (if (memq major-mode '(calc-mode calc-trail-mode))
1731 (progn
1732 (calc-wrapper
1733 (calc-extensions)
1734 (let* ((buf (x-get-cut-buffer))
1735 (val (math-read-exprs (calc-clean-newlines buf))))
1736 (if (eq (car-safe val) 'error)
1737 (progn
1738 (setq val (math-read-exprs buf))
1739 (if (eq (car-safe val) 'error)
1740 (error "%s in yanked data" (nth 2 val)))))
1741 (calc-enter-result 0 "Xynk" val))))
bf77c646 1742 (x-paste-text arg)))
136211a9
EZ
1743
1744
1745
1746;;;; The Calc Trail buffer.
1747
1748(defun calc-check-trail-aligned ()
1749 (save-excursion
1750 (let ((win (get-buffer-window (current-buffer))))
1751 (and win
bf77c646 1752 (pos-visible-in-window-p (1- (point-max)) win)))))
136211a9
EZ
1753
1754(defun calc-trail-buffer ()
1755 (and (or (null calc-trail-buffer)
1756 (null (buffer-name calc-trail-buffer)))
1757 (save-excursion
1758 (setq calc-trail-buffer (get-buffer-create "*Calc Trail*"))
1759 (let ((buf (or (and (not (eq major-mode 'calc-mode))
1760 (get-buffer "*Calculator*"))
1761 (current-buffer))))
1762 (set-buffer calc-trail-buffer)
1763 (or (eq major-mode 'calc-trail-mode)
1764 (calc-trail-mode buf)))))
1765 (or (and calc-trail-pointer
1766 (eq (marker-buffer calc-trail-pointer) calc-trail-buffer))
1767 (save-excursion
1768 (set-buffer calc-trail-buffer)
1769 (goto-line 2)
1770 (setq calc-trail-pointer (point-marker))))
bf77c646 1771 calc-trail-buffer)
136211a9
EZ
1772
1773(defun calc-record (val &optional prefix)
1774 (setq calc-aborted-prefix nil)
1775 (or calc-executing-macro
1776 (let* ((mainbuf (current-buffer))
1777 (buf (calc-trail-buffer))
1778 (calc-display-raw nil)
1779 (calc-can-abbrev-vectors t)
1780 (fval (if val
1781 (if (stringp val)
1782 val
1783 (math-showing-full-precision
1784 (math-format-flat-expr val 0)))
1785 "")))
1786 (save-excursion
1787 (set-buffer buf)
1788 (let ((aligned (calc-check-trail-aligned))
1789 (buffer-read-only nil))
1790 (goto-char (point-max))
1791 (cond ((null prefix) (insert " "))
1792 ((and (> (length prefix) 4)
1793 (string-match " " prefix 4))
1794 (insert (substring prefix 0 4) " "))
1795 (t (insert (format "%4s " prefix))))
1796 (insert fval "\n")
1797 (let ((win (get-buffer-window buf)))
1798 (if (and aligned win (not (memq 'hold-trail calc-command-flags)))
1799 (calc-trail-here))
1800 (goto-char (1- (point-max))))))))
bf77c646 1801 val)
136211a9
EZ
1802
1803
577e1b74
JB
1804(defun calc-trail-display (flag &optional no-refresh interactive)
1805 (interactive "P\ni\np")
136211a9
EZ
1806 (let ((win (get-buffer-window (calc-trail-buffer))))
1807 (if (setq calc-display-trail
1808 (not (if flag (memq flag '(nil 0)) win)))
1809 (if (null win)
1810 (progn
1811 (if (and (boundp 'calc-trail-window-hook) calc-trail-window-hook)
1812 (run-hooks 'calc-trail-window-hook)
1813 (let ((w (split-window nil (/ (* (window-width) 2) 3) t)))
1814 (set-window-buffer w calc-trail-buffer)))
1815 (calc-wrapper
1816 (setq overlay-arrow-string calc-trail-overlay
1817 overlay-arrow-position calc-trail-pointer)
1818 (or no-refresh
577e1b74 1819 (if interactive
136211a9
EZ
1820 (calc-do-refresh)
1821 (calc-refresh))))))
1822 (if win
1823 (progn
1824 (delete-window win)
1825 (calc-wrapper
1826 (or no-refresh
577e1b74 1827 (if interactive
136211a9
EZ
1828 (calc-do-refresh)
1829 (calc-refresh))))))))
bf77c646 1830 calc-trail-buffer)
136211a9
EZ
1831
1832(defun calc-trail-here ()
1833 (interactive)
1834 (if (eq major-mode 'calc-trail-mode)
1835 (progn
1836 (beginning-of-line)
1837 (if (bobp)
1838 (forward-line 1)
1839 (if (eobp)
1840 (forward-line -1)))
1841 (if (or (bobp) (eobp))
1842 (setq overlay-arrow-position nil) ; trail is empty
1843 (set-marker calc-trail-pointer (point) (current-buffer))
1844 (setq calc-trail-overlay (concat (buffer-substring (point)
1845 (+ (point) 4))
1846 ">")
1847 overlay-arrow-string calc-trail-overlay
1848 overlay-arrow-position calc-trail-pointer)
1849 (forward-char 4)
1850 (let ((win (get-buffer-window (current-buffer))))
1851 (if win
1852 (save-excursion
1853 (forward-line (/ (window-height win) 2))
1854 (forward-line (- 1 (window-height win)))
1855 (set-window-start win (point))
1856 (set-window-point win (+ calc-trail-pointer 4))
1857 (set-buffer calc-main-buffer)
1858 (setq overlay-arrow-string calc-trail-overlay
1859 overlay-arrow-position calc-trail-pointer))))))
bf77c646 1860 (error "Not in Calc Trail buffer")))
136211a9
EZ
1861
1862
1863
1864
1865;;;; The Undo list.
1866
1867(defun calc-record-undo (rec)
1868 (or calc-executing-macro
1869 (if (memq 'undo calc-command-flags)
1870 (setq calc-undo-list (cons (cons rec (car calc-undo-list))
1871 (cdr calc-undo-list)))
1872 (setq calc-undo-list (cons (list rec) calc-undo-list)
1873 calc-redo-list nil)
bf77c646 1874 (calc-set-command-flag 'undo))))
136211a9
EZ
1875
1876
1877
1878
1879;;; Arithmetic commands.
1880
1881(defun calc-binary-op (name func arg &optional ident unary func2)
1882 (setq calc-aborted-prefix name)
1883 (if (null arg)
1884 (calc-enter-result 2 name (cons (or func2 func)
1885 (mapcar 'math-check-complete
1886 (calc-top-list 2))))
1887 (calc-extensions)
bf77c646 1888 (calc-binary-op-fancy name func arg ident unary)))
136211a9
EZ
1889
1890(defun calc-unary-op (name func arg &optional func2)
1891 (setq calc-aborted-prefix name)
1892 (if (null arg)
1893 (calc-enter-result 1 name (list (or func2 func)
1894 (math-check-complete (calc-top 1))))
1895 (calc-extensions)
bf77c646 1896 (calc-unary-op-fancy name func arg)))
136211a9
EZ
1897
1898
1899(defun calc-plus (arg)
1900 (interactive "P")
1901 (calc-slow-wrapper
bf77c646 1902 (calc-binary-op "+" 'calcFunc-add arg 0 nil '+)))
136211a9
EZ
1903
1904(defun calc-minus (arg)
1905 (interactive "P")
1906 (calc-slow-wrapper
bf77c646 1907 (calc-binary-op "-" 'calcFunc-sub arg 0 'neg '-)))
136211a9
EZ
1908
1909(defun calc-times (arg)
1910 (interactive "P")
1911 (calc-slow-wrapper
bf77c646 1912 (calc-binary-op "*" 'calcFunc-mul arg 1 nil '*)))
136211a9
EZ
1913
1914(defun calc-divide (arg)
1915 (interactive "P")
1916 (calc-slow-wrapper
bf77c646 1917 (calc-binary-op "/" 'calcFunc-div arg 0 'calcFunc-inv '/)))
136211a9
EZ
1918
1919
1920(defun calc-change-sign (arg)
1921 (interactive "P")
1922 (calc-wrapper
bf77c646 1923 (calc-unary-op "chs" 'neg arg)))
136211a9
EZ
1924
1925
1926
1927;;; Stack management commands.
1928
1929(defun calc-enter (n)
1930 (interactive "p")
1931 (calc-wrapper
1932 (cond ((< n 0)
1933 (calc-push-list (calc-top-list 1 (- n))))
1934 ((= n 0)
1935 (calc-push-list (calc-top-list (calc-stack-size))))
1936 (t
bf77c646 1937 (calc-push-list (calc-top-list n))))))
136211a9
EZ
1938
1939
1940(defun calc-pop (n)
1941 (interactive "P")
1942 (calc-wrapper
1943 (let* ((nn (prefix-numeric-value n))
1944 (top (and (null n) (calc-top 1))))
1945 (cond ((and (null n)
1946 (eq (car-safe top) 'incomplete)
1947 (> (length top) (if (eq (nth 1 top) 'intv) 3 2)))
1948 (calc-pop-push-list 1 (let ((tt (copy-sequence top)))
1949 (setcdr (nthcdr (- (length tt) 2) tt) nil)
1950 (list tt))))
1951 ((< nn 0)
1952 (if (and calc-any-selections
1953 (calc-top-selected 1 (- nn)))
1954 (calc-delete-selection (- nn))
1955 (calc-pop-stack 1 (- nn) t)))
1956 ((= nn 0)
1957 (calc-pop-stack (calc-stack-size) 1 t))
1958 (t
1959 (if (and calc-any-selections
1960 (= nn 1)
1961 (calc-top-selected 1 1))
1962 (calc-delete-selection 1)
bf77c646 1963 (calc-pop-stack nn)))))))
136211a9
EZ
1964
1965
1966
1967
1968;;;; Reading a number using the minibuffer.
730576f3
CW
1969(defvar calc-buffer)
1970(defvar calc-prev-char)
1971(defvar calc-prev-prev-char)
1972(defvar calc-digit-value)
136211a9
EZ
1973(defun calcDigit-start ()
1974 (interactive)
1975 (calc-wrapper
1976 (if (or calc-algebraic-mode
1977 (and (> calc-number-radix 14) (eq last-command-char ?e)))
1978 (calc-alg-digit-entry)
1979 (calc-unread-command)
1980 (setq calc-aborted-prefix nil)
1981 (let* ((calc-digit-value nil)
1982 (calc-prev-char nil)
1983 (calc-prev-prev-char nil)
1984 (calc-buffer (current-buffer))
1985 (buf (if calc-emacs-type-lucid
1986 (catch 'calc-foo
1987 (catch 'execute-kbd-macro
1988 (throw 'calc-foo
1989 (read-from-minibuffer
1990 "Calc: " "" calc-digit-map)))
1991 (error "Lucid Emacs requires RET after %s"
1992 "digit entry in kbd macro"))
1993 (let ((old-esc (lookup-key global-map "\e")))
1994 (unwind-protect
1995 (progn
1996 (define-key global-map "\e" nil)
1997 (read-from-minibuffer "Calc: " "" calc-digit-map))
1998 (define-key global-map "\e" old-esc))))))
1999 (or calc-digit-value (setq calc-digit-value (math-read-number buf)))
2000 (if (stringp calc-digit-value)
2001 (calc-alg-entry calc-digit-value)
2002 (if calc-digit-value
2003 (calc-push-list (list (calc-record (calc-normalize
2004 calc-digit-value))))))
2005 (if (eq calc-prev-char 'dots)
2006 (progn
2007 (calc-extensions)
bf77c646 2008 (calc-dots)))))))
136211a9 2009
91e51f9a
EZ
2010(defsubst calc-minibuffer-size ()
2011 (- (point-max) (minibuffer-prompt-end)))
2012
136211a9
EZ
2013(defun calcDigit-nondigit ()
2014 (interactive)
2015 ;; Exercise for the reader: Figure out why this is a good precaution!
2016 (or (boundp 'calc-buffer)
2017 (use-local-map minibuffer-local-map))
91e51f9a 2018 (let ((str (minibuffer-contents)))
136211a9
EZ
2019 (setq calc-digit-value (save-excursion
2020 (set-buffer calc-buffer)
2021 (math-read-number str))))
91e51f9a 2022 (if (and (null calc-digit-value) (> (calc-minibuffer-size) 0))
136211a9
EZ
2023 (progn
2024 (beep)
2025 (calc-temp-minibuffer-message " [Bad format]"))
2026 (or (memq last-command-char '(32 13))
2027 (progn (setq prefix-arg current-prefix-arg)
2028 (calc-unread-command (if (and (eq last-command-char 27)
2029 (>= last-input-char 128))
2030 last-input-char
2031 nil))))
bf77c646 2032 (exit-minibuffer)))
136211a9
EZ
2033
2034
2035(defun calc-minibuffer-contains (rex)
2036 (save-excursion
91e51f9a 2037 (goto-char (minibuffer-prompt-end))
bf77c646 2038 (looking-at rex)))
136211a9
EZ
2039
2040(defun calcDigit-key ()
2041 (interactive)
2042 (goto-char (point-max))
2043 (if (or (and (memq last-command-char '(?+ ?-))
2044 (> (buffer-size) 0)
2045 (/= (preceding-char) ?e))
2046 (and (memq last-command-char '(?m ?s))
2047 (not (calc-minibuffer-contains "[-+]?[0-9]+\\.?0*[@oh].*"))
2048 (not (calc-minibuffer-contains "[-+]?\\(1[1-9]\\|[2-9][0-9]\\)#.*"))))
2049 (calcDigit-nondigit)
2050 (if (calc-minibuffer-contains "\\([-+]?\\|.* \\)\\'")
2051 (cond ((memq last-command-char '(?. ?@)) (insert "0"))
2052 ((and (memq last-command-char '(?o ?h ?m))
2053 (not (calc-minibuffer-contains ".*#.*"))) (insert "0"))
2054 ((memq last-command-char '(?: ?e)) (insert "1"))
2055 ((eq last-command-char ?#)
2056 (insert (int-to-string calc-number-radix)))))
2057 (if (and (calc-minibuffer-contains "\\([-+]?[0-9]+#\\|[^:]*:\\)\\'")
2058 (eq last-command-char ?:))
2059 (insert "1"))
2060 (if (and (calc-minibuffer-contains "[-+]?[0-9]+#\\'")
2061 (eq last-command-char ?.))
2062 (insert "0"))
2063 (if (and (calc-minibuffer-contains "[-+]?0*\\([2-9]\\|1[0-4]\\)#\\'")
2064 (eq last-command-char ?e))
2065 (insert "1"))
2066 (if (or (and (memq last-command-char '(?h ?o ?m ?s ?p))
2067 (calc-minibuffer-contains ".*#.*"))
2068 (and (eq last-command-char ?e)
2069 (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2070 (and (eq last-command-char ?n)
2071 (calc-minibuffer-contains "[-+]?\\(2[4-9]\\|[3-9][0-9]\\)#.*")))
2072 (setq last-command-char (upcase last-command-char)))
2073 (cond
2074 ((memq last-command-char '(?_ ?n))
cd01f5b9 2075 (goto-char (minibuffer-prompt-end))
136211a9
EZ
2076 (if (and (search-forward " +/- " nil t)
2077 (not (search-forward "e" nil t)))
2078 (beep)
2079 (and (not (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2080 (search-forward "e" nil t))
2081 (if (looking-at "+")
2082 (delete-char 1))
2083 (if (looking-at "-")
2084 (delete-char 1)
2085 (insert "-")))
2086 (goto-char (point-max)))
2087 ((eq last-command-char ?p)
2088 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2089 (calc-minibuffer-contains ".*mod.*")
2090 (calc-minibuffer-contains ".*#.*")
2091 (calc-minibuffer-contains ".*[-+e:]\\'"))
2092 (beep)
2093 (if (not (calc-minibuffer-contains ".* \\'"))
2094 (insert " "))
2095 (insert "+/- ")))
2096 ((and (eq last-command-char ?M)
2097 (not (calc-minibuffer-contains
2098 "[-+]?\\(2[3-9]\\|[3-9][0-9]\\)#.*")))
2099 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2100 (calc-minibuffer-contains ".*mod *[^ ]+")
2101 (calc-minibuffer-contains ".*[-+e:]\\'"))
2102 (beep)
2103 (if (calc-minibuffer-contains ".*mod \\'")
2104 (if calc-previous-modulo
2105 (insert (math-format-flat-expr calc-previous-modulo 0))
2106 (beep))
2107 (if (not (calc-minibuffer-contains ".* \\'"))
2108 (insert " "))
2109 (insert "mod "))))
2110 (t
2111 (insert (char-to-string last-command-char))
2112 (if (or (and (calc-minibuffer-contains "[-+]?\\(.*\\+/- *\\|.*mod *\\)?\\([0-9][0-9]?\\)#[0-9a-zA-Z]*\\(:[0-9a-zA-Z]*\\(:[0-9a-zA-Z]*\\)?\\|.[0-9a-zA-Z]*\\(e[-+]?[0-9]*\\)?\\)?\\'")
2113 (let ((radix (string-to-int
2114 (buffer-substring
2115 (match-beginning 2) (match-end 2)))))
2116 (and (>= radix 2)
2117 (<= radix 36)
2118 (or (memq last-command-char '(?# ?: ?. ?e ?+ ?-))
2119 (let ((dig (math-read-radix-digit
2120 (upcase last-command-char))))
2121 (and dig
2122 (< dig radix)))))))
91e51f9a
EZ
2123 (calc-minibuffer-contains
2124 "[-+]?\\(.*\\+/- *\\|.*mod *\\)?\\([0-9]+\\.?0*[@oh] *\\)?\\([0-9]+\\.?0*['m] *\\)?[0-9]*\\(\\.?[0-9]*\\(e[-+]?[0-3]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?\\)?\\|[0-9]:\\([0-9]+:\\)?[0-9]*\\)?[\"s]?\\'"))
136211a9
EZ
2125 (if (and (memq last-command-char '(?@ ?o ?h ?\' ?m))
2126 (string-match " " calc-hms-format))
2127 (insert " "))
2128 (if (and (eq this-command last-command)
2129 (eq last-command-char ?.))
2130 (progn
2131 (calc-extensions)
2132 (calc-digit-dots))
2133 (delete-backward-char 1)
2134 (beep)
2135 (calc-temp-minibuffer-message " [Bad format]"))))))
2136 (setq calc-prev-prev-char calc-prev-char
bf77c646 2137 calc-prev-char last-command-char))
136211a9
EZ
2138
2139
2140(defun calcDigit-backspace ()
2141 (interactive)
2142 (goto-char (point-max))
2143 (cond ((calc-minibuffer-contains ".* \\+/- \\'")
2144 (backward-delete-char 5))
2145 ((calc-minibuffer-contains ".* mod \\'")
2146 (backward-delete-char 5))
2147 ((calc-minibuffer-contains ".* \\'")
2148 (backward-delete-char 2))
2149 ((eq last-command 'calcDigit-start)
2150 (erase-buffer))
2151 (t (backward-delete-char 1)))
91e51f9a 2152 (if (= (calc-minibuffer-size) 0)
136211a9
EZ
2153 (progn
2154 (setq last-command-char 13)
bf77c646 2155 (calcDigit-nondigit))))
136211a9
EZ
2156
2157
2158
2159
2160
2161
2162
2163;;;; Arithmetic routines.
2164;;;
2165;;; An object as manipulated by one of these routines may take any of the
2166;;; following forms:
2167;;;
2168;;; integer An integer. For normalized numbers, this format
2169;;; is used only for -999999 ... 999999.
2170;;;
2171;;; (bigpos N0 N1 N2 ...) A big positive integer, N0 + N1*1000 + N2*10^6 ...
2172;;; (bigneg N0 N1 N2 ...) A big negative integer, - N0 - N1*1000 ...
2173;;; Each digit N is in the range 0 ... 999.
2174;;; Normalized, always at least three N present,
2175;;; and the most significant N is nonzero.
2176;;;
2177;;; (frac NUM DEN) A fraction. NUM and DEN are small or big integers.
2178;;; Normalized, DEN > 1.
2179;;;
2180;;; (float NUM EXP) A floating-point number, NUM * 10^EXP;
2181;;; NUM is a small or big integer, EXP is a small int.
2182;;; Normalized, NUM is not a multiple of 10, and
2183;;; abs(NUM) < 10^calc-internal-prec.
2184;;; Normalized zero is stored as (float 0 0).
2185;;;
2186;;; (cplx REAL IMAG) A complex number; REAL and IMAG are any of above.
2187;;; Normalized, IMAG is nonzero.
2188;;;
2189;;; (polar R THETA) Polar complex number. Normalized, R > 0 and THETA
2190;;; is neither zero nor 180 degrees (pi radians).
2191;;;
2192;;; (vec A B C ...) Vector of objects A, B, C, ... A matrix is a
2193;;; vector of vectors.
2194;;;
2195;;; (hms H M S) Angle in hours-minutes-seconds form. All three
2196;;; components have the same sign; H and M must be
2197;;; numerically integers; M and S are expected to
2198;;; lie in the range [0,60).
2199;;;
2200;;; (date N) A date or date/time object. N is an integer to
2201;;; store a date only, or a fraction or float to
2202;;; store a date and time.
2203;;;
2204;;; (sdev X SIGMA) Error form, X +/- SIGMA. When normalized,
2205;;; SIGMA > 0. X is any complex number and SIGMA
2206;;; is real numbers; or these may be symbolic
2207;;; expressions where SIGMA is assumed real.
2208;;;
2209;;; (intv MASK LO HI) Interval form. MASK is 0=(), 1=(], 2=[), or 3=[].
2210;;; LO and HI are any real numbers, or symbolic
2211;;; expressions which are assumed real, and LO < HI.
2212;;; For [LO..HI], if LO = HI normalization produces LO,
2213;;; and if LO > HI normalization produces [LO..LO).
2214;;; For other intervals, if LO > HI normalization
2215;;; sets HI equal to LO.
2216;;;
2217;;; (mod N M) Number modulo M. When normalized, 0 <= N < M.
2218;;; N and M are real numbers.
2219;;;
2220;;; (var V S) Symbolic variable. V is a Lisp symbol which
2221;;; represents the variable's visible name. S is
2222;;; the symbol which actually stores the variable's
2223;;; value: (var pi var-pi).
2224;;;
2225;;; In general, combining rational numbers in a calculation always produces
2226;;; a rational result, but if either argument is a float, result is a float.
2227
2228;;; In the following comments, [x y z] means result is x, args must be y, z,
2229;;; respectively, where the code letters are:
2230;;;
2231;;; O Normalized object (vector or number)
2232;;; V Normalized vector
2233;;; N Normalized number of any type
2234;;; N Normalized complex number
2235;;; R Normalized real number (float or rational)
2236;;; F Normalized floating-point number
2237;;; T Normalized rational number
2238;;; I Normalized integer
2239;;; B Normalized big integer
2240;;; S Normalized small integer
2241;;; D Digit (small integer, 0..999)
2242;;; L Normalized bignum digit list (without "bigpos" or "bigneg" symbol)
2243;;; or normalized vector element list (without "vec")
2244;;; P Predicate (truth value)
2245;;; X Any Lisp object
2246;;; Z "nil"
2247;;;
2248;;; Lower-case letters signify possibly un-normalized values.
2249;;; "L.D" means a cons of an L and a D.
2250;;; [N N; n n] means result will be normalized if argument is.
2251;;; Also, [Public] marks routines intended to be called from outside.
2252;;; [This notation has been neglected in many recent routines.]
2253
730576f3
CW
2254(defvar math-eval-rules-cache)
2255(defvar math-eval-rules-cache-other)
136211a9
EZ
2256;;; Reduce an object to canonical (normalized) form. [O o; Z Z] [Public]
2257(defun math-normalize (a)
2258 (cond
2259 ((not (consp a))
2260 (if (integerp a)
2261 (if (or (>= a 1000000) (<= a -1000000))
2262 (math-bignum a)
2263 a)
2264 a))
2265 ((eq (car a) 'bigpos)
2266 (if (eq (nth (1- (length a)) a) 0)
2267 (let* ((last (setq a (copy-sequence a))) (digs a))
2268 (while (setq digs (cdr digs))
2269 (or (eq (car digs) 0) (setq last digs)))
2270 (setcdr last nil)))
2271 (if (cdr (cdr (cdr a)))
2272 a
2273 (cond
2274 ((cdr (cdr a)) (+ (nth 1 a) (* (nth 2 a) 1000)))
2275 ((cdr a) (nth 1 a))
2276 (t 0))))
2277 ((eq (car a) 'bigneg)
2278 (if (eq (nth (1- (length a)) a) 0)
2279 (let* ((last (setq a (copy-sequence a))) (digs a))
2280 (while (setq digs (cdr digs))
2281 (or (eq (car digs) 0) (setq last digs)))
2282 (setcdr last nil)))
2283 (if (cdr (cdr (cdr a)))
2284 a
2285 (cond
2286 ((cdr (cdr a)) (- (+ (nth 1 a) (* (nth 2 a) 1000))))
2287 ((cdr a) (- (nth 1 a)))
2288 (t 0))))
2289 ((eq (car a) 'float)
2290 (math-make-float (math-normalize (nth 1 a)) (nth 2 a)))
2291 ((or (memq (car a) '(frac cplx polar hms date mod sdev intv vec var quote
2292 special-const calcFunc-if calcFunc-lambda
2293 calcFunc-quote calcFunc-condition
2294 calcFunc-evalto))
2295 (integerp (car a))
2296 (and (consp (car a)) (not (eq (car (car a)) 'lambda))))
2297 (calc-extensions)
2298 (math-normalize-fancy a))
2299 (t
2300 (or (and calc-simplify-mode
2301 (calc-extensions)
2302 (math-normalize-nonstandard))
2303 (let ((args (mapcar 'math-normalize (cdr a))))
2304 (or (condition-case err
2305 (let ((func (assq (car a) '( ( + . math-add )
2306 ( - . math-sub )
2307 ( * . math-mul )
2308 ( / . math-div )
2309 ( % . math-mod )
2310 ( ^ . math-pow )
2311 ( neg . math-neg )
2312 ( | . math-concat ) ))))
2313 (or (and var-EvalRules
2314 (progn
2315 (or (eq var-EvalRules math-eval-rules-cache-tag)
2316 (progn
2317 (calc-extensions)
2318 (math-recompile-eval-rules)))
2319 (and (or math-eval-rules-cache-other
2320 (assq (car a) math-eval-rules-cache))
2321 (math-apply-rewrites
2322 (cons (car a) args)
2323 (cdr math-eval-rules-cache)
2324 nil math-eval-rules-cache))))
2325 (if func
2326 (apply (cdr func) args)
2327 (and (or (consp (car a))
2328 (fboundp (car a))
2329 (and (not calc-extensions-loaded)
2330 (calc-extensions)
2331 (fboundp (car a))))
2332 (apply (car a) args)))))
2333 (wrong-number-of-arguments
2334 (calc-record-why "*Wrong number of arguments"
2335 (cons (car a) args))
2336 nil)
2337 (wrong-type-argument
2338 (or calc-next-why (calc-record-why "Wrong type of argument"
2339 (cons (car a) args)))
2340 nil)
2341 (args-out-of-range
2342 (calc-record-why "*Argument out of range" (cons (car a) args))
2343 nil)
2344 (inexact-result
2345 (calc-record-why "No exact representation for result"
2346 (cons (car a) args))
2347 nil)
2348 (math-overflow
2349 (calc-record-why "*Floating-point overflow occurred"
2350 (cons (car a) args))
2351 nil)
2352 (math-underflow
2353 (calc-record-why "*Floating-point underflow occurred"
2354 (cons (car a) args))
2355 nil)
2356 (void-variable
2357 (if (eq (nth 1 err) 'var-EvalRules)
2358 (progn
2359 (setq var-EvalRules nil)
2360 (math-normalize (cons (car a) args)))
2361 (calc-record-why "*Variable is void" (nth 1 err)))))
2362 (if (consp (car a))
2363 (math-dimension-error)
bf77c646 2364 (cons (car a) args))))))))
136211a9
EZ
2365
2366
2367
2368;;; True if A is a floating-point real or complex number. [P x] [Public]
2369(defun math-floatp (a)
2370 (cond ((eq (car-safe a) 'float) t)
2371 ((memq (car-safe a) '(cplx polar mod sdev intv))
2372 (or (math-floatp (nth 1 a))
2373 (math-floatp (nth 2 a))
2374 (and (eq (car a) 'intv) (math-floatp (nth 3 a)))))
2375 ((eq (car-safe a) 'date)
bf77c646 2376 (math-floatp (nth 1 a)))))
136211a9
EZ
2377
2378
2379
2380;;; Verify that A is a complete object and return A. [x x] [Public]
2381(defun math-check-complete (a)
2382 (cond ((integerp a) a)
2383 ((eq (car-safe a) 'incomplete)
2384 (calc-incomplete-error a))
2385 ((consp a) a)
bf77c646 2386 (t (error "Invalid data object encountered"))))
136211a9
EZ
2387
2388
2389
2390;;; Coerce integer A to be a bignum. [B S]
2391(defun math-bignum (a)
2392 (if (>= a 0)
2393 (cons 'bigpos (math-bignum-big a))
bf77c646 2394 (cons 'bigneg (math-bignum-big (- a)))))
136211a9
EZ
2395
2396(defun math-bignum-big (a) ; [L s]
2397 (if (= a 0)
2398 nil
bf77c646 2399 (cons (% a 1000) (math-bignum-big (/ a 1000)))))
136211a9
EZ
2400
2401
2402;;; Build a normalized floating-point number. [F I S]
2403(defun math-make-float (mant exp)
2404 (if (eq mant 0)
2405 '(float 0 0)
2406 (let* ((ldiff (- calc-internal-prec (math-numdigs mant))))
2407 (if (< ldiff 0)
2408 (setq mant (math-scale-rounding mant ldiff)
2409 exp (- exp ldiff))))
2410 (if (consp mant)
2411 (let ((digs (cdr mant)))
2412 (if (= (% (car digs) 10) 0)
2413 (progn
2414 (while (= (car digs) 0)
2415 (setq digs (cdr digs)
2416 exp (+ exp 3)))
2417 (while (= (% (car digs) 10) 0)
2418 (setq digs (math-div10-bignum digs)
2419 exp (1+ exp)))
2420 (setq mant (math-normalize (cons (car mant) digs))))))
2421 (while (= (% mant 10) 0)
2422 (setq mant (/ mant 10)
2423 exp (1+ exp))))
2424 (if (and (<= exp -4000000)
2425 (<= (+ exp (math-numdigs mant) -1) -4000000))
2426 (signal 'math-underflow nil)
2427 (if (and (>= exp 3000000)
2428 (>= (+ exp (math-numdigs mant) -1) 4000000))
2429 (signal 'math-overflow nil)
bf77c646 2430 (list 'float mant exp)))))
136211a9
EZ
2431
2432(defun math-div10-bignum (a) ; [l l]
2433 (if (cdr a)
2434 (cons (+ (/ (car a) 10) (* (% (nth 1 a) 10) 100))
2435 (math-div10-bignum (cdr a)))
bf77c646 2436 (list (/ (car a) 10))))
136211a9
EZ
2437
2438;;; Coerce A to be a float. [F N; V V] [Public]
2439(defun math-float (a)
2440 (cond ((Math-integerp a) (math-make-float a 0))
2441 ((eq (car a) 'frac) (math-div (math-float (nth 1 a)) (nth 2 a)))
2442 ((eq (car a) 'float) a)
2443 ((memq (car a) '(cplx polar vec hms date sdev mod))
2444 (cons (car a) (mapcar 'math-float (cdr a))))
bf77c646 2445 (t (math-float-fancy a))))
136211a9
EZ
2446
2447
2448(defun math-neg (a)
2449 (cond ((not (consp a)) (- a))
2450 ((eq (car a) 'bigpos) (cons 'bigneg (cdr a)))
2451 ((eq (car a) 'bigneg) (cons 'bigpos (cdr a)))
2452 ((memq (car a) '(frac float))
2453 (list (car a) (Math-integer-neg (nth 1 a)) (nth 2 a)))
2454 ((memq (car a) '(cplx vec hms date calcFunc-idn))
2455 (cons (car a) (mapcar 'math-neg (cdr a))))
bf77c646 2456 (t (math-neg-fancy a))))
136211a9
EZ
2457
2458
2459;;; Compute the number of decimal digits in integer A. [S I]
2460(defun math-numdigs (a)
2461 (if (consp a)
2462 (if (cdr a)
2463 (let* ((len (1- (length a)))
2464 (top (nth len a)))
2465 (+ (* len 3) (cond ((>= top 100) 0) ((>= top 10) -1) (t -2))))
2466 0)
2467 (cond ((>= a 100) (+ (math-numdigs (/ a 1000)) 3))
2468 ((>= a 10) 2)
2469 ((>= a 1) 1)
2470 ((= a 0) 0)
2471 ((> a -10) 1)
2472 ((> a -100) 2)
bf77c646 2473 (t (math-numdigs (- a))))))
136211a9
EZ
2474
2475;;; Multiply (with truncation toward 0) the integer A by 10^N. [I i S]
2476(defun math-scale-int (a n)
2477 (cond ((= n 0) a)
2478 ((> n 0) (math-scale-left a n))
bf77c646 2479 (t (math-normalize (math-scale-right a (- n))))))
136211a9
EZ
2480
2481(defun math-scale-left (a n) ; [I I S]
2482 (if (= n 0)
2483 a
2484 (if (consp a)
2485 (cons (car a) (math-scale-left-bignum (cdr a) n))
2486 (if (>= n 3)
2487 (if (or (>= a 1000) (<= a -1000))
2488 (math-scale-left (math-bignum a) n)
2489 (math-scale-left (* a 1000) (- n 3)))
2490 (if (= n 2)
2491 (if (or (>= a 10000) (<= a -10000))
2492 (math-scale-left (math-bignum a) 2)
2493 (* a 100))
2494 (if (or (>= a 100000) (<= a -100000))
2495 (math-scale-left (math-bignum a) 1)
bf77c646 2496 (* a 10)))))))
136211a9
EZ
2497
2498(defun math-scale-left-bignum (a n)
2499 (if (>= n 3)
2500 (while (>= (setq a (cons 0 a)
2501 n (- n 3)) 3)))
2502 (if (> n 0)
2503 (math-mul-bignum-digit a (if (= n 2) 100 10) 0)
bf77c646 2504 a))
136211a9
EZ
2505
2506(defun math-scale-right (a n) ; [i i S]
2507 (if (= n 0)
2508 a
2509 (if (consp a)
2510 (cons (car a) (math-scale-right-bignum (cdr a) n))
2511 (if (<= a 0)
2512 (if (= a 0)
2513 0
2514 (- (math-scale-right (- a) n)))
2515 (if (>= n 3)
2516 (while (and (> (setq a (/ a 1000)) 0)
2517 (>= (setq n (- n 3)) 3))))
2518 (if (= n 2)
2519 (/ a 100)
2520 (if (= n 1)
2521 (/ a 10)
bf77c646 2522 a))))))
136211a9
EZ
2523
2524(defun math-scale-right-bignum (a n) ; [L L S; l l S]
2525 (if (>= n 3)
2526 (setq a (nthcdr (/ n 3) a)
2527 n (% n 3)))
2528 (if (> n 0)
2529 (cdr (math-mul-bignum-digit a (if (= n 2) 10 100) 0))
bf77c646 2530 a))
136211a9
EZ
2531
2532;;; Multiply (with rounding) the integer A by 10^N. [I i S]
2533(defun math-scale-rounding (a n)
2534 (cond ((>= n 0)
2535 (math-scale-left a n))
2536 ((consp a)
2537 (math-normalize
2538 (cons (car a)
2539 (let ((val (if (< n -3)
2540 (math-scale-right-bignum (cdr a) (- -3 n))
2541 (if (= n -2)
2542 (math-mul-bignum-digit (cdr a) 10 0)
2543 (if (= n -1)
2544 (math-mul-bignum-digit (cdr a) 100 0)
2545 (cdr a)))))) ; n = -3
2546 (if (and val (>= (car val) 500))
2547 (if (cdr val)
2548 (if (eq (car (cdr val)) 999)
2549 (math-add-bignum (cdr val) '(1))
2550 (cons (1+ (car (cdr val))) (cdr (cdr val))))
2551 '(1))
2552 (cdr val))))))
2553 (t
2554 (if (< a 0)
2555 (- (math-scale-rounding (- a) n))
2556 (if (= n -1)
2557 (/ (+ a 5) 10)
bf77c646 2558 (/ (+ (math-scale-right a (- -1 n)) 5) 10))))))
136211a9
EZ
2559
2560
2561;;; Compute the sum of A and B. [O O O] [Public]
2562(defun math-add (a b)
2563 (or
2564 (and (not (or (consp a) (consp b)))
2565 (progn
2566 (setq a (+ a b))
2567 (if (or (<= a -1000000) (>= a 1000000))
2568 (math-bignum a)
2569 a)))
2570 (and (Math-zerop a) (not (eq (car-safe a) 'mod))
2571 (if (and (math-floatp a) (Math-ratp b)) (math-float b) b))
2572 (and (Math-zerop b) (not (eq (car-safe b) 'mod))
2573 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a))
2574 (and (Math-objvecp a) (Math-objvecp b)
2575 (or
2576 (and (Math-integerp a) (Math-integerp b)
2577 (progn
2578 (or (consp a) (setq a (math-bignum a)))
2579 (or (consp b) (setq b (math-bignum b)))
2580 (if (eq (car a) 'bigneg)
2581 (if (eq (car b) 'bigneg)
2582 (cons 'bigneg (math-add-bignum (cdr a) (cdr b)))
2583 (math-normalize
2584 (let ((diff (math-sub-bignum (cdr b) (cdr a))))
2585 (if (eq diff 'neg)
2586 (cons 'bigneg (math-sub-bignum (cdr a) (cdr b)))
2587 (cons 'bigpos diff)))))
2588 (if (eq (car b) 'bigneg)
2589 (math-normalize
2590 (let ((diff (math-sub-bignum (cdr a) (cdr b))))
2591 (if (eq diff 'neg)
2592 (cons 'bigneg (math-sub-bignum (cdr b) (cdr a)))
2593 (cons 'bigpos diff))))
2594 (cons 'bigpos (math-add-bignum (cdr a) (cdr b)))))))
2595 (and (Math-ratp a) (Math-ratp b)
2596 (calc-extensions)
2597 (calc-add-fractions a b))
2598 (and (Math-realp a) (Math-realp b)
2599 (progn
2600 (or (and (consp a) (eq (car a) 'float))
2601 (setq a (math-float a)))
2602 (or (and (consp b) (eq (car b) 'float))
2603 (setq b (math-float b)))
2604 (math-add-float a b)))
2605 (and (calc-extensions)
2606 (math-add-objects-fancy a b))))
2607 (and (calc-extensions)
bf77c646 2608 (math-add-symb-fancy a b))))
136211a9
EZ
2609
2610(defun math-add-bignum (a b) ; [L L L; l l l]
2611 (if a
2612 (if b
2613 (let* ((a (copy-sequence a)) (aa a) (carry nil) sum)
2614 (while (and aa b)
2615 (if carry
2616 (if (< (setq sum (+ (car aa) (car b))) 999)
2617 (progn
2618 (setcar aa (1+ sum))
2619 (setq carry nil))
2620 (setcar aa (+ sum -999)))
2621 (if (< (setq sum (+ (car aa) (car b))) 1000)
2622 (setcar aa sum)
2623 (setcar aa (+ sum -1000))
2624 (setq carry t)))
2625 (setq aa (cdr aa)
2626 b (cdr b)))
2627 (if carry
2628 (if b
2629 (nconc a (math-add-bignum b '(1)))
2630 (while (eq (car aa) 999)
2631 (setcar aa 0)
2632 (setq aa (cdr aa)))
2633 (if aa
2634 (progn
2635 (setcar aa (1+ (car aa)))
2636 a)
2637 (nconc a '(1))))
2638 (if b
2639 (nconc a b)
2640 a)))
2641 a)
bf77c646 2642 b))
136211a9
EZ
2643
2644(defun math-sub-bignum (a b) ; [l l l]
2645 (if b
2646 (if a
730576f3 2647 (let* ((a (copy-sequence a)) (aa a) (borrow nil) sum diff)
136211a9
EZ
2648 (while (and aa b)
2649 (if borrow
2650 (if (>= (setq diff (- (car aa) (car b))) 1)
2651 (progn
2652 (setcar aa (1- diff))
2653 (setq borrow nil))
2654 (setcar aa (+ diff 999)))
2655 (if (>= (setq diff (- (car aa) (car b))) 0)
2656 (setcar aa diff)
2657 (setcar aa (+ diff 1000))
2658 (setq borrow t)))
2659 (setq aa (cdr aa)
2660 b (cdr b)))
2661 (if borrow
2662 (progn
2663 (while (eq (car aa) 0)
2664 (setcar aa 999)
2665 (setq aa (cdr aa)))
2666 (if aa
2667 (progn
2668 (setcar aa (1- (car aa)))
2669 a)
2670 'neg))
2671 (while (eq (car b) 0)
2672 (setq b (cdr b)))
2673 (if b
2674 'neg
2675 a)))
2676 (while (eq (car b) 0)
2677 (setq b (cdr b)))
2678 (and b
2679 'neg))
bf77c646 2680 a))
136211a9
EZ
2681
2682(defun math-add-float (a b) ; [F F F]
2683 (let ((ediff (- (nth 2 a) (nth 2 b))))
2684 (if (>= ediff 0)
2685 (if (>= ediff (+ calc-internal-prec calc-internal-prec))
2686 a
2687 (math-make-float (math-add (nth 1 b)
2688 (if (eq ediff 0)
2689 (nth 1 a)
2690 (math-scale-left (nth 1 a) ediff)))
2691 (nth 2 b)))
2692 (if (>= (setq ediff (- ediff))
2693 (+ calc-internal-prec calc-internal-prec))
2694 b
2695 (math-make-float (math-add (nth 1 a)
2696 (math-scale-left (nth 1 b) ediff))
bf77c646 2697 (nth 2 a))))))
136211a9
EZ
2698
2699;;; Compute the difference of A and B. [O O O] [Public]
2700(defun math-sub (a b)
2701 (if (or (consp a) (consp b))
2702 (math-add a (math-neg b))
2703 (setq a (- a b))
2704 (if (or (<= a -1000000) (>= a 1000000))
2705 (math-bignum a)
bf77c646 2706 a)))
136211a9
EZ
2707
2708(defun math-sub-float (a b) ; [F F F]
2709 (let ((ediff (- (nth 2 a) (nth 2 b))))
2710 (if (>= ediff 0)
2711 (if (>= ediff (+ calc-internal-prec calc-internal-prec))
2712 a
2713 (math-make-float (math-add (Math-integer-neg (nth 1 b))
2714 (if (eq ediff 0)
2715 (nth 1 a)
2716 (math-scale-left (nth 1 a) ediff)))
2717 (nth 2 b)))
2718 (if (>= (setq ediff (- ediff))
2719 (+ calc-internal-prec calc-internal-prec))
2720 b
2721 (math-make-float (math-add (nth 1 a)
2722 (Math-integer-neg
2723 (math-scale-left (nth 1 b) ediff)))
bf77c646 2724 (nth 2 a))))))
136211a9
EZ
2725
2726
2727;;; Compute the product of A and B. [O O O] [Public]
2728(defun math-mul (a b)
2729 (or
2730 (and (not (consp a)) (not (consp b))
2731 (< a 1000) (> a -1000) (< b 1000) (> b -1000)
2732 (* a b))
2733 (and (Math-zerop a) (not (eq (car-safe b) 'mod))
2734 (if (Math-scalarp b)
2735 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
2736 (calc-extensions)
2737 (math-mul-zero a b)))
2738 (and (Math-zerop b) (not (eq (car-safe a) 'mod))
2739 (if (Math-scalarp a)
2740 (if (and (math-floatp a) (Math-ratp b)) (math-float b) b)
2741 (calc-extensions)
2742 (math-mul-zero b a)))
2743 (and (Math-objvecp a) (Math-objvecp b)
2744 (or
2745 (and (Math-integerp a) (Math-integerp b)
2746 (progn
2747 (or (consp a) (setq a (math-bignum a)))
2748 (or (consp b) (setq b (math-bignum b)))
2749 (math-normalize
2750 (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
2751 (if (cdr (cdr a))
2752 (if (cdr (cdr b))
2753 (math-mul-bignum (cdr a) (cdr b))
2754 (math-mul-bignum-digit (cdr a) (nth 1 b) 0))
2755 (math-mul-bignum-digit (cdr b) (nth 1 a) 0))))))
2756 (and (Math-ratp a) (Math-ratp b)
2757 (calc-extensions)
2758 (calc-mul-fractions a b))
2759 (and (Math-realp a) (Math-realp b)
2760 (progn
2761 (or (and (consp a) (eq (car a) 'float))
2762 (setq a (math-float a)))
2763 (or (and (consp b) (eq (car b) 'float))
2764 (setq b (math-float b)))
2765 (math-make-float (math-mul (nth 1 a) (nth 1 b))
2766 (+ (nth 2 a) (nth 2 b)))))
2767 (and (calc-extensions)
2768 (math-mul-objects-fancy a b))))
2769 (and (calc-extensions)
bf77c646 2770 (math-mul-symb-fancy a b))))
136211a9
EZ
2771
2772(defun math-infinitep (a &optional undir)
2773 (while (and (consp a) (memq (car a) '(* / neg)))
2774 (if (or (not (eq (car a) '*)) (math-infinitep (nth 1 a)))
2775 (setq a (nth 1 a))
2776 (setq a (nth 2 a))))
2777 (and (consp a)
2778 (eq (car a) 'var)
2779 (memq (nth 2 a) '(var-inf var-uinf var-nan))
2780 (if (and undir (eq (nth 2 a) 'var-inf))
2781 '(var uinf var-uinf)
bf77c646 2782 a)))
136211a9
EZ
2783
2784;;; Multiply digit lists A and B. [L L L; l l l]
2785(defun math-mul-bignum (a b)
2786 (and a b
2787 (let* ((sum (if (<= (car b) 1)
2788 (if (= (car b) 0)
2789 (list 0)
2790 (copy-sequence a))
2791 (math-mul-bignum-digit a (car b) 0)))
2792 (sump sum) c d aa ss prod)
2793 (while (setq b (cdr b))
2794 (setq ss (setq sump (or (cdr sump) (setcdr sump (list 0))))
2795 d (car b)
2796 c 0
2797 aa a)
2798 (while (progn
2799 (setcar ss (% (setq prod (+ (+ (car ss) (* (car aa) d))
2800 c)) 1000))
2801 (setq aa (cdr aa)))
2802 (setq c (/ prod 1000)
2803 ss (or (cdr ss) (setcdr ss (list 0)))))
2804 (if (>= prod 1000)
2805 (if (cdr ss)
2806 (setcar (cdr ss) (+ (/ prod 1000) (car (cdr ss))))
2807 (setcdr ss (list (/ prod 1000))))))
bf77c646 2808 sum)))
136211a9
EZ
2809
2810;;; Multiply digit list A by digit D. [L L D D; l l D D]
2811(defun math-mul-bignum-digit (a d c)
2812 (if a
2813 (if (<= d 1)
2814 (and (= d 1) a)
2815 (let* ((a (copy-sequence a)) (aa a) prod)
2816 (while (progn
2817 (setcar aa (% (setq prod (+ (* (car aa) d) c)) 1000))
2818 (cdr aa))
2819 (setq aa (cdr aa)
2820 c (/ prod 1000)))
2821 (if (>= prod 1000)
2822 (setcdr aa (list (/ prod 1000))))
2823 a))
2824 (and (> c 0)
bf77c646 2825 (list c))))
136211a9
EZ
2826
2827
2828;;; Compute the integer (quotient . remainder) of A and B, which may be
2829;;; small or big integers. Type and consistency of truncation is undefined
2830;;; if A or B is negative. B must be nonzero. [I.I I I] [Public]
2831(defun math-idivmod (a b)
2832 (if (eq b 0)
2833 (math-reject-arg a "*Division by zero"))
2834 (if (or (consp a) (consp b))
2835 (if (and (natnump b) (< b 1000))
2836 (let ((res (math-div-bignum-digit (cdr a) b)))
2837 (cons
2838 (math-normalize (cons (car a) (car res)))
2839 (cdr res)))
2840 (or (consp a) (setq a (math-bignum a)))
2841 (or (consp b) (setq b (math-bignum b)))
2842 (let ((res (math-div-bignum (cdr a) (cdr b))))
2843 (cons
2844 (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
2845 (car res)))
2846 (math-normalize (cons (car a) (cdr res))))))
bf77c646 2847 (cons (/ a b) (% a b))))
136211a9
EZ
2848
2849(defun math-quotient (a b) ; [I I I] [Public]
2850 (if (and (not (consp a)) (not (consp b)))
2851 (if (= b 0)
2852 (math-reject-arg a "*Division by zero")
2853 (/ a b))
2854 (if (and (natnump b) (< b 1000))
2855 (if (= b 0)
2856 (math-reject-arg a "*Division by zero")
2857 (math-normalize (cons (car a)
2858 (car (math-div-bignum-digit (cdr a) b)))))
2859 (or (consp a) (setq a (math-bignum a)))
2860 (or (consp b) (setq b (math-bignum b)))
2861 (let* ((alen (1- (length a)))
2862 (blen (1- (length b)))
2863 (d (/ 1000 (1+ (nth (1- blen) (cdr b)))))
2864 (res (math-div-bignum-big (math-mul-bignum-digit (cdr a) d 0)
2865 (math-mul-bignum-digit (cdr b) d 0)
2866 alen blen)))
2867 (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
bf77c646 2868 (car res)))))))
136211a9
EZ
2869
2870
2871;;; Divide a bignum digit list by another. [l.l l L]
2872;;; The following division algorithm is borrowed from Knuth vol. II, sec. 4.3.1
2873(defun math-div-bignum (a b)
2874 (if (cdr b)
2875 (let* ((alen (length a))
2876 (blen (length b))
2877 (d (/ 1000 (1+ (nth (1- blen) b))))
2878 (res (math-div-bignum-big (math-mul-bignum-digit a d 0)
2879 (math-mul-bignum-digit b d 0)
2880 alen blen)))
2881 (if (= d 1)
2882 res
2883 (cons (car res)
2884 (car (math-div-bignum-digit (cdr res) d)))))
2885 (let ((res (math-div-bignum-digit a (car b))))
bf77c646 2886 (cons (car res) (list (cdr res))))))
136211a9
EZ
2887
2888;;; Divide a bignum digit list by a digit. [l.D l D]
2889(defun math-div-bignum-digit (a b)
2890 (if a
2891 (let* ((res (math-div-bignum-digit (cdr a) b))
2892 (num (+ (* (cdr res) 1000) (car a))))
2893 (cons
2894 (cons (/ num b) (car res))
2895 (% num b)))
bf77c646 2896 '(nil . 0)))
136211a9
EZ
2897
2898(defun math-div-bignum-big (a b alen blen) ; [l.l l L]
2899 (if (< alen blen)
2900 (cons nil a)
2901 (let* ((res (math-div-bignum-big (cdr a) b (1- alen) blen))
2902 (num (cons (car a) (cdr res)))
2903 (res2 (math-div-bignum-part num b blen)))
2904 (cons
2905 (cons (car res2) (car res))
bf77c646 2906 (cdr res2)))))
136211a9
EZ
2907
2908(defun math-div-bignum-part (a b blen) ; a < b*1000 [D.l l L]
2909 (let* ((num (+ (* (or (nth blen a) 0) 1000) (or (nth (1- blen) a) 0)))
2910 (den (nth (1- blen) b))
2911 (guess (min (/ num den) 999)))
bf77c646 2912 (math-div-bignum-try a b (math-mul-bignum-digit b guess 0) guess)))
136211a9
EZ
2913
2914(defun math-div-bignum-try (a b c guess) ; [D.l l l D]
2915 (let ((rem (math-sub-bignum a c)))
2916 (if (eq rem 'neg)
2917 (math-div-bignum-try a b (math-sub-bignum c b) (1- guess))
bf77c646 2918 (cons guess rem))))
136211a9
EZ
2919
2920
2921;;; Compute the quotient of A and B. [O O N] [Public]
2922(defun math-div (a b)
2923 (or
2924 (and (Math-zerop b)
2925 (calc-extensions)
2926 (math-div-by-zero a b))
2927 (and (Math-zerop a) (not (eq (car-safe b) 'mod))
2928 (if (Math-scalarp b)
2929 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
2930 (calc-extensions)
2931 (math-div-zero a b)))
2932 (and (Math-objvecp a) (Math-objvecp b)
2933 (or
2934 (and (Math-integerp a) (Math-integerp b)
2935 (let ((q (math-idivmod a b)))
2936 (if (eq (cdr q) 0)
2937 (car q)
2938 (if calc-prefer-frac
2939 (progn
2940 (calc-extensions)
2941 (math-make-frac a b))
2942 (math-div-float (math-make-float a 0)
2943 (math-make-float b 0))))))
2944 (and (Math-ratp a) (Math-ratp b)
2945 (calc-extensions)
2946 (calc-div-fractions a b))
2947 (and (Math-realp a) (Math-realp b)
2948 (progn
2949 (or (and (consp a) (eq (car a) 'float))
2950 (setq a (math-float a)))
2951 (or (and (consp b) (eq (car b) 'float))
2952 (setq b (math-float b)))
2953 (math-div-float a b)))
2954 (and (calc-extensions)
2955 (math-div-objects-fancy a b))))
2956 (and (calc-extensions)
bf77c646 2957 (math-div-symb-fancy a b))))
136211a9
EZ
2958
2959(defun math-div-float (a b) ; [F F F]
2960 (let ((ldiff (max (- (1+ calc-internal-prec)
2961 (- (math-numdigs (nth 1 a)) (math-numdigs (nth 1 b))))
2962 0)))
2963 (math-make-float (math-quotient (math-scale-int (nth 1 a) ldiff) (nth 1 b))
bf77c646 2964 (- (- (nth 2 a) (nth 2 b)) ldiff))))
136211a9
EZ
2965
2966
2967
2968
730576f3 2969(defvar calc-selection-cache-entry)
136211a9
EZ
2970;;; Format the number A as a string. [X N; X Z] [Public]
2971(defun math-format-stack-value (entry)
2972 (setq calc-selection-cache-entry calc-selection-cache-default-entry)
2973 (let* ((a (car entry))
2974 (math-comp-selected (nth 2 entry))
2975 (c (cond ((null a) "<nil>")
2976 ((eq calc-display-raw t) (format "%s" a))
2977 ((stringp a) a)
cd012309 2978 ((eq a 'top-of-stack) (propertize "." 'font-lock-face 'bold))
136211a9
EZ
2979 (calc-prepared-composition
2980 calc-prepared-composition)
2981 ((and (Math-scalarp a)
2982 (memq calc-language '(nil flat unform))
2983 (null math-comp-selected))
2984 (math-format-number a))
2985 (t (calc-extensions)
2986 (math-compose-expr a 0))))
2987 (off (math-stack-value-offset c))
2988 s w)
2989 (and math-comp-selected (setq calc-any-selections t))
2990 (setq w (cdr off)
2991 off (car off))
cd012309
CW
2992 (when (> off 0)
2993 (setq c (math-comp-concat (make-string off ? ) c)))
136211a9
EZ
2994 (or (equal calc-left-label "")
2995 (setq c (math-comp-concat (if (eq a 'top-of-stack)
2996 (make-string (length calc-left-label) ? )
2997 calc-left-label)
2998 c)))
cd012309
CW
2999 (when calc-line-numbering
3000 (setq c (math-comp-concat (if (eq calc-language 'big)
2363bd8d
DK
3001 (if math-comp-selected
3002 '(tag t "1: ")
3003 "1: ")
cd012309
CW
3004 " ")
3005 c)))
3006 (unless (or (equal calc-right-label "")
3007 (eq a 'top-of-stack))
3008 (calc-extensions)
3009 (setq c (list 'horiz c
3010 (make-string (max (- w (math-comp-width c)
3011 (length calc-right-label)) 0) ? )
3012 '(break -1)
3013 calc-right-label)))
136211a9
EZ
3014 (setq s (if (stringp c)
3015 (if calc-display-raw
3016 (prin1-to-string c)
3017 c)
3018 (math-composition-to-string c w)))
cd012309
CW
3019 (when calc-language-output-filter
3020 (setq s (funcall calc-language-output-filter s)))
136211a9
EZ
3021 (if (eq calc-language 'big)
3022 (setq s (concat s "\n"))
cd012309 3023 (when calc-line-numbering
6a3ed064 3024 (setq s (concat "1:" (substring s 2)))))
136211a9 3025 (setcar (cdr entry) (calc-count-lines s))
bf77c646 3026 s))
136211a9
EZ
3027
3028(defun math-stack-value-offset (c)
3029 (let* ((num (if calc-line-numbering 4 0))
3030 (wid (calc-window-width))
3031 off)
3032 (if calc-display-just
3033 (progn
3034 (calc-extensions)
3035 (math-stack-value-offset-fancy))
3036 (setq off (or calc-display-origin 0))
cd012309
CW
3037 (when (integerp calc-line-breaking)
3038 (setq wid calc-line-breaking)))
136211a9 3039 (cons (max (- off (length calc-left-label)) 0)
bf77c646 3040 (+ wid num))))
136211a9
EZ
3041
3042(defun calc-count-lines (s)
3043 (let ((pos 0)
3044 (num 1))
730576f3
CW
3045 (while (setq pos (string-match "\n" s pos))
3046 (setq pos (1+ pos)
136211a9 3047 num (1+ num)))
bf77c646 3048 num))
136211a9
EZ
3049
3050(defun math-format-value (a &optional w)
3051 (if (and (Math-scalarp a)
3052 (memq calc-language '(nil flat unform)))
3053 (math-format-number a)
3054 (calc-extensions)
3055 (let ((calc-line-breaking nil))
bf77c646 3056 (math-composition-to-string (math-compose-expr a 0) w))))
136211a9
EZ
3057
3058(defun calc-window-width ()
3059 (if calc-embedded-info
3060 (let ((win (get-buffer-window (aref calc-embedded-info 0))))
31b85a14 3061 (1- (if win (window-width win) (frame-width))))
136211a9 3062 (- (window-width (get-buffer-window (current-buffer)))
bf77c646 3063 (if calc-line-numbering 5 1))))
136211a9
EZ
3064
3065(defun math-comp-concat (c1 c2)
3066 (if (and (stringp c1) (stringp c2))
3067 (concat c1 c2)
bf77c646 3068 (list 'horiz c1 c2)))
136211a9
EZ
3069
3070
3071
3072;;; Format an expression as a one-line string suitable for re-reading.
3073
3074(defun math-format-flat-expr (a prec)
3075 (cond
3076 ((or (not (or (consp a) (integerp a)))
3077 (eq calc-display-raw t))
3078 (let ((print-escape-newlines t))
3079 (concat "'" (prin1-to-string a))))
3080 ((Math-scalarp a)
3081 (let ((calc-group-digits nil)
3082 (calc-point-char ".")
3083 (calc-frac-format (if (> (length (car calc-frac-format)) 1)
3084 '("::" nil) '(":" nil)))
3085 (calc-complex-format nil)
3086 (calc-hms-format "%s@ %s' %s\"")
3087 (calc-language nil))
3088 (math-format-number a)))
3089 (t
3090 (calc-extensions)
bf77c646 3091 (math-format-flat-expr-fancy a prec))))
136211a9
EZ
3092
3093
3094
3095;;; Format a number as a string.
3096(defun math-format-number (a &optional prec) ; [X N] [Public]
3097 (cond
3098 ((eq calc-display-raw t) (format "%s" a))
3099 ((and (nth 1 calc-frac-format) (Math-integerp a))
3100 (calc-extensions)
3101 (math-format-number (math-adjust-fraction a)))
3102 ((integerp a)
3103 (if (not (or calc-group-digits calc-leading-zeros))
3104 (if (= calc-number-radix 10)
3105 (int-to-string a)
3106 (if (< a 0)
3107 (concat "-" (math-format-number (- a)))
3108 (calc-extensions)
3109 (if math-radix-explicit-format
3110 (if calc-radix-formatter
3111 (funcall calc-radix-formatter
3112 calc-number-radix
3113 (if (= calc-number-radix 2)
3114 (math-format-binary a)
3115 (math-format-radix a)))
3116 (format "%d#%s" calc-number-radix
3117 (if (= calc-number-radix 2)
3118 (math-format-binary a)
3119 (math-format-radix a))))
3120 (math-format-radix a))))
3121 (math-format-number (math-bignum a))))
3122 ((stringp a) a)
3123 ((not (consp a)) (prin1-to-string a))
3124 ((eq (car a) 'bigpos) (math-format-bignum (cdr a)))
3125 ((eq (car a) 'bigneg) (concat "-" (math-format-bignum (cdr a))))
3126 ((and (eq (car a) 'float) (= calc-number-radix 10))
3127 (if (Math-integer-negp (nth 1 a))
3128 (concat "-" (math-format-number (math-neg a)))
3129 (let ((mant (nth 1 a))
3130 (exp (nth 2 a))
3131 (fmt (car calc-float-format))
3132 (figs (nth 1 calc-float-format))
3133 (point calc-point-char)
3134 str)
3135 (if (and (eq fmt 'fix)
3136 (or (and (< figs 0) (setq figs (- figs)))
3137 (> (+ exp (math-numdigs mant)) (- figs))))
3138 (progn
3139 (setq mant (math-scale-rounding mant (+ exp figs))
3140 str (if (integerp mant)
3141 (int-to-string mant)
3142 (math-format-bignum-decimal (cdr mant))))
3143 (if (<= (length str) figs)
3144 (setq str (concat (make-string (1+ (- figs (length str))) ?0)
3145 str)))
3146 (if (> figs 0)
3147 (setq str (concat (substring str 0 (- figs)) point
3148 (substring str (- figs))))
3149 (setq str (concat str point)))
91da6442
CW
3150 (when calc-group-digits
3151 (require 'calc-ext)
3152 (setq str (math-group-float str))))
cd012309
CW
3153 (when (< figs 0)
3154 (setq figs (+ calc-internal-prec figs)))
3155 (when (> figs 0)
3156 (let ((adj (- figs (math-numdigs mant))))
3157 (when (< adj 0)
3158 (setq mant (math-scale-rounding mant adj)
3159 exp (- exp adj)))))
136211a9
EZ
3160 (setq str (if (integerp mant)
3161 (int-to-string mant)
3162 (math-format-bignum-decimal (cdr mant))))
3163 (let* ((len (length str))
3164 (dpos (+ exp len)))
3165 (if (and (eq fmt 'float)
3166 (<= dpos (+ calc-internal-prec calc-display-sci-high))
3167 (>= dpos (+ calc-display-sci-low 2)))
3168 (progn
3169 (cond
3170 ((= dpos 0)
3171 (setq str (concat "0" point str)))
3172 ((and (<= exp 0) (> dpos 0))
3173 (setq str (concat (substring str 0 dpos) point
3174 (substring str dpos))))
3175 ((> exp 0)
3176 (setq str (concat str (make-string exp ?0) point)))
3177 (t ; (< dpos 0)
3178 (setq str (concat "0" point
3179 (make-string (- dpos) ?0) str))))
91da6442
CW
3180 (when calc-group-digits
3181 (require 'calc-ext)
3182 (setq str (math-group-float str))))
136211a9
EZ
3183 (let* ((eadj (+ exp len))
3184 (scale (if (eq fmt 'eng)
3185 (1+ (math-mod (+ eadj 300002) 3))
3186 1)))
3187 (if (> scale (length str))
3188 (setq str (concat str (make-string (- scale (length str))
3189 ?0))))
3190 (if (< scale (length str))
3191 (setq str (concat (substring str 0 scale) point
3192 (substring str scale))))
91da6442
CW
3193 (when calc-group-digits
3194 (require 'calc-ext)
3195 (setq str (math-group-float str)))
136211a9
EZ
3196 (setq str (format (if (memq calc-language '(math maple))
3197 (if (and prec (> prec 191))
3198 "(%s*10.^%d)" "%s*10.^%d")
3199 "%se%d")
3200 str (- eadj scale)))))))
3201 str)))
3202 (t
3203 (calc-extensions)
bf77c646 3204 (math-format-number-fancy a prec))))
136211a9
EZ
3205
3206(defun math-format-bignum (a) ; [X L]
3207 (if (and (= calc-number-radix 10)
3208 (not calc-leading-zeros)
3209 (not calc-group-digits))
3210 (math-format-bignum-decimal a)
3211 (calc-extensions)
bf77c646 3212 (math-format-bignum-fancy a)))
136211a9
EZ
3213
3214(defun math-format-bignum-decimal (a) ; [X L]
3215 (if a
3216 (let ((s ""))
3217 (while (cdr (cdr a))
3218 (setq s (concat (format "%06d" (+ (* (nth 1 a) 1000) (car a))) s)
3219 a (cdr (cdr a))))
3220 (concat (int-to-string (+ (* (or (nth 1 a) 0) 1000) (car a))) s))
bf77c646 3221 "0"))
136211a9
EZ
3222
3223
3224
3225;;; Parse a simple number in string form. [N X] [Public]
3226(defun math-read-number (s)
3227 (math-normalize
3228 (cond
3229
3230 ;; Integers (most common case)
3231 ((string-match "\\` *\\([0-9]+\\) *\\'" s)
3232 (let ((digs (math-match-substring s 1)))
3233 (if (and (eq calc-language 'c)
3234 (> (length digs) 1)
3235 (eq (aref digs 0) ?0))
3236 (math-read-number (concat "8#" digs))
3237 (if (<= (length digs) 6)
3238 (string-to-int digs)
3239 (cons 'bigpos (math-read-bignum digs))))))
3240
3241 ;; Clean up the string if necessary
3242 ((string-match "\\`\\(.*\\)[ \t\n]+\\([^\001]*\\)\\'" s)
3243 (math-read-number (concat (math-match-substring s 1)
3244 (math-match-substring s 2))))
3245
3246 ;; Plus and minus signs
3247 ((string-match "^[-_+]\\(.*\\)$" s)
3248 (let ((val (math-read-number (math-match-substring s 1))))
3249 (and val (if (eq (aref s 0) ?+) val (math-neg val)))))
3250
3251 ;; Forms that require extensions module
3252 ((string-match "[^-+0-9eE.]" s)
3253 (calc-extensions)
3254 (math-read-number-fancy s))
3255
3256 ;; Decimal point
3257 ((string-match "^\\([0-9]*\\)\\.\\([0-9]*\\)$" s)
3258 (let ((int (math-match-substring s 1))
3259 (frac (math-match-substring s 2)))
3260 (let ((ilen (length int))
3261 (flen (length frac)))
3262 (let ((int (if (> ilen 0) (math-read-number int) 0))
3263 (frac (if (> flen 0) (math-read-number frac) 0)))
3264 (and int frac (or (> ilen 0) (> flen 0))
3265 (list 'float
3266 (math-add (math-scale-int int flen) frac)
3267 (- flen)))))))
3268
3269 ;; "e" notation
3270 ((string-match "^\\(.*\\)[eE]\\([-+]?[0-9]+\\)$" s)
3271 (let ((mant (math-match-substring s 1))
3272 (exp (math-match-substring s 2)))
3273 (let ((mant (if (> (length mant) 0) (math-read-number mant) 1))
3274 (exp (if (<= (length exp) (if (memq (aref exp 0) '(?+ ?-)) 8 7))
3275 (string-to-int exp))))
3276 (and mant exp (Math-realp mant) (> exp -4000000) (< exp 4000000)
3277 (let ((mant (math-float mant)))
3278 (list 'float (nth 1 mant) (+ (nth 2 mant) exp)))))))
3279
3280 ;; Syntax error!
bf77c646 3281 (t nil))))
136211a9
EZ
3282
3283(defun math-match-substring (s n)
3284 (if (match-beginning n)
3285 (substring s (match-beginning n) (match-end n))
bf77c646 3286 ""))
136211a9
EZ
3287
3288(defun math-read-bignum (s) ; [l X]
3289 (if (> (length s) 3)
3290 (cons (string-to-int (substring s -3))
3291 (math-read-bignum (substring s 0 -3)))
bf77c646 3292 (list (string-to-int s))))
136211a9
EZ
3293
3294
3295(defconst math-tex-ignore-words
3296 '( ("\\hbox") ("\\mbox") ("\\text") ("\\left") ("\\right")
3297 ("\\,") ("\\>") ("\\:") ("\\;") ("\\!") ("\\ ")
3298 ("\\quad") ("\\qquad") ("\\hfil") ("\\hfill")
3299 ("\\displaystyle") ("\\textstyle") ("\\dsize") ("\\tsize")
3300 ("\\scriptstyle") ("\\scriptscriptstyle") ("\\ssize") ("\\sssize")
3301 ("\\rm") ("\\bf") ("\\it") ("\\sl")
3302 ("\\roman") ("\\bold") ("\\italic") ("\\slanted")
3303 ("\\cal") ("\\mit") ("\\Cal") ("\\Bbb") ("\\frak") ("\\goth")
3304 ("\\evalto")
3305 ("\\matrix" mat) ("\\bmatrix" mat) ("\\pmatrix" mat)
3306 ("\\cr" punc ";") ("\\\\" punc ";") ("\\*" punc "*")
3307 ("\\{" punc "[") ("\\}" punc "]")
3308))
3309
3310(defconst math-eqn-ignore-words
3311 '( ("roman") ("bold") ("italic") ("mark") ("lineup") ("evalto")
3312 ("left" ("floor") ("ceil"))
3313 ("right" ("floor") ("ceil"))
3314 ("arc" ("sin") ("cos") ("tan") ("sinh") ("cosh") ("tanh"))
3315 ("size" n) ("font" n) ("fwd" n) ("back" n) ("up" n) ("down" n)
3316 ("above" punc ",")
3317))
3318
3319(defconst math-standard-opers
3320 '( ( "_" calcFunc-subscr 1200 1201 )
3321 ( "%" calcFunc-percent 1100 -1 )
3322 ( "u+" ident -1 1000 )
3323 ( "u-" neg -1 1000 197 )
3324 ( "u!" calcFunc-lnot -1 1000 )
3325 ( "mod" mod 400 400 185 )
3326 ( "+/-" sdev 300 300 185 )
3327 ( "!!" calcFunc-dfact 210 -1 )
3328 ( "!" calcFunc-fact 210 -1 )
3329 ( "^" ^ 201 200 )
3330 ( "**" ^ 201 200 )
3331 ( "*" * 196 195 )
3332 ( "2x" * 196 195 )
3333 ( "/" / 190 191 )
3334 ( "%" % 190 191 )
3335 ( "\\" calcFunc-idiv 190 191 )
3336 ( "+" + 180 181 )
3337 ( "-" - 180 181 )
3338 ( "|" | 170 171 )
3339 ( "<" calcFunc-lt 160 161 )
3340 ( ">" calcFunc-gt 160 161 )
3341 ( "<=" calcFunc-leq 160 161 )
3342 ( ">=" calcFunc-geq 160 161 )
3343 ( "=" calcFunc-eq 160 161 )
3344 ( "==" calcFunc-eq 160 161 )
3345 ( "!=" calcFunc-neq 160 161 )
3346 ( "&&" calcFunc-land 110 111 )
3347 ( "||" calcFunc-lor 100 101 )
3348 ( "?" (math-read-if) 91 90 )
3349 ( "!!!" calcFunc-pnot -1 85 )
3350 ( "&&&" calcFunc-pand 80 81 )
3351 ( "|||" calcFunc-por 75 76 )
3352 ( ":=" calcFunc-assign 51 50 )
3353 ( "::" calcFunc-condition 45 46 )
3354 ( "=>" calcFunc-evalto 40 41 )
f269b73e
CW
3355 ( "=>" calcFunc-evalto 40 -1 )))
3356(defvar math-expr-opers math-standard-opers)
136211a9
EZ
3357
3358;;;###autoload
3359(defun calc-grab-region (top bot arg)
3360 "Parse the region as a vector of numbers and push it on the Calculator stack."
3361 (interactive "r\nP")
3362 (calc-extensions)
bf77c646 3363 (calc-do-grab-region top bot arg))
136211a9
EZ
3364
3365;;;###autoload
3366(defun calc-grab-rectangle (top bot arg)
3367 "Parse a rectangle as a matrix of numbers and push it on the Calculator stack."
3368 (interactive "r\nP")
3369 (calc-extensions)
bf77c646 3370 (calc-do-grab-rectangle top bot arg))
136211a9
EZ
3371
3372(defun calc-grab-sum-down (top bot arg)
3373 "Parse a rectangle as a matrix of numbers and sum its columns."
3374 (interactive "r\nP")
3375 (calc-extensions)
bf77c646 3376 (calc-do-grab-rectangle top bot arg 'calcFunc-reduced))
136211a9
EZ
3377
3378(defun calc-grab-sum-across (top bot arg)
3379 "Parse a rectangle as a matrix of numbers and sum its rows."
3380 (interactive "r\nP")
3381 (calc-extensions)
bf77c646 3382 (calc-do-grab-rectangle top bot arg 'calcFunc-reducea))
136211a9
EZ
3383
3384
3385;;;###autoload
3386(defun calc-embedded (arg &optional end obeg oend)
3387 "Start Calc Embedded mode on the formula surrounding point."
3388 (interactive "P")
3389 (calc-extensions)
bf77c646 3390 (calc-do-embedded arg end obeg oend))
136211a9
EZ
3391
3392;;;###autoload
3393(defun calc-embedded-activate (&optional arg cbuf)
3394 "Scan the current editing buffer for all embedded := and => formulas.
3395Also looks for the equivalent TeX words, \\gets and \\evalto."
3396 (interactive "P")
bf77c646 3397 (calc-do-embedded-activate arg cbuf))
136211a9 3398
136211a9
EZ
3399(defun calc-user-invocation ()
3400 (interactive)
cd012309
CW
3401 (unless (stringp calc-invocation-macro)
3402 (error "Use `Z I' inside Calc to define a `M-# Z' keyboard macro"))
bf77c646 3403 (execute-kbd-macro calc-invocation-macro nil))
136211a9 3404
136211a9
EZ
3405;;; User-programmability.
3406
3407;;;###autoload
3408(defmacro defmath (func args &rest body) ; [Public]
3409 (calc-extensions)
bf77c646 3410 (math-do-defmath func args body))
136211a9 3411
136211a9
EZ
3412;;; Functions needed for Lucid Emacs support.
3413
3414(defun calc-read-key (&optional optkey)
3415 (cond (calc-emacs-type-lucid
3416 (let ((event (next-command-event)))
3417 (let ((key (event-to-character event t t)))
3418 (or key optkey (error "Expected a plain keystroke"))
3419 (cons key event))))
136211a9 3420 (t
cecd4c20 3421 (let ((key (read-event)))
bf77c646 3422 (cons key key)))))
136211a9
EZ
3423
3424(defun calc-unread-command (&optional input)
31b85a14
EZ
3425 (if (featurep 'xemacs)
3426 (setq unread-command-event
3427 (if (integerp input) (character-to-event input)
3428 (or input last-command-event)))
3429 (push (or input last-command-event) unread-command-events)))
136211a9
EZ
3430
3431(defun calc-clear-unread-commands ()
a1506d29 3432 (if (featurep 'xemacs)
136211a9 3433 (calc-emacs-type-lucid (setq unread-command-event nil))
31b85a14 3434 (setq unread-command-events nil)))
136211a9 3435
cd012309
CW
3436(when calc-always-load-extensions
3437 (calc-extensions)
3438 (calc-load-everything))
136211a9
EZ
3439
3440
3441(run-hooks 'calc-load-hook)
3442
ab5796a9 3443;;; arch-tag: 0c3b170c-4ce6-4eaf-8d9b-5834d1fe938f
bf77c646 3444;;; calc.el ends here