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