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