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