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