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