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