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