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