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