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