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