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