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