(math-compose-expr): Add new languages.
[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))
43f0c09e 243(declare-function math-normalize-nonstandard "calc-ext" ())
c68aaac5
JB
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.")
f479e32a
JB
970(defvar calc-lang-slash-idiv nil
971 "A list of languages in which / might represent integer division.")
972(defvar calc-lang-allow-underscores nil
973 "A list of languages which allow underscores in variable names.")
7707eaa6
JB
974(defvar calc-lang-allow-percentsigns nil
975 "A list of languages which allow percent signs in variable names.")
f479e32a
JB
976(defvar calc-lang-c-type-hex nil
977 "Languages in which octal and hex numbers are written with leading 0 and 0x,")
978(defvar calc-lang-brackets-are-subscripts nil
979 "Languages in which subscripts are indicated by brackets.")
980(defvar calc-lang-parens-are-subscripts nil
981 "Languages in which subscripts are indicated by parentheses.")
7b2cda38 982
730576f3 983(defvar calc-last-kill nil) ; Last number killed in calc-mode.
730576f3
CW
984(defvar calc-dollar-values nil) ; Values to be used for '$'.
985(defvar calc-dollar-used nil) ; Highest order of '$' that occurred.
986(defvar calc-hashes-used nil) ; Highest order of '#' that occurred.
987(defvar calc-quick-prev-results nil) ; Previous results from Quick Calc.
988(defvar calc-said-hello nil) ; Has welcome message been said yet?
989(defvar calc-executing-macro nil) ; Kbd macro executing from "K" key.
990(defvar calc-any-selections nil) ; Nil means no selections present.
991(defvar calc-help-phase 0) ; Count of consecutive "?" keystrokes.
992(defvar calc-full-help-flag nil) ; Executing calc-full-help?
993(defvar calc-refresh-count 0) ; Count of calc-refresh calls.
994(defvar calc-display-dirty nil)
995(defvar calc-prepared-composition nil)
996(defvar calc-selection-cache-default-entry nil)
997(defvar calc-embedded-info nil)
998(defvar calc-embedded-active nil)
999(defvar calc-standalone-flag nil)
1000(defvar var-EvalRules nil)
1001(defvar math-eval-rules-cache-tag t)
1002(defvar math-radix-explicit-format t)
1003(defvar math-expr-function-mapping nil)
1004(defvar math-expr-variable-mapping nil)
1005(defvar math-read-expr-quotes nil)
1006(defvar math-working-step nil)
1007(defvar math-working-step-2 nil)
1008(defvar var-i '(special-const (math-imaginary 1)))
1009(defvar var-pi '(special-const (math-pi)))
1010(defvar var-e '(special-const (math-e)))
1011(defvar var-phi '(special-const (math-phi)))
1012(defvar var-gamma '(special-const (math-gamma-const)))
1013(defvar var-Modes '(special-const (math-get-modes-vec)))
1014
2a78421d
JB
1015(mapc (lambda (v) (or (boundp v) (set v nil)))
1016 calc-local-var-list)
136211a9 1017
730576f3
CW
1018(defvar calc-mode-map
1019 (let ((map (make-keymap)))
1020 (suppress-keymap map t)
1021 (define-key map "+" 'calc-plus)
1022 (define-key map "-" 'calc-minus)
1023 (define-key map "*" 'calc-times)
1024 (define-key map "/" 'calc-divide)
1025 (define-key map "%" 'calc-mod)
1026 (define-key map "&" 'calc-inv)
1027 (define-key map "^" 'calc-power)
1028 (define-key map "\M-%" 'calc-percent)
1029 (define-key map "e" 'calcDigit-start)
1030 (define-key map "i" 'calc-info)
1031 (define-key map "n" 'calc-change-sign)
1032 (define-key map "q" 'calc-quit)
1033 (define-key map "Y" 'nil)
1034 (define-key map "Y?" 'calc-shift-Y-prefix-help)
1035 (define-key map "?" 'calc-help)
1036 (define-key map " " 'calc-enter)
1037 (define-key map "'" 'calc-algebraic-entry)
1038 (define-key map "$" 'calc-auto-algebraic-entry)
1039 (define-key map "\"" 'calc-auto-algebraic-entry)
1040 (define-key map "\t" 'calc-roll-down)
1041 (define-key map "\M-\t" 'calc-roll-up)
1042 (define-key map "\C-m" 'calc-enter)
1043 (define-key map "\M-\C-m" 'calc-last-args-stub)
1044 (define-key map "\C-j" 'calc-over)
1045
6a3ed064
SM
1046 (mapc (lambda (x) (define-key map (char-to-string x) 'undefined))
1047 "lOW")
1048 (mapc (lambda (x) (define-key map (char-to-string x) 'calc-missing-key))
1049 (concat "ABCDEFGHIJKLMNPQRSTUVXZabcdfghjkmoprstuvwxyz"
1050 ":\\|!()[]<>{},;=~`\C-k\M-k\C-w\M-w\C-y\C-_"))
1051 (mapc (lambda (x) (define-key map (char-to-string x) 'calcDigit-start))
1052 "_0123456789.#@")
730576f3 1053 map))
136211a9 1054
730576f3
CW
1055(defvar calc-digit-map
1056 (let ((map (make-keymap)))
6546555e 1057 (if (featurep 'xemacs)
136211a9
EZ
1058 (map-keymap (function
1059 (lambda (keys bind)
730576f3 1060 (define-key map keys
136211a9
EZ
1061 (if (eq bind 'undefined)
1062 'undefined 'calcDigit-nondigit))))
1063 calc-mode-map)
cecd4c20
JB
1064 (let ((cmap (nth 1 calc-mode-map))
1065 (dmap (nth 1 map))
136211a9
EZ
1066 (i 0))
1067 (while (< i 128)
1068 (aset dmap i
1069 (if (eq (aref cmap i) 'undefined)
1070 'undefined 'calcDigit-nondigit))
1071 (setq i (1+ i)))))
2a78421d
JB
1072 (mapc (lambda (x) (define-key map (char-to-string x) 'calcDigit-key))
1073 "_0123456789.e+-:n#@oh'\"mspM")
1074 (mapc (lambda (x) (define-key map (char-to-string x) 'calcDigit-letter))
136211a9 1075 "abcdfgijklqrtuvwxyzABCDEFGHIJKLNOPQRSTUVWXYZ")
730576f3
CW
1076 (define-key map "'" 'calcDigit-algebraic)
1077 (define-key map "`" 'calcDigit-edit)
1078 (define-key map "\C-g" 'abort-recursive-edit)
1079 map))
136211a9 1080
2a78421d
JB
1081(mapc (lambda (x)
1082 (condition-case err
1083 (progn
1084 (define-key calc-digit-map x 'calcDigit-backspace)
1085 (define-key calc-mode-map x 'calc-pop)
1086 (define-key calc-mode-map
1087 (if (vectorp x)
6546555e 1088 (if (featurep 'xemacs)
2a78421d
JB
1089 (if (= (length x) 1)
1090 (vector (if (consp (aref x 0))
1091 (cons 'meta (aref x 0))
1092 (list 'meta (aref x 0))))
1093 "\e\C-d")
1094 (vconcat "\e" x))
1095 (concat "\e" x))
1096 'calc-pop-above))
1097 (error nil)))
1098 (if calc-scan-for-dels
1099 (append (where-is-internal 'delete-backward-char global-map)
1100 (where-is-internal 'backward-delete-char global-map)
84b4b70d 1101 (where-is-internal 'backward-delete-char-untabify global-map)
2a78421d
JB
1102 '("\C-d"))
1103 '("\177" "\C-d")))
136211a9 1104
730576f3
CW
1105(defvar calc-dispatch-map
1106 (let ((map (make-keymap)))
2a78421d
JB
1107 (mapc (lambda (x)
1108 (define-key map (char-to-string (car x)) (cdr x))
1109 (when (string-match "abcdefhijklnopqrstuwxyz"
1110 (char-to-string (car x)))
1111 (define-key map (char-to-string (- (car x) ?a -1)) (cdr x)))
1112 (define-key map (format "\e%c" (car x)) (cdr x)))
1113 '( ( ?a . calc-embedded-activate )
1114 ( ?b . calc-big-or-small )
1115 ( ?c . calc )
1116 ( ?d . calc-embedded-duplicate )
1117 ( ?e . calc-embedded )
1118 ( ?f . calc-embedded-new-formula )
1119 ( ?g . calc-grab-region )
1120 ( ?h . calc-dispatch-help )
1121 ( ?i . calc-info )
1122 ( ?j . calc-embedded-select )
1123 ( ?k . calc-keypad )
1124 ( ?l . calc-load-everything )
1125 ( ?m . read-kbd-macro )
1126 ( ?n . calc-embedded-next )
1127 ( ?o . calc-other-window )
1128 ( ?p . calc-embedded-previous )
1129 ( ?q . quick-calc )
1130 ( ?r . calc-grab-rectangle )
1131 ( ?s . calc-info-summary )
1132 ( ?t . calc-tutorial )
1133 ( ?u . calc-embedded-update-formula )
1134 ( ?w . calc-embedded-word )
1135 ( ?x . calc-quit )
1136 ( ?y . calc-copy-to-buffer )
1137 ( ?z . calc-user-invocation )
1138 ( ?\' . calc-embedded-new-formula )
1139 ( ?\` . calc-embedded-edit )
1140 ( ?: . calc-grab-sum-down )
1141 ( ?_ . calc-grab-sum-across )
1142 ( ?0 . calc-reset )
1143 ( ?? . calc-dispatch-help )
1144 ( ?# . calc-same-interface )
1145 ( ?& . calc-same-interface )
1146 ( ?\\ . calc-same-interface )
1147 ( ?= . calc-same-interface )
1148 ( ?* . calc-same-interface )
1149 ( ?/ . calc-same-interface )
1150 ( ?+ . calc-same-interface )
1151 ( ?- . calc-same-interface ) ))
80f952a2 1152 map))
136211a9 1153
136211a9 1154;;;; (Autoloads here)
2a78421d 1155(mapc
730576f3 1156 (lambda (x) (dolist (func (cdr x)) (autoload func (car x))))
136211a9
EZ
1157 '(
1158
451d4c5c 1159 ("calc-aent" calc-alg-digit-entry calc-alg-entry
730576f3
CW
1160 calc-check-user-syntax calc-do-alg-entry calc-do-calc-eval
1161 calc-do-quick-calc calc-match-user-syntax math-build-parse-table
1162 math-find-user-tokens math-read-expr-list math-read-exprs math-read-if
5ff9dafd 1163 math-read-token math-remove-dashes math-read-preprocess-string)
136211a9 1164
451d4c5c
JB
1165 ("calc-embed" calc-do-embedded-activate)
1166
2a78421d 1167 ("calc-misc"
730576f3
CW
1168 calc-do-handle-whys calc-do-refresh calc-num-prefix-name
1169 calc-record-list calc-record-why calc-report-bug calc-roll-down-stack
1170 calc-roll-up-stack calc-temp-minibuffer-message calcFunc-floor
1171 calcFunc-inv calcFunc-trunc math-concat math-constp math-div2
1172 math-div2-bignum math-do-working math-evenp math-fixnatnump
1173 math-fixnump math-floor math-imod math-ipow math-looks-negp math-mod
1174 math-negp math-posp math-pow math-read-radix-digit math-reject-arg
1175 math-trunc math-zerop)))
1176
2a78421d 1177(mapc
730576f3 1178 (lambda (x) (dolist (cmd (cdr x)) (autoload cmd (car x) nil t)))
136211a9
EZ
1179 '(
1180
1181 ("calc-aent" calc-algebraic-entry calc-auto-algebraic-entry
730576f3 1182 calcDigit-algebraic calcDigit-edit)
136211a9
EZ
1183
1184 ("calc-misc" another-calc calc-big-or-small calc-dispatch-help
2a78421d 1185 calc-help calc-info calc-info-goto-node calc-info-summary calc-inv
9d3c486a 1186 calc-last-args-stub
730576f3
CW
1187 calc-missing-key calc-mod calc-other-window calc-over calc-percent
1188 calc-pop-above calc-power calc-roll-down calc-roll-up
1189 calc-shift-Y-prefix-help calc-tutorial calcDigit-letter
1190 report-calc-bug)))
136211a9
EZ
1191
1192
d24f83d4 1193;;;###autoload (define-key ctl-x-map "*" 'calc-dispatch)
136211a9
EZ
1194
1195;;;###autoload
1196(defun calc-dispatch (&optional arg)
f269b73e 1197 "Invoke the GNU Emacs Calculator. See `calc-dispatch-help' for details."
136211a9 1198 (interactive "P")
99992264 1199; (sit-for echo-keystrokes)
136211a9
EZ
1200 (condition-case err ; look for other keys bound to calc-dispatch
1201 (let ((keys (this-command-keys)))
cd012309
CW
1202 (unless (or (not (stringp keys))
1203 (string-match "\\`\C-u\\|\\`\e[-0-9#]\\|`[\M--\M-0-\M-9]" keys)
1204 (eq (lookup-key calc-dispatch-map keys) 'calc-same-interface))
1205 (when (and (string-match "\\`[\C-@-\C-_]" keys)
1206 (symbolp
1207 (lookup-key calc-dispatch-map (substring keys 0 1))))
1208 (define-key calc-dispatch-map (substring keys 0 1) nil))
1209 (define-key calc-dispatch-map keys 'calc-same-interface)))
136211a9 1210 (error nil))
bf77c646 1211 (calc-do-dispatch arg))
136211a9 1212
f269b73e 1213(defvar calc-dispatch-help nil)
136211a9
EZ
1214(defun calc-do-dispatch (arg)
1215 (let ((key (calc-read-key-sequence
1216 (if calc-dispatch-help
1217 "Calc options: Calc, Keypad, Quick, Embed; eXit; Info, Tutorial; Grab; ?=more"
1218 (format "%s (Type ? for a list of Calc options)"
1219 (key-description (this-command-keys))))
1220 calc-dispatch-map)))
1221 (setq key (lookup-key calc-dispatch-map key))
1222 (message "")
1223 (if key
1224 (progn
ce805efa 1225 (or (commandp key) (require 'calc-ext))
136211a9 1226 (call-interactively key))
bf77c646 1227 (beep))))
136211a9
EZ
1228
1229(defun calc-read-key-sequence (prompt map)
1230 (let ((prompt2 (format "%s " (key-description (this-command-keys))))
1231 (glob (current-global-map))
1232 (loc (current-local-map)))
274f1353 1233 (or (input-pending-p) (message "%s" prompt))
136211a9
EZ
1234 (let ((key (calc-read-key t)))
1235 (calc-unread-command (cdr key))
1236 (unwind-protect
1237 (progn
1238 (use-global-map map)
1239 (use-local-map nil)
7e1637c2 1240 (read-key-sequence nil))
136211a9 1241 (use-global-map glob)
bf77c646 1242 (use-local-map loc)))))
136211a9 1243
f5a3eb30 1244(defvar calc-alg-map) ; Defined in calc-ext.el
136211a9 1245
bd149d6e
JB
1246(defun calc-version ()
1247 "Return version of this version of Calc."
1248 (interactive)
274f1353 1249 (message "Calc version %s" calc-version))
bd149d6e 1250
136211a9
EZ
1251(defun calc-mode ()
1252 "Calculator major mode.
1253
1254This is an RPN calculator featuring arbitrary-precision integer, rational,
1255floating-point, complex, matrix, and symbolic arithmetic.
1256
1257RPN calculation: 2 RET 3 + produces 5.
1258Algebraic style: ' 2+3 RET produces 5.
1259
1260Basic operators are +, -, *, /, ^, & (reciprocal), % (modulo), n (change-sign).
1261
1262Press ? repeatedly for more complete help. Press `h i' to read the
1263Calc manual on-line, `h s' to read the summary, or `h t' for the tutorial.
1264
1265Notations: 3.14e6 3.14 * 10^6
1266 _23 negative number -23 (or type `23 n')
1267 17:3 the fraction 17/3
1268 5:2:3 the fraction 5 and 2/3
1269 16#12C the integer 12C base 16 = 300 base 10
1270 8#177:100 the fraction 177:100 base 8 = 127:64 base 10
1271 (2, 4) complex number 2 + 4i
1272 (2; 4) polar complex number (r; theta)
1273 [1, 2, 3] vector ([[1, 2], [3, 4]] is a matrix)
1274 [1 .. 4) semi-open interval, 1 <= x < 4
1275 2 +/- 3 (p key) number with mean 2, standard deviation 3
1276 2 mod 3 (M key) number 2 computed modulo 3
1277 <1 jan 91> Date form (enter using ' key)
1278
1279
1280\\{calc-mode-map}
1281"
1282 (interactive)
2a78421d
JB
1283 (mapc (function
1284 (lambda (v) (set-default v (symbol-value v)))) calc-local-var-list)
136211a9
EZ
1285 (kill-all-local-variables)
1286 (use-local-map (if (eq calc-algebraic-mode 'total)
ce805efa 1287 (progn (require 'calc-ext) calc-alg-map) calc-mode-map))
2a78421d 1288 (mapc (function (lambda (v) (make-local-variable v))) calc-local-var-list)
136211a9
EZ
1289 (make-local-variable 'overlay-arrow-position)
1290 (make-local-variable 'overlay-arrow-string)
558f9ba1 1291 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
136211a9
EZ
1292 (setq truncate-lines t)
1293 (setq buffer-read-only t)
1294 (setq major-mode 'calc-mode)
1295 (setq mode-name "Calculator")
1296 (setq calc-stack-top (length (or (memq (assq 'top-of-stack calc-stack)
1297 calc-stack)
1298 (setq calc-stack (list (list 'top-of-stack
1299 1 nil))))))
1300 (setq calc-stack-top (- (length calc-stack) calc-stack-top -1))
1301 (or calc-loaded-settings-file
f269b73e 1302 (null calc-settings-file)
a8aee43b 1303 (equal calc-settings-file user-init-file)
136211a9
EZ
1304 (progn
1305 (setq calc-loaded-settings-file t)
6bbfeec5 1306 (load (file-name-sans-extension calc-settings-file) t))) ; t = missing-ok
136211a9
EZ
1307 (let ((p command-line-args))
1308 (while p
1309 (and (equal (car p) "-f")
1310 (string-match "calc" (nth 1 p))
1311 (string-match "full" (nth 1 p))
1312 (setq calc-standalone-flag t))
1313 (setq p (cdr p))))
ebbdfa24 1314 (require 'calc-menu)
d74fa98c 1315 (run-mode-hooks 'calc-mode-hook)
136211a9
EZ
1316 (calc-refresh t)
1317 (calc-set-mode-line)
bf77c646 1318 (calc-check-defines))
136211a9 1319
f269b73e 1320(defvar calc-check-defines 'calc-check-defines) ; suitable for run-hooks
136211a9
EZ
1321(defun calc-check-defines ()
1322 (if (symbol-plist 'calc-define)
1323 (let ((plist (copy-sequence (symbol-plist 'calc-define))))
1324 (while (and plist (null (nth 1 plist)))
1325 (setq plist (cdr (cdr plist))))
1326 (if plist
1327 (save-excursion
ce805efa
JB
1328 (require 'calc-ext)
1329 (require 'calc-macs)
136211a9
EZ
1330 (set-buffer "*Calculator*")
1331 (while plist
1332 (put 'calc-define (car plist) nil)
1333 (eval (nth 1 plist))
1334 (setq plist (cdr (cdr plist))))
1335 ;; See if this has added any more calc-define properties.
1336 (calc-check-defines))
bf77c646 1337 (setplist 'calc-define nil)))))
136211a9
EZ
1338
1339(defun calc-trail-mode (&optional buf)
1340 "Calc Trail mode.
1341This mode is used by the *Calc Trail* buffer, which records all results
1342obtained by the GNU Emacs Calculator.
1343
1344Calculator commands beginning with the `t' key are used to manipulate
1345the Trail.
1346
1347This buffer uses the same key map as the *Calculator* buffer; calculator
1348commands given here will actually operate on the *Calculator* stack."
1349 (interactive)
1350 (fundamental-mode)
1351 (use-local-map calc-mode-map)
1352 (setq major-mode 'calc-trail-mode)
1353 (setq mode-name "Calc Trail")
1354 (setq truncate-lines t)
1355 (setq buffer-read-only t)
1356 (make-local-variable 'overlay-arrow-position)
1357 (make-local-variable 'overlay-arrow-string)
cd012309
CW
1358 (when buf
1359 (set (make-local-variable 'calc-main-buffer) buf))
1360 (when (= (buffer-size) 0)
1361 (let ((buffer-read-only nil))
802ed9b9 1362 (insert (propertize (concat "Emacs Calculator Trail\n")
cd012309 1363 'font-lock-face 'italic))))
d74fa98c 1364 (run-mode-hooks 'calc-trail-mode-hook))
136211a9
EZ
1365
1366(defun calc-create-buffer ()
1367 (set-buffer (get-buffer-create "*Calculator*"))
1368 (or (eq major-mode 'calc-mode)
1369 (calc-mode))
1370 (setq max-lisp-eval-depth (max max-lisp-eval-depth 1000))
cd012309 1371 (when calc-always-load-extensions
ce805efa 1372 (require 'calc-ext))
cd012309 1373 (when calc-language
ce805efa 1374 (require 'calc-ext)
cd012309 1375 (calc-set-language calc-language calc-language-option t)))
136211a9
EZ
1376
1377;;;###autoload
1378(defun calc (&optional arg full-display interactive)
1379 "The Emacs Calculator. Full documentation is listed under \"calc-mode\"."
577e1b74 1380 (interactive "P\ni\np")
136211a9 1381 (if arg
cd012309 1382 (unless (eq arg 0)
ce805efa 1383 (require 'calc-ext)
cd012309
CW
1384 (if (= (prefix-numeric-value arg) -1)
1385 (calc-grab-region (region-beginning) (region-end) nil)
1386 (when (= (prefix-numeric-value arg) -2)
1387 (calc-keypad))))
1388 (when (get-buffer-window "*Calc Keypad*")
1389 (calc-keypad)
1390 (set-buffer (window-buffer (selected-window))))
136211a9
EZ
1391 (if (eq major-mode 'calc-mode)
1392 (calc-quit)
1393 (let ((oldbuf (current-buffer)))
1394 (calc-create-buffer)
1395 (setq calc-was-keypad-mode nil)
1396 (if (or (eq full-display t)
1397 (and (null full-display) calc-full-mode))
1398 (switch-to-buffer (current-buffer) t)
1399 (if (get-buffer-window (current-buffer))
1400 (select-window (get-buffer-window (current-buffer)))
ed65ed86
JB
1401 (if calc-window-hook
1402 (run-hooks 'calc-window-hook)
1403 (let ((w (get-largest-window)))
1404 (if (and pop-up-windows
1405 (> (window-height w)
1406 (+ window-min-height calc-window-height 2)))
1407 (progn
1408 (setq w (split-window w
1409 (- (window-height w)
1410 calc-window-height 2)
1411 nil))
1412 (set-window-buffer w (current-buffer))
1413 (select-window w))
1414 (pop-to-buffer (current-buffer)))))))
136211a9
EZ
1415 (save-excursion
1416 (set-buffer (calc-trail-buffer))
1417 (and calc-display-trail
31b85a14 1418 (= (window-width) (frame-width))
136211a9 1419 (calc-trail-display 1 t)))
f269b73e 1420 (message "Welcome to the GNU Emacs Calculator! Press `?' or `h' for help, `q' to quit")
136211a9
EZ
1421 (run-hooks 'calc-start-hook)
1422 (and (windowp full-display)
1423 (window-point full-display)
1424 (select-window full-display))
1425 (calc-check-defines)
577e1b74 1426 (when (and calc-said-hello interactive)
cd012309
CW
1427 (sit-for 2)
1428 (message ""))
bf77c646 1429 (setq calc-said-hello t)))))
136211a9
EZ
1430
1431;;;###autoload
577e1b74 1432(defun full-calc (&optional interactive)
136211a9 1433 "Invoke the Calculator and give it a full-sized window."
577e1b74
JB
1434 (interactive "p")
1435 (calc nil t interactive))
136211a9
EZ
1436
1437(defun calc-same-interface (arg)
1438 "Invoke the Calculator using the most recent interface (calc or calc-keypad)."
1439 (interactive "P")
1440 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1441 (> (recursion-depth) 0))
1442 (exit-recursive-edit)
1443 (if (eq major-mode 'calc-edit-mode)
1444 (calc-edit-finish arg)
c84eeafa
JB
1445 (if calc-was-keypad-mode
1446 (calc-keypad)
1447 (calc arg calc-full-mode t)))))
136211a9 1448
577e1b74
JB
1449(defun calc-quit (&optional non-fatal interactive)
1450 (interactive "i\np")
136211a9
EZ
1451 (and calc-standalone-flag (not non-fatal)
1452 (save-buffers-kill-emacs nil))
1453 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1454 (> (recursion-depth) 0))
1455 (exit-recursive-edit))
1456 (if (eq major-mode 'calc-edit-mode)
1457 (calc-edit-cancel)
c84eeafa
JB
1458 (if (and interactive
1459 calc-embedded-info
1460 (eq (current-buffer) (aref calc-embedded-info 0)))
1461 (calc-embedded nil)
1462 (unless (eq major-mode 'calc-mode)
1463 (calc-create-buffer))
1464 (run-hooks 'calc-end-hook)
1465 (setq calc-undo-list nil calc-redo-list nil)
2a78421d
JB
1466 (mapc (function (lambda (v) (set-default v (symbol-value v))))
1467 calc-local-var-list)
c84eeafa
JB
1468 (let ((buf (current-buffer))
1469 (win (get-buffer-window (current-buffer)))
1470 (kbuf (get-buffer "*Calc Keypad*")))
1471 (delete-windows-on (calc-trail-buffer))
1472 (if (and win
1473 (< (window-height win) (1- (frame-height)))
1474 (= (window-width win) (frame-width)) ; avoid calc-keypad
1475 (not (get-buffer-window "*Calc Keypad*")))
1476 (setq calc-window-height (- (window-height win) 2)))
1477 (progn
1478 (delete-windows-on buf)
1479 (delete-windows-on kbuf))
1480 (bury-buffer buf)
1481 (bury-buffer calc-trail-buffer)
1482 (and kbuf (bury-buffer kbuf))))))
136211a9
EZ
1483
1484;;;###autoload
1485(defun quick-calc ()
1486 "Do a quick calculation in the minibuffer without invoking full Calculator."
1487 (interactive)
bf77c646 1488 (calc-do-quick-calc))
136211a9
EZ
1489
1490;;;###autoload
1491(defun calc-eval (str &optional separator &rest args)
1492 "Do a quick calculation and return the result as a string.
1493Return value will either be the formatted result in string form,
1494or a list containing a character position and an error message in string form."
bf77c646 1495 (calc-do-calc-eval str separator args))
136211a9
EZ
1496
1497;;;###autoload
577e1b74 1498(defun calc-keypad (&optional interactive)
136211a9
EZ
1499 "Invoke the Calculator in \"visual keypad\" mode.
1500This is most useful in the X window system.
1501In this mode, click on the Calc \"buttons\" using the left mouse button.
1502Or, position the cursor manually and do M-x calc-keypad-press."
577e1b74 1503 (interactive "p")
ce805efa 1504 (require 'calc-ext)
577e1b74 1505 (calc-do-keypad calc-full-mode interactive))
136211a9
EZ
1506
1507;;;###autoload
577e1b74 1508(defun full-calc-keypad (&optional interactive)
136211a9
EZ
1509 "Invoke the Calculator in full-screen \"visual keypad\" mode.
1510See calc-keypad for details."
577e1b74 1511 (interactive "p")
ce805efa 1512 (require 'calc-ext)
577e1b74 1513 (calc-do-keypad t interactive))
136211a9
EZ
1514
1515
f269b73e
CW
1516(defvar calc-aborted-prefix nil)
1517(defvar calc-start-time nil)
730576f3
CW
1518(defvar calc-command-flags)
1519(defvar calc-final-point-line)
1520(defvar calc-final-point-column)
136211a9
EZ
1521;;; Note that modifications to this function may break calc-pass-errors.
1522(defun calc-do (do-body &optional do-slow)
1523 (calc-check-defines)
1524 (let* ((calc-command-flags nil)
1525 (calc-start-time (and calc-timing (not calc-start-time)
ce805efa 1526 (require 'calc-ext)
136211a9
EZ
1527 (current-time-string)))
1528 (gc-cons-threshold (max gc-cons-threshold
730576f3
CW
1529 (if calc-timing 2000000 100000)))
1530 calc-final-point-line calc-final-point-column)
136211a9
EZ
1531 (setq calc-aborted-prefix "")
1532 (unwind-protect
1533 (condition-case err
1534 (save-excursion
1535 (if calc-embedded-info
1536 (calc-embedded-select-buffer)
1537 (calc-select-buffer))
1538 (and (eq calc-algebraic-mode 'total)
ce805efa 1539 (require 'calc-ext)
136211a9 1540 (use-local-map calc-alg-map))
f269b73e
CW
1541 (when (and do-slow calc-display-working-message)
1542 (message "Working...")
1543 (calc-set-command-flag 'clear-message))
136211a9
EZ
1544 (funcall do-body)
1545 (setq calc-aborted-prefix nil)
f269b73e
CW
1546 (when (memq 'renum-stack calc-command-flags)
1547 (calc-renumber-stack))
1548 (when (memq 'clear-message calc-command-flags)
1549 (message "")))
136211a9
EZ
1550 (error
1551 (if (and (eq (car err) 'error)
1552 (stringp (nth 1 err))
1553 (string-match "max-specpdl-size\\|max-lisp-eval-depth"
1554 (nth 1 err)))
f269b73e 1555 (error "Computation got stuck or ran too long. Type `M' to increase the limit")
136211a9
EZ
1556 (setq calc-aborted-prefix nil)
1557 (signal (car err) (cdr err)))))
f269b73e
CW
1558 (when calc-aborted-prefix
1559 (calc-record "<Aborted>" calc-aborted-prefix))
136211a9
EZ
1560 (and calc-start-time
1561 (let* ((calc-internal-prec 12)
1562 (calc-date-format nil)
1563 (end-time (current-time-string))
1564 (time (if (equal calc-start-time end-time)
1565 0
1566 (math-sub
1567 (calcFunc-unixtime (math-parse-date end-time) 0)
1568 (calcFunc-unixtime (math-parse-date calc-start-time)
1569 0)))))
1570 (if (math-lessp 1 time)
1571 (calc-record time "(t)"))))
1572 (or (memq 'no-align calc-command-flags)
1573 (eq major-mode 'calc-trail-mode)
1574 (calc-align-stack-window))
1575 (and (memq 'position-point calc-command-flags)
1576 (if (eq major-mode 'calc-mode)
1577 (progn
1578 (goto-line calc-final-point-line)
1579 (move-to-column calc-final-point-column))
730576f3 1580 (save-current-buffer
136211a9
EZ
1581 (calc-select-buffer)
1582 (goto-line calc-final-point-line)
1583 (move-to-column calc-final-point-column))))
f269b73e
CW
1584 (unless (memq 'keep-flags calc-command-flags)
1585 (save-excursion
1586 (calc-select-buffer)
1587 (setq calc-inverse-flag nil
1588 calc-hyperbolic-flag nil
1589 calc-keep-args-flag nil)))
1590 (when (memq 'do-edit calc-command-flags)
1591 (switch-to-buffer (get-buffer-create "*Calc Edit*")))
136211a9 1592 (calc-set-mode-line)
f269b73e
CW
1593 (when calc-embedded-info
1594 (calc-embedded-finish-command))))
bf77c646
CW
1595 (identity nil)) ; allow a GC after timing is done
1596
136211a9
EZ
1597
1598(defun calc-set-command-flag (f)
f269b73e
CW
1599 (unless (memq f calc-command-flags)
1600 (setq calc-command-flags (cons f calc-command-flags))))
136211a9
EZ
1601
1602(defun calc-select-buffer ()
1603 (or (eq major-mode 'calc-mode)
1604 (if calc-main-buffer
1605 (set-buffer calc-main-buffer)
1606 (let ((buf (get-buffer "*Calculator*")))
1607 (if buf
1608 (set-buffer buf)
bf77c646 1609 (error "Calculator buffer not available"))))))
136211a9
EZ
1610
1611(defun calc-cursor-stack-index (&optional index)
1612 (goto-char (point-max))
bf77c646 1613 (forward-line (- (calc-substack-height (or index 1)))))
136211a9
EZ
1614
1615(defun calc-stack-size ()
bf77c646 1616 (- (length calc-stack) calc-stack-top))
136211a9
EZ
1617
1618(defun calc-substack-height (n)
1619 (let ((sum 0)
1620 (stack calc-stack))
1621 (setq n (+ n calc-stack-top))
1622 (while (and (> n 0) stack)
1623 (setq sum (+ sum (nth 1 (car stack)))
1624 n (1- n)
1625 stack (cdr stack)))
bf77c646 1626 sum))
136211a9
EZ
1627
1628(defun calc-set-mode-line ()
1629 (save-excursion
1630 (calc-select-buffer)
1631 (let* ((fmt (car calc-float-format))
1632 (figs (nth 1 calc-float-format))
1633 (new-mode-string
1634 (format "Calc%s%s: %d %s %-14s"
1635 (if calc-embedded-info "Embed" "")
1636 (if (and (> (length (buffer-name)) 12)
1637 (equal (substring (buffer-name) 0 12)
1638 "*Calculator*"))
1639 (substring (buffer-name) 12)
1640 "")
1641 calc-internal-prec
1642 (capitalize (symbol-name calc-angle-mode))
1643 (concat
1644
1645 ;; Input-related modes
1646 (if (eq calc-algebraic-mode 'total) "Alg* "
1647 (if calc-algebraic-mode "Alg "
1648 (if calc-incomplete-algebraic-mode "Alg[( " "")))
1649
1650 ;; Computational modes
1651 (if calc-symbolic-mode "Symb " "")
1652 (cond ((eq calc-matrix-mode 'matrix) "Matrix ")
1653 ((integerp calc-matrix-mode)
1654 (format "Matrix%d " calc-matrix-mode))
bbcaa3e3 1655 ((eq calc-matrix-mode 'sqmatrix) "SqMatrix ")
136211a9
EZ
1656 ((eq calc-matrix-mode 'scalar) "Scalar ")
1657 (t ""))
1658 (if (eq calc-complex-mode 'polar) "Polar " "")
1659 (if calc-prefer-frac "Frac " "")
1660 (cond ((null calc-infinite-mode) "")
1661 ((eq calc-infinite-mode 1) "+Inf ")
1662 (t "Inf "))
1663 (cond ((eq calc-simplify-mode 'none) "NoSimp ")
1664 ((eq calc-simplify-mode 'num) "NumSimp ")
1665 ((eq calc-simplify-mode 'binary)
1666 (format "BinSimp%d " calc-word-size))
1667 ((eq calc-simplify-mode 'alg) "AlgSimp ")
1668 ((eq calc-simplify-mode 'ext) "ExtSimp ")
1669 ((eq calc-simplify-mode 'units) "UnitSimp ")
1670 (t ""))
1671
1672 ;; Display modes
1673 (cond ((= calc-number-radix 10) "")
1674 ((= calc-number-radix 2) "Bin ")
1675 ((= calc-number-radix 8) "Oct ")
1676 ((= calc-number-radix 16) "Hex ")
1677 (t (format "Radix%d " calc-number-radix)))
1678 (if calc-leading-zeros "Zero " "")
1679 (cond ((null calc-language) "")
da6b9bf4
JB
1680 ((get calc-language 'math-lang-name)
1681 (concat (get calc-language 'math-lang-name) " "))
136211a9
EZ
1682 (t (concat
1683 (capitalize (symbol-name calc-language))
1684 " ")))
1685 (cond ((eq fmt 'float)
1686 (if (zerop figs) "" (format "Norm%d " figs)))
1687 ((eq fmt 'fix) (format "Fix%d " figs))
1688 ((eq fmt 'sci)
1689 (if (zerop figs) "Sci " (format "Sci%d " figs)))
1690 ((eq fmt 'eng)
1691 (if (zerop figs) "Eng " (format "Eng%d " figs))))
1692 (cond ((not calc-display-just)
1693 (if calc-display-origin
1694 (format "Left%d " calc-display-origin) ""))
1695 ((eq calc-display-just 'right)
1696 (if calc-display-origin
1697 (format "Right%d " calc-display-origin)
1698 "Right "))
1699 (t
1700 (if calc-display-origin
1701 (format "Center%d " calc-display-origin)
1702 "Center ")))
1703 (cond ((integerp calc-line-breaking)
1704 (format "Wid%d " calc-line-breaking))
1705 (calc-line-breaking "")
1706 (t "Wide "))
1707
1708 ;; Miscellaneous other modes/indicators
1709 (if calc-assoc-selections "" "Break ")
1710 (cond ((eq calc-mode-save-mode 'save) "Save ")
1711 ((not calc-embedded-info) "")
1712 ((eq calc-mode-save-mode 'local) "Local ")
1713 ((eq calc-mode-save-mode 'edit) "LocEdit ")
1714 ((eq calc-mode-save-mode 'perm) "LocPerm ")
1715 ((eq calc-mode-save-mode 'global) "Global ")
1716 (t ""))
1717 (if calc-auto-recompute "" "Manual ")
1718 (if (and (fboundp 'calc-gnuplot-alive)
1719 (calc-gnuplot-alive)) "Graph " "")
1720 (if (and calc-embedded-info
1721 (> (calc-stack-size) 0)
1722 (calc-top 1 'sel)) "Sel " "")
1723 (if calc-display-dirty "Dirty " "")
1724 (if calc-inverse-flag "Inv " "")
1725 (if calc-hyperbolic-flag "Hyp " "")
1726 (if calc-keep-args-flag "Keep " "")
1727 (if (/= calc-stack-top 1) "Narrow " "")
1728 (apply 'concat calc-other-modes)))))
1729 (if (equal new-mode-string mode-line-buffer-identification)
1730 nil
1731 (setq mode-line-buffer-identification new-mode-string)
1732 (set-buffer-modified-p (buffer-modified-p))
bf77c646 1733 (and calc-embedded-info (calc-embedded-mode-line-change))))))
136211a9
EZ
1734
1735(defun calc-align-stack-window ()
1736 (if (eq major-mode 'calc-mode)
1737 (progn
1738 (let ((win (get-buffer-window (current-buffer))))
1739 (if win
1740 (progn
1741 (calc-cursor-stack-index 0)
1742 (vertical-motion (- 2 (window-height win)))
1743 (set-window-start win (point)))))
1744 (calc-cursor-stack-index 0)
1745 (if (looking-at " *\\.$")
1746 (goto-char (1- (match-end 0)))))
1747 (save-excursion
1748 (calc-select-buffer)
bf77c646 1749 (calc-align-stack-window))))
136211a9
EZ
1750
1751(defun calc-check-stack (n)
1752 (if (> n (calc-stack-size))
1753 (error "Too few elements on stack"))
1754 (if (< n 0)
bf77c646 1755 (error "Invalid argument")))
136211a9
EZ
1756
1757(defun calc-push-list (vals &optional m sels)
1758 (while vals
1759 (if calc-executing-macro
1760 (calc-push-list-in-macro vals m sels)
1761 (save-excursion
1762 (calc-select-buffer)
1763 (let* ((val (car vals))
1764 (entry (list val 1 (car sels)))
1765 (mm (+ (or m 1) calc-stack-top)))
1766 (calc-cursor-stack-index (1- (or m 1)))
1767 (if (> mm 1)
1768 (setcdr (nthcdr (- mm 2) calc-stack)
1769 (cons entry (nthcdr (1- mm) calc-stack)))
1770 (setq calc-stack (cons entry calc-stack)))
1771 (let ((buffer-read-only nil))
1772 (insert (math-format-stack-value entry) "\n"))
1773 (calc-record-undo (list 'push mm))
1774 (calc-set-command-flag 'renum-stack))))
1775 (setq vals (cdr vals)
bf77c646 1776 sels (cdr sels))))
136211a9
EZ
1777
1778(defun calc-pop-push-list (n vals &optional m sels)
1779 (if (and calc-any-selections (null sels))
1780 (calc-replace-selections n vals m)
1781 (calc-pop-stack n m sels)
bf77c646 1782 (calc-push-list vals m sels)))
136211a9
EZ
1783
1784(defun calc-pop-push-record-list (n prefix vals &optional m sels)
1785 (or (and (consp vals)
1786 (or (integerp (car vals))
1787 (consp (car vals))))
1788 (and vals (setq vals (list vals)
1789 sels (and sels (list sels)))))
1790 (calc-check-stack (+ n (or m 1) -1))
1791 (if prefix
1792 (if (cdr vals)
1793 (calc-record-list vals prefix)
1794 (calc-record (car vals) prefix)))
bf77c646 1795 (calc-pop-push-list n vals m sels))
136211a9
EZ
1796
1797(defun calc-enter-result (n prefix vals &optional m)
1798 (setq calc-aborted-prefix prefix)
1799 (if (and (consp vals)
1800 (or (integerp (car vals))
1801 (consp (car vals))))
1802 (setq vals (mapcar 'calc-normalize vals))
1803 (setq vals (calc-normalize vals)))
1804 (or (and (consp vals)
1805 (or (integerp (car vals))
1806 (consp (car vals))))
1807 (setq vals (list vals)))
1808 (if (equal vals '((nil)))
1809 (setq vals nil))
1810 (calc-pop-push-record-list n prefix vals m)
bf77c646 1811 (calc-handle-whys))
136211a9
EZ
1812
1813(defun calc-normalize (val)
1814 (if (memq calc-simplify-mode '(nil none num))
1815 (math-normalize val)
ce805efa 1816 (require 'calc-ext)
bf77c646 1817 (calc-normalize-fancy val)))
136211a9
EZ
1818
1819(defun calc-handle-whys ()
1820 (if calc-next-why
bf77c646 1821 (calc-do-handle-whys)))
136211a9
EZ
1822
1823
1824(defun calc-pop-stack (&optional n m sel-ok) ; pop N objs at level M of stack.
1825 (or n (setq n 1))
1826 (or m (setq m 1))
1827 (or calc-keep-args-flag
1828 (let ((mm (+ m calc-stack-top)))
1829 (if (and calc-any-selections (not sel-ok)
1830 (calc-top-selected n m))
1831 (calc-sel-error))
1832 (if calc-executing-macro
1833 (calc-pop-stack-in-macro n mm)
1834 (calc-record-undo (list 'pop mm (calc-top-list n m 'full)))
1835 (save-excursion
1836 (calc-select-buffer)
1837 (let ((buffer-read-only nil))
1838 (if (> mm 1)
1839 (progn
1840 (calc-cursor-stack-index (1- m))
1841 (let ((bot (point)))
1842 (calc-cursor-stack-index (+ n m -1))
1843 (delete-region (point) bot))
1844 (setcdr (nthcdr (- mm 2) calc-stack)
1845 (nthcdr (+ n mm -1) calc-stack)))
1846 (calc-cursor-stack-index n)
1847 (setq calc-stack (nthcdr n calc-stack))
1848 (delete-region (point) (point-max))))
bf77c646 1849 (calc-set-command-flag 'renum-stack))))))
136211a9 1850
730576f3 1851(defvar sel-mode)
136211a9
EZ
1852(defun calc-get-stack-element (x)
1853 (cond ((eq sel-mode 'entry)
1854 x)
1855 ((eq sel-mode 'sel)
1856 (nth 2 x))
1857 ((or (null (nth 2 x))
1858 (eq sel-mode 'full)
1859 (not calc-use-selections))
1860 (car x))
1861 (sel-mode
1862 (calc-sel-error))
bf77c646 1863 (t (nth 2 x))))
136211a9
EZ
1864
1865;; Get the Nth element of the stack (N=1 is the top element).
1866(defun calc-top (&optional n sel-mode)
1867 (or n (setq n 1))
1868 (calc-check-stack n)
bf77c646 1869 (calc-get-stack-element (nth (+ n calc-stack-top -1) calc-stack)))
136211a9
EZ
1870
1871(defun calc-top-n (&optional n sel-mode) ; in case precision has changed
bf77c646 1872 (math-check-complete (calc-normalize (calc-top n sel-mode))))
136211a9
EZ
1873
1874(defun calc-top-list (&optional n m sel-mode)
1875 (or n (setq n 1))
1876 (or m (setq m 1))
1877 (calc-check-stack (+ n m -1))
1878 (and (> n 0)
1879 (let ((top (copy-sequence (nthcdr (+ m calc-stack-top -1)
1880 calc-stack))))
1881 (setcdr (nthcdr (1- n) top) nil)
bf77c646 1882 (nreverse (mapcar 'calc-get-stack-element top)))))
136211a9
EZ
1883
1884(defun calc-top-list-n (&optional n m sel-mode)
1885 (mapcar 'math-check-complete
bf77c646 1886 (mapcar 'calc-normalize (calc-top-list n m sel-mode))))
136211a9
EZ
1887
1888
1889(defun calc-renumber-stack ()
1890 (if calc-line-numbering
1891 (save-excursion
1892 (calc-cursor-stack-index 0)
1893 (let ((lnum 1)
1894 (buffer-read-only nil)
1895 (stack (nthcdr calc-stack-top calc-stack)))
1896 (if (re-search-forward "^[0-9]+[:*]" nil t)
1897 (progn
1898 (beginning-of-line)
1899 (while (re-search-forward "^[0-9]+[:*]" nil t)
1900 (let ((buffer-read-only nil))
1901 (beginning-of-line)
1902 (delete-char 4)
1903 (insert " ")))
1904 (calc-cursor-stack-index 0)))
1905 (while (re-search-backward "^[0-9]+[:*]" nil t)
1906 (delete-char 4)
1907 (if (> lnum 999)
1908 (insert (format "%03d%s" (% lnum 1000)
1909 (if (and (nth 2 (car stack))
1910 calc-use-selections) "*" ":")))
1911 (let ((prefix (int-to-string lnum)))
1912 (insert prefix (if (and (nth 2 (car stack))
1913 calc-use-selections) "*" ":")
1914 (make-string (- 3 (length prefix)) 32))))
1915 (beginning-of-line)
1916 (setq lnum (1+ lnum)
1917 stack (cdr stack))))))
bf77c646 1918 (and calc-embedded-info (calc-embedded-stack-change)))
136211a9 1919
11bfbbd2 1920(defvar calc-any-evaltos nil)
136211a9
EZ
1921(defun calc-refresh (&optional align)
1922 (interactive)
1923 (and (eq major-mode 'calc-mode)
1924 (not calc-executing-macro)
1925 (let* ((buffer-read-only nil)
1926 (save-point (point))
1927 (save-mark (condition-case err (mark) (error nil)))
1928 (save-aligned (looking-at "\\.$"))
730576f3
CW
1929 (thing calc-stack)
1930 (calc-any-evaltos nil))
1931 (setq calc-any-selections nil)
136211a9 1932 (erase-buffer)
1501f4f6 1933 (when calc-show-banner
cd012309
CW
1934 (insert (propertize "--- Emacs Calculator Mode ---\n"
1935 'font-lock-face 'italic)))
136211a9
EZ
1936 (while thing
1937 (goto-char (point-min))
1501f4f6
MB
1938 (when calc-show-banner
1939 (forward-line 1))
136211a9
EZ
1940 (insert (math-format-stack-value (car thing)) "\n")
1941 (setq thing (cdr thing)))
1942 (calc-renumber-stack)
1943 (if calc-display-dirty
1944 (calc-wrapper (setq calc-display-dirty nil)))
1945 (and calc-any-evaltos calc-auto-recompute
1946 (calc-wrapper (calc-refresh-evaltos)))
1947 (if (or align save-aligned)
1948 (calc-align-stack-window)
1949 (goto-char save-point))
1950 (if save-mark (set-mark save-mark))))
1951 (and calc-embedded-info (not (eq major-mode 'calc-mode))
1952 (save-excursion
1953 (set-buffer (aref calc-embedded-info 1))
1954 (calc-refresh align)))
bf77c646 1955 (setq calc-refresh-count (1+ calc-refresh-count)))
136211a9 1956
136211a9
EZ
1957;;;; The Calc Trail buffer.
1958
1959(defun calc-check-trail-aligned ()
1960 (save-excursion
1961 (let ((win (get-buffer-window (current-buffer))))
1962 (and win
bf77c646 1963 (pos-visible-in-window-p (1- (point-max)) win)))))
136211a9
EZ
1964
1965(defun calc-trail-buffer ()
1966 (and (or (null calc-trail-buffer)
1967 (null (buffer-name calc-trail-buffer)))
1968 (save-excursion
1969 (setq calc-trail-buffer (get-buffer-create "*Calc Trail*"))
1970 (let ((buf (or (and (not (eq major-mode 'calc-mode))
1971 (get-buffer "*Calculator*"))
1972 (current-buffer))))
1973 (set-buffer calc-trail-buffer)
1974 (or (eq major-mode 'calc-trail-mode)
1975 (calc-trail-mode buf)))))
1976 (or (and calc-trail-pointer
1977 (eq (marker-buffer calc-trail-pointer) calc-trail-buffer))
1978 (save-excursion
1979 (set-buffer calc-trail-buffer)
1980 (goto-line 2)
1981 (setq calc-trail-pointer (point-marker))))
bf77c646 1982 calc-trail-buffer)
136211a9
EZ
1983
1984(defun calc-record (val &optional prefix)
1985 (setq calc-aborted-prefix nil)
1986 (or calc-executing-macro
1987 (let* ((mainbuf (current-buffer))
1988 (buf (calc-trail-buffer))
1989 (calc-display-raw nil)
1990 (calc-can-abbrev-vectors t)
1991 (fval (if val
1992 (if (stringp val)
1993 val
1994 (math-showing-full-precision
1995 (math-format-flat-expr val 0)))
1996 "")))
1997 (save-excursion
1998 (set-buffer buf)
1999 (let ((aligned (calc-check-trail-aligned))
2000 (buffer-read-only nil))
2001 (goto-char (point-max))
2002 (cond ((null prefix) (insert " "))
2003 ((and (> (length prefix) 4)
2004 (string-match " " prefix 4))
2005 (insert (substring prefix 0 4) " "))
2006 (t (insert (format "%4s " prefix))))
2007 (insert fval "\n")
2008 (let ((win (get-buffer-window buf)))
2009 (if (and aligned win (not (memq 'hold-trail calc-command-flags)))
2010 (calc-trail-here))
2011 (goto-char (1- (point-max))))))))
bf77c646 2012 val)
136211a9
EZ
2013
2014
577e1b74
JB
2015(defun calc-trail-display (flag &optional no-refresh interactive)
2016 (interactive "P\ni\np")
136211a9
EZ
2017 (let ((win (get-buffer-window (calc-trail-buffer))))
2018 (if (setq calc-display-trail
2019 (not (if flag (memq flag '(nil 0)) win)))
2020 (if (null win)
2021 (progn
ed65ed86
JB
2022 (if calc-trail-window-hook
2023 (run-hooks 'calc-trail-window-hook)
2024 (let ((w (split-window nil (/ (* (window-width) 2) 3) t)))
2025 (set-window-buffer w calc-trail-buffer)))
2026 (calc-wrapper
2027 (setq overlay-arrow-string calc-trail-overlay
2028 overlay-arrow-position calc-trail-pointer)
2029 (or no-refresh
2030 (if interactive
2031 (calc-do-refresh)
2032 (calc-refresh))))))
136211a9
EZ
2033 (if win
2034 (progn
2035 (delete-window win)
2036 (calc-wrapper
2037 (or no-refresh
577e1b74 2038 (if interactive
136211a9
EZ
2039 (calc-do-refresh)
2040 (calc-refresh))))))))
bf77c646 2041 calc-trail-buffer)
136211a9
EZ
2042
2043(defun calc-trail-here ()
2044 (interactive)
2045 (if (eq major-mode 'calc-trail-mode)
2046 (progn
2047 (beginning-of-line)
2048 (if (bobp)
2049 (forward-line 1)
2050 (if (eobp)
2051 (forward-line -1)))
2052 (if (or (bobp) (eobp))
2053 (setq overlay-arrow-position nil) ; trail is empty
2054 (set-marker calc-trail-pointer (point) (current-buffer))
2055 (setq calc-trail-overlay (concat (buffer-substring (point)
2056 (+ (point) 4))
2057 ">")
2058 overlay-arrow-string calc-trail-overlay
2059 overlay-arrow-position calc-trail-pointer)
2060 (forward-char 4)
2061 (let ((win (get-buffer-window (current-buffer))))
2062 (if win
2063 (save-excursion
2064 (forward-line (/ (window-height win) 2))
2065 (forward-line (- 1 (window-height win)))
2066 (set-window-start win (point))
2067 (set-window-point win (+ calc-trail-pointer 4))
2068 (set-buffer calc-main-buffer)
2069 (setq overlay-arrow-string calc-trail-overlay
2070 overlay-arrow-position calc-trail-pointer))))))
bf77c646 2071 (error "Not in Calc Trail buffer")))
136211a9
EZ
2072
2073
2074
2075
2076;;;; The Undo list.
2077
2078(defun calc-record-undo (rec)
2079 (or calc-executing-macro
2080 (if (memq 'undo calc-command-flags)
2081 (setq calc-undo-list (cons (cons rec (car calc-undo-list))
2082 (cdr calc-undo-list)))
2083 (setq calc-undo-list (cons (list rec) calc-undo-list)
2084 calc-redo-list nil)
bf77c646 2085 (calc-set-command-flag 'undo))))
136211a9
EZ
2086
2087
2088
2089
2090;;; Arithmetic commands.
2091
2092(defun calc-binary-op (name func arg &optional ident unary func2)
2093 (setq calc-aborted-prefix name)
2094 (if (null arg)
2095 (calc-enter-result 2 name (cons (or func2 func)
2096 (mapcar 'math-check-complete
2097 (calc-top-list 2))))
ce805efa 2098 (require 'calc-ext)
bf77c646 2099 (calc-binary-op-fancy name func arg ident unary)))
136211a9
EZ
2100
2101(defun calc-unary-op (name func arg &optional func2)
2102 (setq calc-aborted-prefix name)
2103 (if (null arg)
2104 (calc-enter-result 1 name (list (or func2 func)
2105 (math-check-complete (calc-top 1))))
ce805efa 2106 (require 'calc-ext)
bf77c646 2107 (calc-unary-op-fancy name func arg)))
136211a9
EZ
2108
2109
2110(defun calc-plus (arg)
2111 (interactive "P")
2112 (calc-slow-wrapper
bf77c646 2113 (calc-binary-op "+" 'calcFunc-add arg 0 nil '+)))
136211a9
EZ
2114
2115(defun calc-minus (arg)
2116 (interactive "P")
2117 (calc-slow-wrapper
bf77c646 2118 (calc-binary-op "-" 'calcFunc-sub arg 0 'neg '-)))
136211a9
EZ
2119
2120(defun calc-times (arg)
2121 (interactive "P")
2122 (calc-slow-wrapper
bf77c646 2123 (calc-binary-op "*" 'calcFunc-mul arg 1 nil '*)))
136211a9
EZ
2124
2125(defun calc-divide (arg)
2126 (interactive "P")
2127 (calc-slow-wrapper
bf77c646 2128 (calc-binary-op "/" 'calcFunc-div arg 0 'calcFunc-inv '/)))
136211a9 2129
431bbd67
JB
2130(defun calc-left-divide (arg)
2131 (interactive "P")
2132 (calc-slow-wrapper
2133 (calc-binary-op "ldiv" 'calcFunc-ldiv arg 0 nil nil)))
136211a9
EZ
2134
2135(defun calc-change-sign (arg)
2136 (interactive "P")
2137 (calc-wrapper
bf77c646 2138 (calc-unary-op "chs" 'neg arg)))
136211a9
EZ
2139
2140
2141
2142;;; Stack management commands.
2143
2144(defun calc-enter (n)
2145 (interactive "p")
2146 (calc-wrapper
2147 (cond ((< n 0)
2148 (calc-push-list (calc-top-list 1 (- n))))
2149 ((= n 0)
2150 (calc-push-list (calc-top-list (calc-stack-size))))
2151 (t
bf77c646 2152 (calc-push-list (calc-top-list n))))))
136211a9
EZ
2153
2154
2155(defun calc-pop (n)
2156 (interactive "P")
2157 (calc-wrapper
2158 (let* ((nn (prefix-numeric-value n))
2159 (top (and (null n) (calc-top 1))))
2160 (cond ((and (null n)
2161 (eq (car-safe top) 'incomplete)
2162 (> (length top) (if (eq (nth 1 top) 'intv) 3 2)))
2163 (calc-pop-push-list 1 (let ((tt (copy-sequence top)))
2164 (setcdr (nthcdr (- (length tt) 2) tt) nil)
2165 (list tt))))
2166 ((< nn 0)
2167 (if (and calc-any-selections
2168 (calc-top-selected 1 (- nn)))
2169 (calc-delete-selection (- nn))
2170 (calc-pop-stack 1 (- nn) t)))
2171 ((= nn 0)
2172 (calc-pop-stack (calc-stack-size) 1 t))
2173 (t
2174 (if (and calc-any-selections
2175 (= nn 1)
2176 (calc-top-selected 1 1))
2177 (calc-delete-selection 1)
bf77c646 2178 (calc-pop-stack nn)))))))
136211a9
EZ
2179
2180
2181
2182
2183;;;; Reading a number using the minibuffer.
730576f3
CW
2184(defvar calc-buffer)
2185(defvar calc-prev-char)
2186(defvar calc-prev-prev-char)
2187(defvar calc-digit-value)
136211a9
EZ
2188(defun calcDigit-start ()
2189 (interactive)
2190 (calc-wrapper
2191 (if (or calc-algebraic-mode
2192 (and (> calc-number-radix 14) (eq last-command-char ?e)))
2193 (calc-alg-digit-entry)
2194 (calc-unread-command)
2195 (setq calc-aborted-prefix nil)
2196 (let* ((calc-digit-value nil)
2197 (calc-prev-char nil)
2198 (calc-prev-prev-char nil)
2199 (calc-buffer (current-buffer))
6546555e 2200 (buf (if (featurep 'xemacs)
136211a9
EZ
2201 (catch 'calc-foo
2202 (catch 'execute-kbd-macro
2203 (throw 'calc-foo
2204 (read-from-minibuffer
2205 "Calc: " "" calc-digit-map)))
6546555e 2206 (error "XEmacs requires RET after %s"
136211a9
EZ
2207 "digit entry in kbd macro"))
2208 (let ((old-esc (lookup-key global-map "\e")))
2209 (unwind-protect
2210 (progn
2211 (define-key global-map "\e" nil)
2212 (read-from-minibuffer "Calc: " "" calc-digit-map))
2213 (define-key global-map "\e" old-esc))))))
2214 (or calc-digit-value (setq calc-digit-value (math-read-number buf)))
2215 (if (stringp calc-digit-value)
2216 (calc-alg-entry calc-digit-value)
2217 (if calc-digit-value
2218 (calc-push-list (list (calc-record (calc-normalize
2219 calc-digit-value))))))
2220 (if (eq calc-prev-char 'dots)
2221 (progn
ce805efa 2222 (require 'calc-ext)
bf77c646 2223 (calc-dots)))))))
136211a9 2224
91e51f9a
EZ
2225(defsubst calc-minibuffer-size ()
2226 (- (point-max) (minibuffer-prompt-end)))
2227
136211a9
EZ
2228(defun calcDigit-nondigit ()
2229 (interactive)
2230 ;; Exercise for the reader: Figure out why this is a good precaution!
2231 (or (boundp 'calc-buffer)
2232 (use-local-map minibuffer-local-map))
91e51f9a 2233 (let ((str (minibuffer-contents)))
136211a9
EZ
2234 (setq calc-digit-value (save-excursion
2235 (set-buffer calc-buffer)
2236 (math-read-number str))))
91e51f9a 2237 (if (and (null calc-digit-value) (> (calc-minibuffer-size) 0))
136211a9
EZ
2238 (progn
2239 (beep)
2240 (calc-temp-minibuffer-message " [Bad format]"))
2241 (or (memq last-command-char '(32 13))
2242 (progn (setq prefix-arg current-prefix-arg)
2243 (calc-unread-command (if (and (eq last-command-char 27)
2244 (>= last-input-char 128))
2245 last-input-char
2246 nil))))
bf77c646 2247 (exit-minibuffer)))
136211a9
EZ
2248
2249
2250(defun calc-minibuffer-contains (rex)
2251 (save-excursion
91e51f9a 2252 (goto-char (minibuffer-prompt-end))
bf77c646 2253 (looking-at rex)))
136211a9
EZ
2254
2255(defun calcDigit-key ()
2256 (interactive)
2257 (goto-char (point-max))
2258 (if (or (and (memq last-command-char '(?+ ?-))
2259 (> (buffer-size) 0)
2260 (/= (preceding-char) ?e))
2261 (and (memq last-command-char '(?m ?s))
2262 (not (calc-minibuffer-contains "[-+]?[0-9]+\\.?0*[@oh].*"))
2263 (not (calc-minibuffer-contains "[-+]?\\(1[1-9]\\|[2-9][0-9]\\)#.*"))))
2264 (calcDigit-nondigit)
2265 (if (calc-minibuffer-contains "\\([-+]?\\|.* \\)\\'")
2266 (cond ((memq last-command-char '(?. ?@)) (insert "0"))
2267 ((and (memq last-command-char '(?o ?h ?m))
2268 (not (calc-minibuffer-contains ".*#.*"))) (insert "0"))
2269 ((memq last-command-char '(?: ?e)) (insert "1"))
2270 ((eq last-command-char ?#)
2271 (insert (int-to-string calc-number-radix)))))
2272 (if (and (calc-minibuffer-contains "\\([-+]?[0-9]+#\\|[^:]*:\\)\\'")
2273 (eq last-command-char ?:))
2274 (insert "1"))
2275 (if (and (calc-minibuffer-contains "[-+]?[0-9]+#\\'")
2276 (eq last-command-char ?.))
2277 (insert "0"))
2278 (if (and (calc-minibuffer-contains "[-+]?0*\\([2-9]\\|1[0-4]\\)#\\'")
2279 (eq last-command-char ?e))
2280 (insert "1"))
2281 (if (or (and (memq last-command-char '(?h ?o ?m ?s ?p))
2282 (calc-minibuffer-contains ".*#.*"))
2283 (and (eq last-command-char ?e)
2284 (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2285 (and (eq last-command-char ?n)
2286 (calc-minibuffer-contains "[-+]?\\(2[4-9]\\|[3-9][0-9]\\)#.*")))
2287 (setq last-command-char (upcase last-command-char)))
2288 (cond
2289 ((memq last-command-char '(?_ ?n))
cd01f5b9 2290 (goto-char (minibuffer-prompt-end))
136211a9
EZ
2291 (if (and (search-forward " +/- " nil t)
2292 (not (search-forward "e" nil t)))
2293 (beep)
2294 (and (not (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2295 (search-forward "e" nil t))
2296 (if (looking-at "+")
2297 (delete-char 1))
2298 (if (looking-at "-")
2299 (delete-char 1)
2300 (insert "-")))
2301 (goto-char (point-max)))
2302 ((eq last-command-char ?p)
2303 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2304 (calc-minibuffer-contains ".*mod.*")
2305 (calc-minibuffer-contains ".*#.*")
2306 (calc-minibuffer-contains ".*[-+e:]\\'"))
2307 (beep)
2308 (if (not (calc-minibuffer-contains ".* \\'"))
2309 (insert " "))
2310 (insert "+/- ")))
2311 ((and (eq last-command-char ?M)
2312 (not (calc-minibuffer-contains
2313 "[-+]?\\(2[3-9]\\|[3-9][0-9]\\)#.*")))
2314 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2315 (calc-minibuffer-contains ".*mod *[^ ]+")
2316 (calc-minibuffer-contains ".*[-+e:]\\'"))
2317 (beep)
2318 (if (calc-minibuffer-contains ".*mod \\'")
2319 (if calc-previous-modulo
2320 (insert (math-format-flat-expr calc-previous-modulo 0))
2321 (beep))
2322 (if (not (calc-minibuffer-contains ".* \\'"))
2323 (insert " "))
2324 (insert "mod "))))
2325 (t
2326 (insert (char-to-string last-command-char))
2327 (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 2328 (let ((radix (string-to-number
136211a9
EZ
2329 (buffer-substring
2330 (match-beginning 2) (match-end 2)))))
2331 (and (>= radix 2)
2332 (<= radix 36)
2333 (or (memq last-command-char '(?# ?: ?. ?e ?+ ?-))
2334 (let ((dig (math-read-radix-digit
2335 (upcase last-command-char))))
2336 (and dig
2337 (< dig radix)))))))
91e51f9a
EZ
2338 (calc-minibuffer-contains
2339 "[-+]?\\(.*\\+/- *\\|.*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
2340 (if (and (memq last-command-char '(?@ ?o ?h ?\' ?m))
2341 (string-match " " calc-hms-format))
2342 (insert " "))
2343 (if (and (eq this-command last-command)
2344 (eq last-command-char ?.))
2345 (progn
ce805efa 2346 (require 'calc-ext)
136211a9
EZ
2347 (calc-digit-dots))
2348 (delete-backward-char 1)
2349 (beep)
2350 (calc-temp-minibuffer-message " [Bad format]"))))))
2351 (setq calc-prev-prev-char calc-prev-char
bf77c646 2352 calc-prev-char last-command-char))
136211a9
EZ
2353
2354
2355(defun calcDigit-backspace ()
2356 (interactive)
2357 (goto-char (point-max))
2358 (cond ((calc-minibuffer-contains ".* \\+/- \\'")
2359 (backward-delete-char 5))
2360 ((calc-minibuffer-contains ".* mod \\'")
2361 (backward-delete-char 5))
2362 ((calc-minibuffer-contains ".* \\'")
2363 (backward-delete-char 2))
2364 ((eq last-command 'calcDigit-start)
2365 (erase-buffer))
2366 (t (backward-delete-char 1)))
91e51f9a 2367 (if (= (calc-minibuffer-size) 0)
136211a9
EZ
2368 (progn
2369 (setq last-command-char 13)
bf77c646 2370 (calcDigit-nondigit))))
136211a9
EZ
2371
2372
2373
2374
2a78421d 2375(defconst math-bignum-digit-length
37cecd78 2376 (truncate (/ (log10 (/ most-positive-fixnum 2)) 2))
a6d107f1
JB
2377 "The length of a \"digit\" in Calc bignums.
2378If a big integer is of the form (bigpos N0 N1 ...), this is the
2379length of the allowable Emacs integers N0, N1,...
2380The value of 2*10^(2*MATH-BIGNUM-DIGIT-LENGTH) must be less than the
2381largest Emacs integer.")
136211a9 2382
2a78421d 2383(defconst math-bignum-digit-size
236e165a 2384 (expt 10 math-bignum-digit-length)
a6d107f1
JB
2385 "An upper bound for the size of the \"digit\"s in Calc bignums.")
2386
2a78421d 2387(defconst math-small-integer-size
236e165a 2388 (expt math-bignum-digit-size 2)
a6d107f1 2389 "An upper bound for the size of \"small integer\"s in Calc.")
136211a9
EZ
2390
2391
2392;;;; Arithmetic routines.
2393;;;
2394;;; An object as manipulated by one of these routines may take any of the
2395;;; following forms:
2396;;;
2397;;; integer An integer. For normalized numbers, this format
2a78421d 2398;;; is used only for
a6d107f1
JB
2399;;; negative math-small-integer-size + 1 to
2400;;; math-small-integer-size - 1
136211a9 2401;;;
2a78421d
JB
2402;;; (bigpos N0 N1 N2 ...) A big positive integer,
2403;;; N0 + N1*math-bignum-digit-size
a6d107f1 2404;;; + N2*(math-bignum-digit-size)^2 ...
2a78421d 2405;;; (bigneg N0 N1 N2 ...) A big negative integer,
a6d107f1 2406;;; - N0 - N1*math-bignum-digit-size ...
2a78421d 2407;;; Each digit N is in the range
a6d107f1 2408;;; 0 ... math-bignum-digit-size -1.
136211a9
EZ
2409;;; Normalized, always at least three N present,
2410;;; and the most significant N is nonzero.
2411;;;
2412;;; (frac NUM DEN) A fraction. NUM and DEN are small or big integers.
2413;;; Normalized, DEN > 1.
2414;;;
2415;;; (float NUM EXP) A floating-point number, NUM * 10^EXP;
2416;;; NUM is a small or big integer, EXP is a small int.
2417;;; Normalized, NUM is not a multiple of 10, and
2418;;; abs(NUM) < 10^calc-internal-prec.
2419;;; Normalized zero is stored as (float 0 0).
2420;;;
2421;;; (cplx REAL IMAG) A complex number; REAL and IMAG are any of above.
2422;;; Normalized, IMAG is nonzero.
2423;;;
2424;;; (polar R THETA) Polar complex number. Normalized, R > 0 and THETA
2425;;; is neither zero nor 180 degrees (pi radians).
2426;;;
2427;;; (vec A B C ...) Vector of objects A, B, C, ... A matrix is a
2428;;; vector of vectors.
2429;;;
2430;;; (hms H M S) Angle in hours-minutes-seconds form. All three
2431;;; components have the same sign; H and M must be
2432;;; numerically integers; M and S are expected to
2433;;; lie in the range [0,60).
2434;;;
2435;;; (date N) A date or date/time object. N is an integer to
2436;;; store a date only, or a fraction or float to
2437;;; store a date and time.
2438;;;
2439;;; (sdev X SIGMA) Error form, X +/- SIGMA. When normalized,
2440;;; SIGMA > 0. X is any complex number and SIGMA
2441;;; is real numbers; or these may be symbolic
2442;;; expressions where SIGMA is assumed real.
2443;;;
2444;;; (intv MASK LO HI) Interval form. MASK is 0=(), 1=(], 2=[), or 3=[].
2445;;; LO and HI are any real numbers, or symbolic
2446;;; expressions which are assumed real, and LO < HI.
2447;;; For [LO..HI], if LO = HI normalization produces LO,
2448;;; and if LO > HI normalization produces [LO..LO).
2449;;; For other intervals, if LO > HI normalization
2450;;; sets HI equal to LO.
2451;;;
2452;;; (mod N M) Number modulo M. When normalized, 0 <= N < M.
2453;;; N and M are real numbers.
2454;;;
2455;;; (var V S) Symbolic variable. V is a Lisp symbol which
2456;;; represents the variable's visible name. S is
2457;;; the symbol which actually stores the variable's
2458;;; value: (var pi var-pi).
2459;;;
2460;;; In general, combining rational numbers in a calculation always produces
2461;;; a rational result, but if either argument is a float, result is a float.
2462
2463;;; In the following comments, [x y z] means result is x, args must be y, z,
2464;;; respectively, where the code letters are:
2465;;;
2466;;; O Normalized object (vector or number)
2467;;; V Normalized vector
2468;;; N Normalized number of any type
2469;;; N Normalized complex number
2470;;; R Normalized real number (float or rational)
2471;;; F Normalized floating-point number
2472;;; T Normalized rational number
2473;;; I Normalized integer
2474;;; B Normalized big integer
2475;;; S Normalized small integer
2476;;; D Digit (small integer, 0..999)
2477;;; L Normalized bignum digit list (without "bigpos" or "bigneg" symbol)
2478;;; or normalized vector element list (without "vec")
2479;;; P Predicate (truth value)
2480;;; X Any Lisp object
2481;;; Z "nil"
2482;;;
2483;;; Lower-case letters signify possibly un-normalized values.
2484;;; "L.D" means a cons of an L and a D.
2485;;; [N N; n n] means result will be normalized if argument is.
2486;;; Also, [Public] marks routines intended to be called from outside.
2487;;; [This notation has been neglected in many recent routines.]
2488
730576f3
CW
2489(defvar math-eval-rules-cache)
2490(defvar math-eval-rules-cache-other)
136211a9 2491;;; Reduce an object to canonical (normalized) form. [O o; Z Z] [Public]
dc781413
JB
2492
2493(defvar math-normalize-a)
2494(defun math-normalize (math-normalize-a)
136211a9 2495 (cond
dc781413
JB
2496 ((not (consp math-normalize-a))
2497 (if (integerp math-normalize-a)
2a78421d 2498 (if (or (>= math-normalize-a math-small-integer-size)
a6d107f1 2499 (<= math-normalize-a (- math-small-integer-size)))
dc781413
JB
2500 (math-bignum math-normalize-a)
2501 math-normalize-a)
2502 math-normalize-a))
2503 ((eq (car math-normalize-a) 'bigpos)
2504 (if (eq (nth (1- (length math-normalize-a)) math-normalize-a) 0)
2a78421d 2505 (let* ((last (setq math-normalize-a
dc781413 2506 (copy-sequence math-normalize-a))) (digs math-normalize-a))
136211a9
EZ
2507 (while (setq digs (cdr digs))
2508 (or (eq (car digs) 0) (setq last digs)))
2509 (setcdr last nil)))
dc781413
JB
2510 (if (cdr (cdr (cdr math-normalize-a)))
2511 math-normalize-a
136211a9 2512 (cond
2a78421d
JB
2513 ((cdr (cdr math-normalize-a)) (+ (nth 1 math-normalize-a)
2514 (* (nth 2 math-normalize-a)
a6d107f1 2515 math-bignum-digit-size)))
dc781413 2516 ((cdr math-normalize-a) (nth 1 math-normalize-a))
136211a9 2517 (t 0))))
dc781413
JB
2518 ((eq (car math-normalize-a) 'bigneg)
2519 (if (eq (nth (1- (length math-normalize-a)) math-normalize-a) 0)
2a78421d 2520 (let* ((last (setq math-normalize-a (copy-sequence math-normalize-a)))
dc781413 2521 (digs math-normalize-a))
136211a9
EZ
2522 (while (setq digs (cdr digs))
2523 (or (eq (car digs) 0) (setq last digs)))
2524 (setcdr last nil)))
dc781413
JB
2525 (if (cdr (cdr (cdr math-normalize-a)))
2526 math-normalize-a
136211a9 2527 (cond
2a78421d
JB
2528 ((cdr (cdr math-normalize-a)) (- (+ (nth 1 math-normalize-a)
2529 (* (nth 2 math-normalize-a)
a6d107f1 2530 math-bignum-digit-size))))
dc781413 2531 ((cdr math-normalize-a) (- (nth 1 math-normalize-a)))
136211a9 2532 (t 0))))
dc781413 2533 ((eq (car math-normalize-a) 'float)
2a78421d 2534 (math-make-float (math-normalize (nth 1 math-normalize-a))
dc781413 2535 (nth 2 math-normalize-a)))
2a78421d 2536 ((or (memq (car math-normalize-a)
dc781413
JB
2537 '(frac cplx polar hms date mod sdev intv vec var quote
2538 special-const calcFunc-if calcFunc-lambda
2539 calcFunc-quote calcFunc-condition
2540 calcFunc-evalto))
2541 (integerp (car math-normalize-a))
2a78421d 2542 (and (consp (car math-normalize-a))
dc781413 2543 (not (eq (car (car math-normalize-a)) 'lambda))))
ce805efa 2544 (require 'calc-ext)
dc781413 2545 (math-normalize-fancy math-normalize-a))
136211a9
EZ
2546 (t
2547 (or (and calc-simplify-mode
ce805efa 2548 (require 'calc-ext)
136211a9 2549 (math-normalize-nonstandard))
dc781413 2550 (let ((args (mapcar 'math-normalize (cdr math-normalize-a))))
136211a9 2551 (or (condition-case err
2a78421d 2552 (let ((func
dc781413
JB
2553 (assq (car math-normalize-a) '( ( + . math-add )
2554 ( - . math-sub )
2555 ( * . math-mul )
2556 ( / . math-div )
2557 ( % . math-mod )
2558 ( ^ . math-pow )
2559 ( neg . math-neg )
2560 ( | . math-concat ) ))))
136211a9
EZ
2561 (or (and var-EvalRules
2562 (progn
2563 (or (eq var-EvalRules math-eval-rules-cache-tag)
2564 (progn
ce805efa 2565 (require 'calc-ext)
136211a9
EZ
2566 (math-recompile-eval-rules)))
2567 (and (or math-eval-rules-cache-other
2a78421d 2568 (assq (car math-normalize-a)
dc781413 2569 math-eval-rules-cache))
136211a9 2570 (math-apply-rewrites
dc781413 2571 (cons (car math-normalize-a) args)
136211a9
EZ
2572 (cdr math-eval-rules-cache)
2573 nil math-eval-rules-cache))))
2574 (if func
2575 (apply (cdr func) args)
dc781413
JB
2576 (and (or (consp (car math-normalize-a))
2577 (fboundp (car math-normalize-a))
ce805efa
JB
2578 (and (not (featurep 'calc-ext))
2579 (require 'calc-ext)
dc781413
JB
2580 (fboundp (car math-normalize-a))))
2581 (apply (car math-normalize-a) args)))))
136211a9
EZ
2582 (wrong-number-of-arguments
2583 (calc-record-why "*Wrong number of arguments"
dc781413 2584 (cons (car math-normalize-a) args))
136211a9
EZ
2585 nil)
2586 (wrong-type-argument
2a78421d 2587 (or calc-next-why
dc781413
JB
2588 (calc-record-why "Wrong type of argument"
2589 (cons (car math-normalize-a) args)))
136211a9
EZ
2590 nil)
2591 (args-out-of-range
2a78421d 2592 (calc-record-why "*Argument out of range"
dc781413 2593 (cons (car math-normalize-a) args))
136211a9
EZ
2594 nil)
2595 (inexact-result
2596 (calc-record-why "No exact representation for result"
dc781413 2597 (cons (car math-normalize-a) args))
136211a9
EZ
2598 nil)
2599 (math-overflow
2600 (calc-record-why "*Floating-point overflow occurred"
dc781413 2601 (cons (car math-normalize-a) args))
136211a9
EZ
2602 nil)
2603 (math-underflow
2604 (calc-record-why "*Floating-point underflow occurred"
dc781413 2605 (cons (car math-normalize-a) args))
136211a9
EZ
2606 nil)
2607 (void-variable
2608 (if (eq (nth 1 err) 'var-EvalRules)
2609 (progn
2610 (setq var-EvalRules nil)
dc781413 2611 (math-normalize (cons (car math-normalize-a) args)))
136211a9 2612 (calc-record-why "*Variable is void" (nth 1 err)))))
dc781413 2613 (if (consp (car math-normalize-a))
136211a9 2614 (math-dimension-error)
dc781413 2615 (cons (car math-normalize-a) args))))))))
136211a9
EZ
2616
2617
2618
2619;;; True if A is a floating-point real or complex number. [P x] [Public]
2620(defun math-floatp (a)
2621 (cond ((eq (car-safe a) 'float) t)
2622 ((memq (car-safe a) '(cplx polar mod sdev intv))
2623 (or (math-floatp (nth 1 a))
2624 (math-floatp (nth 2 a))
2625 (and (eq (car a) 'intv) (math-floatp (nth 3 a)))))
2626 ((eq (car-safe a) 'date)
bf77c646 2627 (math-floatp (nth 1 a)))))
136211a9
EZ
2628
2629
2630
2631;;; Verify that A is a complete object and return A. [x x] [Public]
2632(defun math-check-complete (a)
2633 (cond ((integerp a) a)
2634 ((eq (car-safe a) 'incomplete)
2635 (calc-incomplete-error a))
2636 ((consp a) a)
bf77c646 2637 (t (error "Invalid data object encountered"))))
136211a9
EZ
2638
2639
2640
2641;;; Coerce integer A to be a bignum. [B S]
2642(defun math-bignum (a)
2643 (if (>= a 0)
2644 (cons 'bigpos (math-bignum-big a))
bf77c646 2645 (cons 'bigneg (math-bignum-big (- a)))))
136211a9
EZ
2646
2647(defun math-bignum-big (a) ; [L s]
2648 (if (= a 0)
2649 nil
2a78421d 2650 (cons (% a math-bignum-digit-size)
a6d107f1 2651 (math-bignum-big (/ a math-bignum-digit-size)))))
136211a9
EZ
2652
2653
2654;;; Build a normalized floating-point number. [F I S]
2655(defun math-make-float (mant exp)
2656 (if (eq mant 0)
2657 '(float 0 0)
2658 (let* ((ldiff (- calc-internal-prec (math-numdigs mant))))
2659 (if (< ldiff 0)
2660 (setq mant (math-scale-rounding mant ldiff)
2661 exp (- exp ldiff))))
2662 (if (consp mant)
2663 (let ((digs (cdr mant)))
2664 (if (= (% (car digs) 10) 0)
2665 (progn
2666 (while (= (car digs) 0)
2667 (setq digs (cdr digs)
a6d107f1 2668 exp (+ exp math-bignum-digit-length)))
136211a9
EZ
2669 (while (= (% (car digs) 10) 0)
2670 (setq digs (math-div10-bignum digs)
2671 exp (1+ exp)))
2672 (setq mant (math-normalize (cons (car mant) digs))))))
2673 (while (= (% mant 10) 0)
2674 (setq mant (/ mant 10)
2675 exp (1+ exp))))
2676 (if (and (<= exp -4000000)
2677 (<= (+ exp (math-numdigs mant) -1) -4000000))
2678 (signal 'math-underflow nil)
2679 (if (and (>= exp 3000000)
2680 (>= (+ exp (math-numdigs mant) -1) 4000000))
2681 (signal 'math-overflow nil)
bf77c646 2682 (list 'float mant exp)))))
136211a9
EZ
2683
2684(defun math-div10-bignum (a) ; [l l]
2685 (if (cdr a)
2a78421d 2686 (cons (+ (/ (car a) 10) (* (% (nth 1 a) 10)
a6d107f1 2687 (expt 10 (1- math-bignum-digit-length))))
136211a9 2688 (math-div10-bignum (cdr a)))
bf77c646 2689 (list (/ (car a) 10))))
136211a9
EZ
2690
2691;;; Coerce A to be a float. [F N; V V] [Public]
2692(defun math-float (a)
2693 (cond ((Math-integerp a) (math-make-float a 0))
2694 ((eq (car a) 'frac) (math-div (math-float (nth 1 a)) (nth 2 a)))
2695 ((eq (car a) 'float) a)
2696 ((memq (car a) '(cplx polar vec hms date sdev mod))
2697 (cons (car a) (mapcar 'math-float (cdr a))))
bf77c646 2698 (t (math-float-fancy a))))
136211a9
EZ
2699
2700
2701(defun math-neg (a)
2702 (cond ((not (consp a)) (- a))
2703 ((eq (car a) 'bigpos) (cons 'bigneg (cdr a)))
2704 ((eq (car a) 'bigneg) (cons 'bigpos (cdr a)))
2705 ((memq (car a) '(frac float))
2706 (list (car a) (Math-integer-neg (nth 1 a)) (nth 2 a)))
2707 ((memq (car a) '(cplx vec hms date calcFunc-idn))
2708 (cons (car a) (mapcar 'math-neg (cdr a))))
bf77c646 2709 (t (math-neg-fancy a))))
136211a9
EZ
2710
2711
2712;;; Compute the number of decimal digits in integer A. [S I]
2713(defun math-numdigs (a)
2714 (if (consp a)
2715 (if (cdr a)
2716 (let* ((len (1- (length a)))
2717 (top (nth len a)))
a6d107f1 2718 (+ (* (1- len) math-bignum-digit-length) (math-numdigs top)))
136211a9
EZ
2719 0)
2720 (cond ((>= a 100) (+ (math-numdigs (/ a 1000)) 3))
2721 ((>= a 10) 2)
2722 ((>= a 1) 1)
2723 ((= a 0) 0)
2724 ((> a -10) 1)
2725 ((> a -100) 2)
bf77c646 2726 (t (math-numdigs (- a))))))
136211a9
EZ
2727
2728;;; Multiply (with truncation toward 0) the integer A by 10^N. [I i S]
2729(defun math-scale-int (a n)
2730 (cond ((= n 0) a)
2731 ((> n 0) (math-scale-left a n))
bf77c646 2732 (t (math-normalize (math-scale-right a (- n))))))
136211a9
EZ
2733
2734(defun math-scale-left (a n) ; [I I S]
2735 (if (= n 0)
2736 a
2737 (if (consp a)
2738 (cons (car a) (math-scale-left-bignum (cdr a) n))
a6d107f1 2739 (if (>= n math-bignum-digit-length)
2a78421d 2740 (if (or (>= a math-bignum-digit-size)
a6d107f1 2741 (<= a (- math-bignum-digit-size)))
136211a9 2742 (math-scale-left (math-bignum a) n)
2a78421d 2743 (math-scale-left (* a math-bignum-digit-size)
a6d107f1
JB
2744 (- n math-bignum-digit-length)))
2745 (let ((sz (expt 10 (- (* 2 math-bignum-digit-length) n))))
2746 (if (or (>= a sz) (<= a (- sz)))
2747 (math-scale-left (math-bignum a) n)
2748 (* a (expt 10 n))))))))
136211a9
EZ
2749
2750(defun math-scale-left-bignum (a n)
a6d107f1 2751 (if (>= n math-bignum-digit-length)
136211a9 2752 (while (>= (setq a (cons 0 a)
2a78421d 2753 n (- n math-bignum-digit-length))
a6d107f1 2754 math-bignum-digit-length)))
136211a9 2755 (if (> n 0)
a6d107f1 2756 (math-mul-bignum-digit a (expt 10 n) 0)
bf77c646 2757 a))
136211a9
EZ
2758
2759(defun math-scale-right (a n) ; [i i S]
2760 (if (= n 0)
2761 a
2762 (if (consp a)
2763 (cons (car a) (math-scale-right-bignum (cdr a) n))
2764 (if (<= a 0)
2765 (if (= a 0)
2766 0
2767 (- (math-scale-right (- a) n)))
a6d107f1
JB
2768 (if (>= n math-bignum-digit-length)
2769 (while (and (> (setq a (/ a math-bignum-digit-size)) 0)
2a78421d 2770 (>= (setq n (- n math-bignum-digit-length))
a6d107f1
JB
2771 math-bignum-digit-length))))
2772 (if (> n 0)
2773 (/ a (expt 10 n))
2774 a)))))
136211a9
EZ
2775
2776(defun math-scale-right-bignum (a n) ; [L L S; l l S]
a6d107f1
JB
2777 (if (>= n math-bignum-digit-length)
2778 (setq a (nthcdr (/ n math-bignum-digit-length) a)
2779 n (% n math-bignum-digit-length)))
136211a9 2780 (if (> n 0)
a6d107f1 2781 (cdr (math-mul-bignum-digit a (expt 10 (- math-bignum-digit-length n)) 0))
bf77c646 2782 a))
136211a9
EZ
2783
2784;;; Multiply (with rounding) the integer A by 10^N. [I i S]
2785(defun math-scale-rounding (a n)
2786 (cond ((>= n 0)
2787 (math-scale-left a n))
2788 ((consp a)
2789 (math-normalize
2790 (cons (car a)
a6d107f1 2791 (let ((val (if (< n (- math-bignum-digit-length))
2a78421d
JB
2792 (math-scale-right-bignum
2793 (cdr a)
a6d107f1
JB
2794 (- (- math-bignum-digit-length) n))
2795 (if (< n 0)
2a78421d
JB
2796 (math-mul-bignum-digit
2797 (cdr a)
a6d107f1
JB
2798 (expt 10 (+ math-bignum-digit-length n)) 0)
2799 (cdr a))))) ; n = -math-bignum-digit-length
2800 (if (and val (>= (car val) (/ math-bignum-digit-size 2)))
136211a9 2801 (if (cdr val)
a6d107f1 2802 (if (eq (car (cdr val)) (1- math-bignum-digit-size))
136211a9
EZ
2803 (math-add-bignum (cdr val) '(1))
2804 (cons (1+ (car (cdr val))) (cdr (cdr val))))
2805 '(1))
2806 (cdr val))))))
2807 (t
2808 (if (< a 0)
2809 (- (math-scale-rounding (- a) n))
2810 (if (= n -1)
2811 (/ (+ a 5) 10)
bf77c646 2812 (/ (+ (math-scale-right a (- -1 n)) 5) 10))))))
136211a9
EZ
2813
2814
2815;;; Compute the sum of A and B. [O O O] [Public]
2816(defun math-add (a b)
2817 (or
2818 (and (not (or (consp a) (consp b)))
2819 (progn
2820 (setq a (+ a b))
a6d107f1 2821 (if (or (<= a (- math-small-integer-size)) (>= a math-small-integer-size))
136211a9
EZ
2822 (math-bignum a)
2823 a)))
2824 (and (Math-zerop a) (not (eq (car-safe a) 'mod))
2825 (if (and (math-floatp a) (Math-ratp b)) (math-float b) b))
2826 (and (Math-zerop b) (not (eq (car-safe b) 'mod))
2827 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a))
2828 (and (Math-objvecp a) (Math-objvecp b)
2829 (or
2830 (and (Math-integerp a) (Math-integerp b)
2831 (progn
2832 (or (consp a) (setq a (math-bignum a)))
2833 (or (consp b) (setq b (math-bignum b)))
2834 (if (eq (car a) 'bigneg)
2835 (if (eq (car b) 'bigneg)
2836 (cons 'bigneg (math-add-bignum (cdr a) (cdr b)))
2837 (math-normalize
2838 (let ((diff (math-sub-bignum (cdr b) (cdr a))))
2839 (if (eq diff 'neg)
2840 (cons 'bigneg (math-sub-bignum (cdr a) (cdr b)))
2841 (cons 'bigpos diff)))))
2842 (if (eq (car b) 'bigneg)
2843 (math-normalize
2844 (let ((diff (math-sub-bignum (cdr a) (cdr b))))
2845 (if (eq diff 'neg)
2846 (cons 'bigneg (math-sub-bignum (cdr b) (cdr a)))
2847 (cons 'bigpos diff))))
2848 (cons 'bigpos (math-add-bignum (cdr a) (cdr b)))))))
2849 (and (Math-ratp a) (Math-ratp b)
ce805efa 2850 (require 'calc-ext)
136211a9
EZ
2851 (calc-add-fractions a b))
2852 (and (Math-realp a) (Math-realp b)
2853 (progn
2854 (or (and (consp a) (eq (car a) 'float))
2855 (setq a (math-float a)))
2856 (or (and (consp b) (eq (car b) 'float))
2857 (setq b (math-float b)))
2858 (math-add-float a b)))
ce805efa 2859 (and (require 'calc-ext)
136211a9 2860 (math-add-objects-fancy a b))))
ce805efa 2861 (and (require 'calc-ext)
bf77c646 2862 (math-add-symb-fancy a b))))
136211a9
EZ
2863
2864(defun math-add-bignum (a b) ; [L L L; l l l]
2865 (if a
2866 (if b
2867 (let* ((a (copy-sequence a)) (aa a) (carry nil) sum)
2868 (while (and aa b)
2869 (if carry
2a78421d 2870 (if (< (setq sum (+ (car aa) (car b)))
a6d107f1 2871 (1- math-bignum-digit-size))
136211a9
EZ
2872 (progn
2873 (setcar aa (1+ sum))
2874 (setq carry nil))
9ae06d96 2875 (setcar aa (- sum (1- math-bignum-digit-size))))
a6d107f1 2876 (if (< (setq sum (+ (car aa) (car b))) math-bignum-digit-size)
136211a9 2877 (setcar aa sum)
a6d107f1 2878 (setcar aa (- sum math-bignum-digit-size))
136211a9
EZ
2879 (setq carry t)))
2880 (setq aa (cdr aa)
2881 b (cdr b)))
2882 (if carry
2883 (if b
2884 (nconc a (math-add-bignum b '(1)))
9ae06d96 2885 (while (eq (car aa) (1- math-bignum-digit-size))
136211a9
EZ
2886 (setcar aa 0)
2887 (setq aa (cdr aa)))
2888 (if aa
2889 (progn
2890 (setcar aa (1+ (car aa)))
2891 a)
2892 (nconc a '(1))))
2893 (if b
2894 (nconc a b)
2895 a)))
2896 a)
bf77c646 2897 b))
136211a9
EZ
2898
2899(defun math-sub-bignum (a b) ; [l l l]
2900 (if b
2901 (if a
730576f3 2902 (let* ((a (copy-sequence a)) (aa a) (borrow nil) sum diff)
136211a9
EZ
2903 (while (and aa b)
2904 (if borrow
2905 (if (>= (setq diff (- (car aa) (car b))) 1)
2906 (progn
2907 (setcar aa (1- diff))
2908 (setq borrow nil))
a6d107f1 2909 (setcar aa (+ diff (1- math-bignum-digit-size))))
136211a9
EZ
2910 (if (>= (setq diff (- (car aa) (car b))) 0)
2911 (setcar aa diff)
a6d107f1 2912 (setcar aa (+ diff math-bignum-digit-size))
136211a9
EZ
2913 (setq borrow t)))
2914 (setq aa (cdr aa)
2915 b (cdr b)))
2916 (if borrow
2917 (progn
2918 (while (eq (car aa) 0)
a6d107f1 2919 (setcar aa (1- math-bignum-digit-size))
136211a9
EZ
2920 (setq aa (cdr aa)))
2921 (if aa
2922 (progn
2923 (setcar aa (1- (car aa)))
2924 a)
2925 'neg))
2926 (while (eq (car b) 0)
2927 (setq b (cdr b)))
2928 (if b
2929 'neg
2930 a)))
2931 (while (eq (car b) 0)
2932 (setq b (cdr b)))
2933 (and b
2934 'neg))
bf77c646 2935 a))
136211a9
EZ
2936
2937(defun math-add-float (a b) ; [F F F]
2938 (let ((ediff (- (nth 2 a) (nth 2 b))))
2939 (if (>= ediff 0)
2940 (if (>= ediff (+ calc-internal-prec calc-internal-prec))
2941 a
2942 (math-make-float (math-add (nth 1 b)
2943 (if (eq ediff 0)
2944 (nth 1 a)
2945 (math-scale-left (nth 1 a) ediff)))
2946 (nth 2 b)))
2947 (if (>= (setq ediff (- ediff))
2948 (+ calc-internal-prec calc-internal-prec))
2949 b
2950 (math-make-float (math-add (nth 1 a)
2951 (math-scale-left (nth 1 b) ediff))
bf77c646 2952 (nth 2 a))))))
136211a9
EZ
2953
2954;;; Compute the difference of A and B. [O O O] [Public]
2955(defun math-sub (a b)
2956 (if (or (consp a) (consp b))
2957 (math-add a (math-neg b))
2958 (setq a (- a b))
a6d107f1 2959 (if (or (<= a (- math-small-integer-size)) (>= a math-small-integer-size))
136211a9 2960 (math-bignum a)
bf77c646 2961 a)))
136211a9
EZ
2962
2963(defun math-sub-float (a b) ; [F F F]
2964 (let ((ediff (- (nth 2 a) (nth 2 b))))
2965 (if (>= ediff 0)
2966 (if (>= ediff (+ calc-internal-prec calc-internal-prec))
2967 a
2968 (math-make-float (math-add (Math-integer-neg (nth 1 b))
2969 (if (eq ediff 0)
2970 (nth 1 a)
2971 (math-scale-left (nth 1 a) ediff)))
2972 (nth 2 b)))
2973 (if (>= (setq ediff (- ediff))
2974 (+ calc-internal-prec calc-internal-prec))
2975 b
2976 (math-make-float (math-add (nth 1 a)
2977 (Math-integer-neg
2978 (math-scale-left (nth 1 b) ediff)))
bf77c646 2979 (nth 2 a))))))
136211a9
EZ
2980
2981
2982;;; Compute the product of A and B. [O O O] [Public]
2983(defun math-mul (a b)
2984 (or
2985 (and (not (consp a)) (not (consp b))
2a78421d 2986 (< a math-bignum-digit-size) (> a (- math-bignum-digit-size))
a6d107f1 2987 (< b math-bignum-digit-size) (> b (- math-bignum-digit-size))
136211a9
EZ
2988 (* a b))
2989 (and (Math-zerop a) (not (eq (car-safe b) 'mod))
2990 (if (Math-scalarp b)
2991 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
ce805efa 2992 (require 'calc-ext)
136211a9
EZ
2993 (math-mul-zero a b)))
2994 (and (Math-zerop b) (not (eq (car-safe a) 'mod))
2995 (if (Math-scalarp a)
2996 (if (and (math-floatp a) (Math-ratp b)) (math-float b) b)
ce805efa 2997 (require 'calc-ext)
136211a9
EZ
2998 (math-mul-zero b a)))
2999 (and (Math-objvecp a) (Math-objvecp b)
3000 (or
3001 (and (Math-integerp a) (Math-integerp b)
3002 (progn
3003 (or (consp a) (setq a (math-bignum a)))
3004 (or (consp b) (setq b (math-bignum b)))
3005 (math-normalize
3006 (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
3007 (if (cdr (cdr a))
3008 (if (cdr (cdr b))
3009 (math-mul-bignum (cdr a) (cdr b))
3010 (math-mul-bignum-digit (cdr a) (nth 1 b) 0))
3011 (math-mul-bignum-digit (cdr b) (nth 1 a) 0))))))
3012 (and (Math-ratp a) (Math-ratp b)
ce805efa 3013 (require 'calc-ext)
136211a9
EZ
3014 (calc-mul-fractions a b))
3015 (and (Math-realp a) (Math-realp b)
3016 (progn
3017 (or (and (consp a) (eq (car a) 'float))
3018 (setq a (math-float a)))
3019 (or (and (consp b) (eq (car b) 'float))
3020 (setq b (math-float b)))
3021 (math-make-float (math-mul (nth 1 a) (nth 1 b))
3022 (+ (nth 2 a) (nth 2 b)))))
ce805efa 3023 (and (require 'calc-ext)
136211a9 3024 (math-mul-objects-fancy a b))))
ce805efa 3025 (and (require 'calc-ext)
bf77c646 3026 (math-mul-symb-fancy a b))))
136211a9
EZ
3027
3028(defun math-infinitep (a &optional undir)
3029 (while (and (consp a) (memq (car a) '(* / neg)))
3030 (if (or (not (eq (car a) '*)) (math-infinitep (nth 1 a)))
3031 (setq a (nth 1 a))
3032 (setq a (nth 2 a))))
3033 (and (consp a)
3034 (eq (car a) 'var)
3035 (memq (nth 2 a) '(var-inf var-uinf var-nan))
3036 (if (and undir (eq (nth 2 a) 'var-inf))
3037 '(var uinf var-uinf)
bf77c646 3038 a)))
136211a9
EZ
3039
3040;;; Multiply digit lists A and B. [L L L; l l l]
3041(defun math-mul-bignum (a b)
3042 (and a b
3043 (let* ((sum (if (<= (car b) 1)
3044 (if (= (car b) 0)
3045 (list 0)
3046 (copy-sequence a))
3047 (math-mul-bignum-digit a (car b) 0)))
3048 (sump sum) c d aa ss prod)
3049 (while (setq b (cdr b))
3050 (setq ss (setq sump (or (cdr sump) (setcdr sump (list 0))))
3051 d (car b)
3052 c 0
3053 aa a)
3054 (while (progn
3055 (setcar ss (% (setq prod (+ (+ (car ss) (* (car aa) d))
a6d107f1 3056 c)) math-bignum-digit-size))
136211a9 3057 (setq aa (cdr aa)))
a6d107f1 3058 (setq c (/ prod math-bignum-digit-size)
136211a9 3059 ss (or (cdr ss) (setcdr ss (list 0)))))
a6d107f1 3060 (if (>= prod math-bignum-digit-size)
136211a9 3061 (if (cdr ss)
a6d107f1
JB
3062 (setcar (cdr ss) (+ (/ prod math-bignum-digit-size) (car (cdr ss))))
3063 (setcdr ss (list (/ prod math-bignum-digit-size))))))
bf77c646 3064 sum)))
136211a9
EZ
3065
3066;;; Multiply digit list A by digit D. [L L D D; l l D D]
3067(defun math-mul-bignum-digit (a d c)
3068 (if a
3069 (if (<= d 1)
3070 (and (= d 1) a)
3071 (let* ((a (copy-sequence a)) (aa a) prod)
3072 (while (progn
2a78421d
JB
3073 (setcar aa
3074 (% (setq prod (+ (* (car aa) d) c))
a6d107f1 3075 math-bignum-digit-size))
136211a9
EZ
3076 (cdr aa))
3077 (setq aa (cdr aa)
a6d107f1
JB
3078 c (/ prod math-bignum-digit-size)))
3079 (if (>= prod math-bignum-digit-size)
3080 (setcdr aa (list (/ prod math-bignum-digit-size))))
136211a9
EZ
3081 a))
3082 (and (> c 0)
bf77c646 3083 (list c))))
136211a9
EZ
3084
3085
3086;;; Compute the integer (quotient . remainder) of A and B, which may be
3087;;; small or big integers. Type and consistency of truncation is undefined
3088;;; if A or B is negative. B must be nonzero. [I.I I I] [Public]
3089(defun math-idivmod (a b)
3090 (if (eq b 0)
3091 (math-reject-arg a "*Division by zero"))
3092 (if (or (consp a) (consp b))
a6d107f1 3093 (if (and (natnump b) (< b math-bignum-digit-size))
136211a9
EZ
3094 (let ((res (math-div-bignum-digit (cdr a) b)))
3095 (cons
3096 (math-normalize (cons (car a) (car res)))
3097 (cdr res)))
3098 (or (consp a) (setq a (math-bignum a)))
3099 (or (consp b) (setq b (math-bignum b)))
3100 (let ((res (math-div-bignum (cdr a) (cdr b))))
3101 (cons
3102 (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
3103 (car res)))
3104 (math-normalize (cons (car a) (cdr res))))))
bf77c646 3105 (cons (/ a b) (% a b))))
136211a9
EZ
3106
3107(defun math-quotient (a b) ; [I I I] [Public]
3108 (if (and (not (consp a)) (not (consp b)))
3109 (if (= b 0)
3110 (math-reject-arg a "*Division by zero")
3111 (/ a b))
a6d107f1 3112 (if (and (natnump b) (< b math-bignum-digit-size))
136211a9
EZ
3113 (if (= b 0)
3114 (math-reject-arg a "*Division by zero")
3115 (math-normalize (cons (car a)
3116 (car (math-div-bignum-digit (cdr a) b)))))
3117 (or (consp a) (setq a (math-bignum a)))
3118 (or (consp b) (setq b (math-bignum b)))
3119 (let* ((alen (1- (length a)))
3120 (blen (1- (length b)))
a6d107f1 3121 (d (/ math-bignum-digit-size (1+ (nth (1- blen) (cdr b)))))
136211a9
EZ
3122 (res (math-div-bignum-big (math-mul-bignum-digit (cdr a) d 0)
3123 (math-mul-bignum-digit (cdr b) d 0)
3124 alen blen)))
3125 (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
bf77c646 3126 (car res)))))))
136211a9
EZ
3127
3128
3129;;; Divide a bignum digit list by another. [l.l l L]
3130;;; The following division algorithm is borrowed from Knuth vol. II, sec. 4.3.1
3131(defun math-div-bignum (a b)
3132 (if (cdr b)
3133 (let* ((alen (length a))
3134 (blen (length b))
a6d107f1 3135 (d (/ math-bignum-digit-size (1+ (nth (1- blen) b))))
136211a9
EZ
3136 (res (math-div-bignum-big (math-mul-bignum-digit a d 0)
3137 (math-mul-bignum-digit b d 0)
3138 alen blen)))
3139 (if (= d 1)
3140 res
3141 (cons (car res)
3142 (car (math-div-bignum-digit (cdr res) d)))))
3143 (let ((res (math-div-bignum-digit a (car b))))
bf77c646 3144 (cons (car res) (list (cdr res))))))
136211a9
EZ
3145
3146;;; Divide a bignum digit list by a digit. [l.D l D]
3147(defun math-div-bignum-digit (a b)
3148 (if a
3149 (let* ((res (math-div-bignum-digit (cdr a) b))
a6d107f1 3150 (num (+ (* (cdr res) math-bignum-digit-size) (car a))))
136211a9
EZ
3151 (cons
3152 (cons (/ num b) (car res))
3153 (% num b)))
bf77c646 3154 '(nil . 0)))
136211a9
EZ
3155
3156(defun math-div-bignum-big (a b alen blen) ; [l.l l L]
3157 (if (< alen blen)
3158 (cons nil a)
3159 (let* ((res (math-div-bignum-big (cdr a) b (1- alen) blen))
3160 (num (cons (car a) (cdr res)))
3161 (res2 (math-div-bignum-part num b blen)))
3162 (cons
3163 (cons (car res2) (car res))
bf77c646 3164 (cdr res2)))))
136211a9 3165
a6d107f1 3166(defun math-div-bignum-part (a b blen) ; a < b*math-bignum-digit-size [D.l l L]
2a78421d 3167 (let* ((num (+ (* (or (nth blen a) 0) math-bignum-digit-size)
a6d107f1 3168 (or (nth (1- blen) a) 0)))
136211a9 3169 (den (nth (1- blen) b))
a6d107f1 3170 (guess (min (/ num den) (1- math-bignum-digit-size))))
bf77c646 3171 (math-div-bignum-try a b (math-mul-bignum-digit b guess 0) guess)))
136211a9
EZ
3172
3173(defun math-div-bignum-try (a b c guess) ; [D.l l l D]
3174 (let ((rem (math-sub-bignum a c)))
3175 (if (eq rem 'neg)
3176 (math-div-bignum-try a b (math-sub-bignum c b) (1- guess))
bf77c646 3177 (cons guess rem))))
136211a9
EZ
3178
3179
3180;;; Compute the quotient of A and B. [O O N] [Public]
3181(defun math-div (a b)
3182 (or
3183 (and (Math-zerop b)
ce805efa 3184 (require 'calc-ext)
136211a9
EZ
3185 (math-div-by-zero a b))
3186 (and (Math-zerop a) (not (eq (car-safe b) 'mod))
3187 (if (Math-scalarp b)
3188 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
ce805efa 3189 (require 'calc-ext)
136211a9
EZ
3190 (math-div-zero a b)))
3191 (and (Math-objvecp a) (Math-objvecp b)
3192 (or
3193 (and (Math-integerp a) (Math-integerp b)
3194 (let ((q (math-idivmod a b)))
3195 (if (eq (cdr q) 0)
3196 (car q)
3197 (if calc-prefer-frac
3198 (progn
ce805efa 3199 (require 'calc-ext)
136211a9
EZ
3200 (math-make-frac a b))
3201 (math-div-float (math-make-float a 0)
3202 (math-make-float b 0))))))
3203 (and (Math-ratp a) (Math-ratp b)
ce805efa 3204 (require 'calc-ext)
136211a9
EZ
3205 (calc-div-fractions a b))
3206 (and (Math-realp a) (Math-realp b)
3207 (progn
3208 (or (and (consp a) (eq (car a) 'float))
3209 (setq a (math-float a)))
3210 (or (and (consp b) (eq (car b) 'float))
3211 (setq b (math-float b)))
3212 (math-div-float a b)))
ce805efa 3213 (and (require 'calc-ext)
136211a9 3214 (math-div-objects-fancy a b))))
ce805efa 3215 (and (require 'calc-ext)
bf77c646 3216 (math-div-symb-fancy a b))))
136211a9
EZ
3217
3218(defun math-div-float (a b) ; [F F F]
3219 (let ((ldiff (max (- (1+ calc-internal-prec)
3220 (- (math-numdigs (nth 1 a)) (math-numdigs (nth 1 b))))
3221 0)))
3222 (math-make-float (math-quotient (math-scale-int (nth 1 a) ldiff) (nth 1 b))
bf77c646 3223 (- (- (nth 2 a) (nth 2 b)) ldiff))))
136211a9
EZ
3224
3225
3226
3227
730576f3 3228(defvar calc-selection-cache-entry)
136211a9
EZ
3229;;; Format the number A as a string. [X N; X Z] [Public]
3230(defun math-format-stack-value (entry)
3231 (setq calc-selection-cache-entry calc-selection-cache-default-entry)
3232 (let* ((a (car entry))
3233 (math-comp-selected (nth 2 entry))
3234 (c (cond ((null a) "<nil>")
3235 ((eq calc-display-raw t) (format "%s" a))
3236 ((stringp a) a)
cd012309 3237 ((eq a 'top-of-stack) (propertize "." 'font-lock-face 'bold))
136211a9
EZ
3238 (calc-prepared-composition
3239 calc-prepared-composition)
3240 ((and (Math-scalarp a)
3241 (memq calc-language '(nil flat unform))
3242 (null math-comp-selected))
3243 (math-format-number a))
ce805efa 3244 (t (require 'calc-ext)
136211a9
EZ
3245 (math-compose-expr a 0))))
3246 (off (math-stack-value-offset c))
3247 s w)
3248 (and math-comp-selected (setq calc-any-selections t))
3249 (setq w (cdr off)
3250 off (car off))
cd012309 3251 (when (> off 0)
111a5355 3252 (setq c (math-comp-concat (make-string off ?\s) c)))
136211a9
EZ
3253 (or (equal calc-left-label "")
3254 (setq c (math-comp-concat (if (eq a 'top-of-stack)
111a5355 3255 (make-string (length calc-left-label) ?\s)
136211a9
EZ
3256 calc-left-label)
3257 c)))
cd012309
CW
3258 (when calc-line-numbering
3259 (setq c (math-comp-concat (if (eq calc-language 'big)
2363bd8d
DK
3260 (if math-comp-selected
3261 '(tag t "1: ")
3262 "1: ")
cd012309
CW
3263 " ")
3264 c)))
3265 (unless (or (equal calc-right-label "")
3266 (eq a 'top-of-stack))
ce805efa 3267 (require 'calc-ext)
cd012309
CW
3268 (setq c (list 'horiz c
3269 (make-string (max (- w (math-comp-width c)
111a5355 3270 (length calc-right-label)) 0) ?\s)
cd012309
CW
3271 '(break -1)
3272 calc-right-label)))
136211a9
EZ
3273 (setq s (if (stringp c)
3274 (if calc-display-raw
3275 (prin1-to-string c)
3276 c)
3277 (math-composition-to-string c w)))
cd012309
CW
3278 (when calc-language-output-filter
3279 (setq s (funcall calc-language-output-filter s)))
136211a9
EZ
3280 (if (eq calc-language 'big)
3281 (setq s (concat s "\n"))
cd012309 3282 (when calc-line-numbering
6a3ed064 3283 (setq s (concat "1:" (substring s 2)))))
136211a9 3284 (setcar (cdr entry) (calc-count-lines s))
bf77c646 3285 s))
136211a9 3286
f0a35df4
JB
3287;; The variables math-svo-c, math-svo-wid and math-svo-off are local
3288;; to math-stack-value-offset, but are used by math-stack-value-offset-fancy
3289;; in calccomp.el.
3290
3291(defun math-stack-value-offset (math-svo-c)
136211a9 3292 (let* ((num (if calc-line-numbering 4 0))
f0a35df4
JB
3293 (math-svo-wid (calc-window-width))
3294 math-svo-off)
136211a9
EZ
3295 (if calc-display-just
3296 (progn
ce805efa 3297 (require 'calc-ext)
136211a9 3298 (math-stack-value-offset-fancy))
f0a35df4 3299 (setq math-svo-off (or calc-display-origin 0))
cd012309 3300 (when (integerp calc-line-breaking)
f0a35df4
JB
3301 (setq math-svo-wid calc-line-breaking)))
3302 (cons (max (- math-svo-off (length calc-left-label)) 0)
3303 (+ math-svo-wid num))))
136211a9
EZ
3304
3305(defun calc-count-lines (s)
3306 (let ((pos 0)
3307 (num 1))
730576f3
CW
3308 (while (setq pos (string-match "\n" s pos))
3309 (setq pos (1+ pos)
136211a9 3310 num (1+ num)))
bf77c646 3311 num))
136211a9
EZ
3312
3313(defun math-format-value (a &optional w)
3314 (if (and (Math-scalarp a)
3315 (memq calc-language '(nil flat unform)))
3316 (math-format-number a)
ce805efa 3317 (require 'calc-ext)
136211a9 3318 (let ((calc-line-breaking nil))
bf77c646 3319 (math-composition-to-string (math-compose-expr a 0) w))))
136211a9
EZ
3320
3321(defun calc-window-width ()
3322 (if calc-embedded-info
3323 (let ((win (get-buffer-window (aref calc-embedded-info 0))))
31b85a14 3324 (1- (if win (window-width win) (frame-width))))
136211a9 3325 (- (window-width (get-buffer-window (current-buffer)))
bf77c646 3326 (if calc-line-numbering 5 1))))
136211a9
EZ
3327
3328(defun math-comp-concat (c1 c2)
3329 (if (and (stringp c1) (stringp c2))
3330 (concat c1 c2)
bf77c646 3331 (list 'horiz c1 c2)))
136211a9
EZ
3332
3333
3334
3335;;; Format an expression as a one-line string suitable for re-reading.
3336
3337(defun math-format-flat-expr (a prec)
3338 (cond
3339 ((or (not (or (consp a) (integerp a)))
3340 (eq calc-display-raw t))
3341 (let ((print-escape-newlines t))
3342 (concat "'" (prin1-to-string a))))
3343 ((Math-scalarp a)
3344 (let ((calc-group-digits nil)
3345 (calc-point-char ".")
3346 (calc-frac-format (if (> (length (car calc-frac-format)) 1)
3347 '("::" nil) '(":" nil)))
3348 (calc-complex-format nil)
3349 (calc-hms-format "%s@ %s' %s\"")
3350 (calc-language nil))
3351 (math-format-number a)))
3352 (t
ce805efa 3353 (require 'calc-ext)
bf77c646 3354 (math-format-flat-expr-fancy a prec))))
136211a9
EZ
3355
3356
3357
3358;;; Format a number as a string.
3359(defun math-format-number (a &optional prec) ; [X N] [Public]
3360 (cond
3361 ((eq calc-display-raw t) (format "%s" a))
3362 ((and (nth 1 calc-frac-format) (Math-integerp a))
ce805efa 3363 (require 'calc-ext)
136211a9
EZ
3364 (math-format-number (math-adjust-fraction a)))
3365 ((integerp a)
3366 (if (not (or calc-group-digits calc-leading-zeros))
3367 (if (= calc-number-radix 10)
3368 (int-to-string a)
3369 (if (< a 0)
3370 (concat "-" (math-format-number (- a)))
ce805efa 3371 (require 'calc-ext)
136211a9
EZ
3372 (if math-radix-explicit-format
3373 (if calc-radix-formatter
3374 (funcall calc-radix-formatter
3375 calc-number-radix
3376 (if (= calc-number-radix 2)
3377 (math-format-binary a)
3378 (math-format-radix a)))
3379 (format "%d#%s" calc-number-radix
3380 (if (= calc-number-radix 2)
3381 (math-format-binary a)
3382 (math-format-radix a))))
3383 (math-format-radix a))))
3384 (math-format-number (math-bignum a))))
3385 ((stringp a) a)
3386 ((not (consp a)) (prin1-to-string a))
3387 ((eq (car a) 'bigpos) (math-format-bignum (cdr a)))
3388 ((eq (car a) 'bigneg) (concat "-" (math-format-bignum (cdr a))))
3389 ((and (eq (car a) 'float) (= calc-number-radix 10))
3390 (if (Math-integer-negp (nth 1 a))
3391 (concat "-" (math-format-number (math-neg a)))
3392 (let ((mant (nth 1 a))
3393 (exp (nth 2 a))
3394 (fmt (car calc-float-format))
3395 (figs (nth 1 calc-float-format))
3396 (point calc-point-char)
3397 str)
3398 (if (and (eq fmt 'fix)
3399 (or (and (< figs 0) (setq figs (- figs)))
3400 (> (+ exp (math-numdigs mant)) (- figs))))
3401 (progn
3402 (setq mant (math-scale-rounding mant (+ exp figs))
3403 str (if (integerp mant)
3404 (int-to-string mant)
3405 (math-format-bignum-decimal (cdr mant))))
3406 (if (<= (length str) figs)
3407 (setq str (concat (make-string (1+ (- figs (length str))) ?0)
3408 str)))
3409 (if (> figs 0)
3410 (setq str (concat (substring str 0 (- figs)) point
3411 (substring str (- figs))))
3412 (setq str (concat str point)))
91da6442
CW
3413 (when calc-group-digits
3414 (require 'calc-ext)
3415 (setq str (math-group-float str))))
cd012309
CW
3416 (when (< figs 0)
3417 (setq figs (+ calc-internal-prec figs)))
3418 (when (> figs 0)
3419 (let ((adj (- figs (math-numdigs mant))))
3420 (when (< adj 0)
3421 (setq mant (math-scale-rounding mant adj)
3422 exp (- exp adj)))))
136211a9
EZ
3423 (setq str (if (integerp mant)
3424 (int-to-string mant)
3425 (math-format-bignum-decimal (cdr mant))))
3426 (let* ((len (length str))
3427 (dpos (+ exp len)))
3428 (if (and (eq fmt 'float)
3429 (<= dpos (+ calc-internal-prec calc-display-sci-high))
3430 (>= dpos (+ calc-display-sci-low 2)))
3431 (progn
3432 (cond
3433 ((= dpos 0)
3434 (setq str (concat "0" point str)))
3435 ((and (<= exp 0) (> dpos 0))
3436 (setq str (concat (substring str 0 dpos) point
3437 (substring str dpos))))
3438 ((> exp 0)
3439 (setq str (concat str (make-string exp ?0) point)))
3440 (t ; (< dpos 0)
3441 (setq str (concat "0" point
3442 (make-string (- dpos) ?0) str))))
91da6442
CW
3443 (when calc-group-digits
3444 (require 'calc-ext)
3445 (setq str (math-group-float str))))
136211a9
EZ
3446 (let* ((eadj (+ exp len))
3447 (scale (if (eq fmt 'eng)
3448 (1+ (math-mod (+ eadj 300002) 3))
3449 1)))
3450 (if (> scale (length str))
3451 (setq str (concat str (make-string (- scale (length str))
3452 ?0))))
3453 (if (< scale (length str))
3454 (setq str (concat (substring str 0 scale) point
3455 (substring str scale))))
91da6442
CW
3456 (when calc-group-digits
3457 (require 'calc-ext)
3458 (setq str (math-group-float str)))
136211a9
EZ
3459 (setq str (format (if (memq calc-language '(math maple))
3460 (if (and prec (> prec 191))
3461 "(%s*10.^%d)" "%s*10.^%d")
3462 "%se%d")
3463 str (- eadj scale)))))))
3464 str)))
3465 (t
ce805efa 3466 (require 'calc-ext)
bf77c646 3467 (math-format-number-fancy a prec))))
136211a9
EZ
3468
3469(defun math-format-bignum (a) ; [X L]
3470 (if (and (= calc-number-radix 10)
3471 (not calc-leading-zeros)
3472 (not calc-group-digits))
3473 (math-format-bignum-decimal a)
ce805efa 3474 (require 'calc-ext)
bf77c646 3475 (math-format-bignum-fancy a)))
136211a9
EZ
3476
3477(defun math-format-bignum-decimal (a) ; [X L]
3478 (if a
3479 (let ((s ""))
3480 (while (cdr (cdr a))
2a78421d
JB
3481 (setq s (concat
3482 (format
3483 (concat "%0"
3484 (number-to-string (* 2 math-bignum-digit-length))
a6d107f1
JB
3485 "d")
3486 (+ (* (nth 1 a) math-bignum-digit-size) (car a))) s)
136211a9 3487 a (cdr (cdr a))))
2a78421d 3488 (concat (int-to-string
a6d107f1 3489 (+ (* (or (nth 1 a) 0) math-bignum-digit-size) (car a))) s))
bf77c646 3490 "0"))
136211a9
EZ
3491
3492
3493
3494;;; Parse a simple number in string form. [N X] [Public]
3495(defun math-read-number (s)
e90988a0 3496 "Convert the string S into a Calc number."
136211a9
EZ
3497 (math-normalize
3498 (cond
3499
3500 ;; Integers (most common case)
3501 ((string-match "\\` *\\([0-9]+\\) *\\'" s)
3502 (let ((digs (math-match-substring s 1)))
3503 (if (and (eq calc-language 'c)
3504 (> (length digs) 1)
3505 (eq (aref digs 0) ?0))
3506 (math-read-number (concat "8#" digs))
e90988a0 3507 (if (<= (length digs) (* 2 math-bignum-digit-length))
28572d7d 3508 (string-to-number digs)
136211a9
EZ
3509 (cons 'bigpos (math-read-bignum digs))))))
3510
3511 ;; Clean up the string if necessary
3512 ((string-match "\\`\\(.*\\)[ \t\n]+\\([^\001]*\\)\\'" s)
3513 (math-read-number (concat (math-match-substring s 1)
3514 (math-match-substring s 2))))
3515
3516 ;; Plus and minus signs
3517 ((string-match "^[-_+]\\(.*\\)$" s)
3518 (let ((val (math-read-number (math-match-substring s 1))))
3519 (and val (if (eq (aref s 0) ?+) val (math-neg val)))))
3520
3521 ;; Forms that require extensions module
3522 ((string-match "[^-+0-9eE.]" s)
ce805efa 3523 (require 'calc-ext)
136211a9
EZ
3524 (math-read-number-fancy s))
3525
3526 ;; Decimal point
3527 ((string-match "^\\([0-9]*\\)\\.\\([0-9]*\\)$" s)
3528 (let ((int (math-match-substring s 1))
3529 (frac (math-match-substring s 2)))
3530 (let ((ilen (length int))
3531 (flen (length frac)))
3532 (let ((int (if (> ilen 0) (math-read-number int) 0))
3533 (frac (if (> flen 0) (math-read-number frac) 0)))
3534 (and int frac (or (> ilen 0) (> flen 0))
3535 (list 'float
3536 (math-add (math-scale-int int flen) frac)
3537 (- flen)))))))
3538
3539 ;; "e" notation
3540 ((string-match "^\\(.*\\)[eE]\\([-+]?[0-9]+\\)$" s)
3541 (let ((mant (math-match-substring s 1))
3542 (exp (math-match-substring s 2)))
3543 (let ((mant (if (> (length mant) 0) (math-read-number mant) 1))
3544 (exp (if (<= (length exp) (if (memq (aref exp 0) '(?+ ?-)) 8 7))
28572d7d 3545 (string-to-number exp))))
136211a9
EZ
3546 (and mant exp (Math-realp mant) (> exp -4000000) (< exp 4000000)
3547 (let ((mant (math-float mant)))
3548 (list 'float (nth 1 mant) (+ (nth 2 mant) exp)))))))
3549
3550 ;; Syntax error!
bf77c646 3551 (t nil))))
136211a9 3552
1f26c380
JB
3553;;; Parse a very simple number, keeping all digits.
3554(defun math-read-number-simple (s)
e90988a0
JB
3555 "Convert the string S into a Calc number.
3556S is assumed to be a simple number (integer or float without an exponent)
3557and all digits are kept, regardless of Calc's current precision."
1f26c380
JB
3558 (cond
3559 ;; Integer
3560 ((string-match "^[0-9]+$" s)
aefad52d
JB
3561 (if (string-match "^\\(0+\\)" s)
3562 (setq s (substring s (match-end 0))))
e90988a0
JB
3563 (if (<= (length s) (* 2 math-bignum-digit-length))
3564 (string-to-number s)
3565 (cons 'bigpos (math-read-bignum s))))
1f26c380
JB
3566 ;; Minus sign
3567 ((string-match "^-[0-9]+$" s)
e90988a0
JB
3568 (if (<= (length s) (1+ (* 2 math-bignum-digit-length)))
3569 (string-to-number s)
3570 (cons 'bigneg (math-read-bignum (substring s 1)))))
1f26c380
JB
3571 ;; Decimal point
3572 ((string-match "^\\(-?[0-9]*\\)\\.\\([0-9]*\\)$" s)
3573 (let ((int (math-match-substring s 1))
3574 (frac (math-match-substring s 2)))
3575 (list 'float (math-read-number-simple (concat int frac))
3576 (- (length frac)))))
3577 ;; Syntax error!
3578 (t nil)))
3579
136211a9
EZ
3580(defun math-match-substring (s n)
3581 (if (match-beginning n)
3582 (substring s (match-beginning n) (match-end n))
bf77c646 3583 ""))
136211a9
EZ
3584
3585(defun math-read-bignum (s) ; [l X]
a6d107f1
JB
3586 (if (> (length s) math-bignum-digit-length)
3587 (cons (string-to-number (substring s (- math-bignum-digit-length)))
3588 (math-read-bignum (substring s 0 (- math-bignum-digit-length))))
28572d7d 3589 (list (string-to-number s))))
136211a9 3590
136211a9
EZ
3591(defconst math-standard-opers
3592 '( ( "_" calcFunc-subscr 1200 1201 )
3593 ( "%" calcFunc-percent 1100 -1 )
136211a9
EZ
3594 ( "u!" calcFunc-lnot -1 1000 )
3595 ( "mod" mod 400 400 185 )
3596 ( "+/-" sdev 300 300 185 )
3597 ( "!!" calcFunc-dfact 210 -1 )
3598 ( "!" calcFunc-fact 210 -1 )
3599 ( "^" ^ 201 200 )
3600 ( "**" ^ 201 200 )
c8d00744
JB
3601 ( "u+" ident -1 197 )
3602 ( "u-" neg -1 197 )
136211a9
EZ
3603 ( "/" / 190 191 )
3604 ( "%" % 190 191 )
3605 ( "\\" calcFunc-idiv 190 191 )
3606 ( "+" + 180 181 )
3607 ( "-" - 180 181 )
3608 ( "|" | 170 171 )
3609 ( "<" calcFunc-lt 160 161 )
3610 ( ">" calcFunc-gt 160 161 )
3611 ( "<=" calcFunc-leq 160 161 )
3612 ( ">=" calcFunc-geq 160 161 )
3613 ( "=" calcFunc-eq 160 161 )
3614 ( "==" calcFunc-eq 160 161 )
3615 ( "!=" calcFunc-neq 160 161 )
3616 ( "&&" calcFunc-land 110 111 )
3617 ( "||" calcFunc-lor 100 101 )
3618 ( "?" (math-read-if) 91 90 )
3619 ( "!!!" calcFunc-pnot -1 85 )
3620 ( "&&&" calcFunc-pand 80 81 )
3621 ( "|||" calcFunc-por 75 76 )
3622 ( ":=" calcFunc-assign 51 50 )
3623 ( "::" calcFunc-condition 45 46 )
3624 ( "=>" calcFunc-evalto 40 41 )
f269b73e 3625 ( "=>" calcFunc-evalto 40 -1 )))
515e955e
JB
3626
3627(defun math-standard-ops ()
3628 (if calc-multiplication-has-precedence
3629 (cons
3630 '( "*" * 196 195 )
3631 (cons
3632 '( "2x" * 196 195 )
3633 math-standard-opers))
3634 (cons
cad63e32 3635 '( "*" * 190 191 )
515e955e 3636 (cons
cad63e32 3637 '( "2x" * 190 191 )
515e955e
JB
3638 math-standard-opers))))
3639
a6a0d3cb
JB
3640(defvar math-expr-opers (math-standard-ops))
3641
515e955e
JB
3642(defun math-standard-ops-p ()
3643 (let ((meo (caar math-expr-opers)))
3644 (and (stringp meo)
3645 (string= meo "*"))))
3646
515e955e
JB
3647(defun math-expr-ops ()
3648 (if (math-standard-ops-p)
3649 (math-standard-ops)
3650 math-expr-opers))
136211a9
EZ
3651
3652;;;###autoload
3653(defun calc-grab-region (top bot arg)
3654 "Parse the region as a vector of numbers and push it on the Calculator stack."
3655 (interactive "r\nP")
ce805efa 3656 (require 'calc-ext)
bf77c646 3657 (calc-do-grab-region top bot arg))
136211a9
EZ
3658
3659;;;###autoload
3660(defun calc-grab-rectangle (top bot arg)
3661 "Parse a rectangle as a matrix of numbers and push it on the Calculator stack."
3662 (interactive "r\nP")
ce805efa 3663 (require 'calc-ext)
bf77c646 3664 (calc-do-grab-rectangle top bot arg))
136211a9
EZ
3665
3666(defun calc-grab-sum-down (top bot arg)
3667 "Parse a rectangle as a matrix of numbers and sum its columns."
3668 (interactive "r\nP")
ce805efa 3669 (require 'calc-ext)
bf77c646 3670 (calc-do-grab-rectangle top bot arg 'calcFunc-reduced))
136211a9
EZ
3671
3672(defun calc-grab-sum-across (top bot arg)
3673 "Parse a rectangle as a matrix of numbers and sum its rows."
3674 (interactive "r\nP")
ce805efa 3675 (require 'calc-ext)
bf77c646 3676 (calc-do-grab-rectangle top bot arg 'calcFunc-reducea))
136211a9
EZ
3677
3678
3679;;;###autoload
3680(defun calc-embedded (arg &optional end obeg oend)
3681 "Start Calc Embedded mode on the formula surrounding point."
3682 (interactive "P")
ce805efa 3683 (require 'calc-ext)
bf77c646 3684 (calc-do-embedded arg end obeg oend))
136211a9
EZ
3685
3686;;;###autoload
3687(defun calc-embedded-activate (&optional arg cbuf)
3688 "Scan the current editing buffer for all embedded := and => formulas.
3689Also looks for the equivalent TeX words, \\gets and \\evalto."
3690 (interactive "P")
bf77c646 3691 (calc-do-embedded-activate arg cbuf))
136211a9 3692
136211a9
EZ
3693(defun calc-user-invocation ()
3694 (interactive)
dd168a3e 3695 (unless calc-invocation-macro
d24f83d4 3696 (error "Use `Z I' inside Calc to define a `C-x * Z' keyboard macro"))
bf77c646 3697 (execute-kbd-macro calc-invocation-macro nil))
136211a9 3698
136211a9
EZ
3699;;; User-programmability.
3700
3701;;;###autoload
3702(defmacro defmath (func args &rest body) ; [Public]
ce805efa 3703 (require 'calc-ext)
bf77c646 3704 (math-do-defmath func args body))
136211a9 3705
136211a9
EZ
3706;;; Functions needed for Lucid Emacs support.
3707
3708(defun calc-read-key (&optional optkey)
6546555e 3709 (cond ((featurep 'xemacs)
136211a9
EZ
3710 (let ((event (next-command-event)))
3711 (let ((key (event-to-character event t t)))
3712 (or key optkey (error "Expected a plain keystroke"))
3713 (cons key event))))
136211a9 3714 (t
cecd4c20 3715 (let ((key (read-event)))
bf77c646 3716 (cons key key)))))
136211a9
EZ
3717
3718(defun calc-unread-command (&optional input)
31b85a14
EZ
3719 (if (featurep 'xemacs)
3720 (setq unread-command-event
3721 (if (integerp input) (character-to-event input)
3722 (or input last-command-event)))
3723 (push (or input last-command-event) unread-command-events)))
136211a9
EZ
3724
3725(defun calc-clear-unread-commands ()
a1506d29 3726 (if (featurep 'xemacs)
6546555e 3727 (setq unread-command-event nil)
31b85a14 3728 (setq unread-command-events nil)))
136211a9 3729
cd012309 3730(when calc-always-load-extensions
ce805efa 3731 (require 'calc-ext)
cd012309 3732 (calc-load-everything))
136211a9
EZ
3733
3734
3735(run-hooks 'calc-load-hook)
3736
ce805efa
JB
3737(provide 'calc)
3738
ab5796a9 3739;;; arch-tag: 0c3b170c-4ce6-4eaf-8d9b-5834d1fe938f
bf77c646 3740;;; calc.el ends here