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