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