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