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