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