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