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