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