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