Fix Bug#24962
[emacs.git] / lisp / calc / calc.el
blob7ae8fdfae03a779e5869ea61ecd7837f42efd08c
1 ;;; calc.el --- the GNU Emacs calculator
3 ;; Copyright (C) 1990-1993, 2001-2016 Free Software Foundation, Inc.
5 ;; Author: David Gillespie <daveg@synaptics.com>
6 ;; Keywords: convenience, extensions
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; Calc is split into many files. This file is the main entry point.
26 ;; This file includes autoload commands for various other basic Calc
27 ;; facilities. The more advanced features are based in calc-ext, which
28 ;; in turn contains autoloads for the rest of the Calc files. This
29 ;; odd set of interactions is designed to make Calc's loading time
30 ;; be as short as possible when only simple calculations are needed.
32 ;; Original author's address:
33 ;; Dave Gillespie, daveg@synaptics.com, uunet!synaptx!daveg.
34 ;; Synaptics, Inc., 2698 Orchard Parkway, San Jose, CA 95134.
36 ;; The old address daveg@csvax.cs.caltech.edu will continue to
37 ;; work for the foreseeable future.
39 ;; Bug reports and suggestions are always welcome! (Type M-x
40 ;; report-calc-bug to send them).
42 ;; All functions, macros, and Lisp variables defined here begin with one
43 ;; of the prefixes "math", "Math", or "calc", with the exceptions of
44 ;; "full-calc", "full-calc-keypad", "another-calc", "quick-calc",
45 ;; "report-calc-bug", and "defmath". User-accessible variables begin
46 ;; with "var-".
48 ;;; TODO:
50 ;; Fix rewrite mechanism to do less gratuitous rearrangement of terms.
51 ;; Implement a pattern-based "refers" predicate.
53 ;; Make it possible to Undo a selection command.
54 ;; Figure out how to allow selecting rows of matrices.
55 ;; If cursor was in selection before, move it after j n, j p, j L, etc.
56 ;; Consider reimplementing calc-delete-selection using rewrites.
58 ;; Implement line-breaking in non-flat compositions (is this desirable?).
59 ;; Implement matrix formatting with multi-line components.
61 ;; Have "Z R" define a user command based on a set of rewrite rules.
62 ;; Support "incf" and "decf" in defmath definitions.
63 ;; Have defmath generate calls to calc-binary-op or calc-unary-op.
64 ;; Make some way to define algebraic functions using keyboard macros.
66 ;; Allow calc-word-size=0 => Common Lisp-style signed bitwise arithmetic.
67 ;; Consider digamma function (and thus arb. prec. Euler's gamma constant).
68 ;; May as well make continued-fractions stuff available to the user.
70 ;; How about matrix eigenvalues, SVD, pseudo-inverse, etc.?
71 ;; Should cache matrix inverses as well as decompositions.
72 ;; If dividing by a non-square matrix, use least-squares automatically.
73 ;; Consider supporting matrix exponentials.
75 ;; Have ninteg detect and work around singularities at the endpoints.
76 ;; Use an adaptive subdivision algorithm for ninteg.
77 ;; Provide nsum and nprod to go along with ninteg.
79 ;; Handle TeX-mode parsing of \matrix{ ... } where ... contains braces.
80 ;; Support AmS-TeX's \{d,t,}frac, \{d,t,}binom notations.
81 ;; Format and parse sums and products in Eqn and Math modes.
83 ;; Get math-read-big-expr to read sums, products, etc.
84 ;; Change calc-grab-region to use math-read-big-expr.
85 ;; Have a way to define functions using := in Embedded Mode.
87 ;; Support polar plotting with GNUPLOT.
88 ;; Make a calc-graph-histogram function.
90 ;; Replace hokey formulas for complex functions with formulas designed
91 ;; to minimize roundoff while maintaining the proper branch cuts.
92 ;; Test accuracy of advanced math functions over whole complex plane.
93 ;; Extend Bessel functions to provide arbitrary precision.
94 ;; Extend advanced math functions to handle error forms and intervals.
95 ;; Provide a better implementation for math-sin-cos-raw.
96 ;; Provide a better implementation for math-hypot.
97 ;; Provide a better implementation for math-make-frac.
98 ;; Provide a better implementation for calcFunc-prfac.
99 ;; Provide a better implementation for calcFunc-factor.
101 ;; Provide more examples in the tutorial section of the manual.
102 ;; Cover in the tutorial: simplification modes, declarations,
103 ;; bitwise stuff, selections, matrix mapping, financial functions.
104 ;; Provide more Lisp programming examples in the manual.
105 ;; Finish the Internals section of the manual (and bring it up to date).
107 ;; Tim suggests adding spreadsheet-like features.
108 ;; Implement language modes for Gnuplot, Lisp, Ada, APL, ...?
110 ;; For atan series, if x > tan(pi/12) (about 0.268) reduce using the identity
111 ;; atan(x) = atan((x * sqrt(3) - 1) / (sqrt(3) + x)) + pi/6.
113 ;; A better integration algorithm:
114 ;; Use breadth-first instead of depth-first search, as follows:
115 ;; The integral cache allows unfinished integrals in symbolic notation
116 ;; on the righthand side. An entry with no unfinished integrals on the
117 ;; RHS is "complete"; references to it elsewhere are replaced by the
118 ;; integrated value. More than one cache entry for the same integral
119 ;; may exist, though if one becomes complete, the others may be deleted.
120 ;; The integrator works by using every applicable rule (such as
121 ;; substitution, parts, linearity, etc.) to generate possible righthand
122 ;; sides, all of which are entered into the cache. Now, as long as the
123 ;; target integral is not complete (and the time limit has not run out)
124 ;; choose an incomplete integral from the cache and, for every integral
125 ;; appearing in its RHS's, add those integrals to the cache using the
126 ;; same substitution, parts, etc. rules. The cache should be organized
127 ;; as a priority queue, choosing the "simplest" incomplete integral at
128 ;; each step, or choosing randomly among equally simple integrals.
129 ;; Simplicity equals small size, and few steps removed from the original
130 ;; target integral. Note that when the integrator finishes, incomplete
131 ;; integrals can be left in the cache, so the algorithm can start where
132 ;; it left off if another similar integral is later requested.
133 ;; Breadth-first search would avoid the nagging problem of, e.g., whether
134 ;; to use parts or substitution first, and which decomposition is best.
135 ;; All are tried, and any path that diverges will quickly be put on the
136 ;; back burner by the priority queue.
137 ;; Note: Probably a good idea to call math-simplify-extended before
138 ;; measuring a formula's simplicity.
140 ;;; Code:
142 (require 'calc-macs)
144 ;; Declare functions which are defined elsewhere.
145 (declare-function calc-set-language "calc-lang" (lang &optional option no-refresh))
146 (declare-function calc-edit-finish "calc-yank" (&optional keep))
147 (declare-function calc-edit-cancel "calc-yank" ())
148 (declare-function calc-locate-cursor-element "calc-yank" (pt))
149 (declare-function calc-do-quick-calc "calc-aent" (&optional insert))
150 (declare-function calc-do-calc-eval "calc-aent" (str separator args))
151 (declare-function calc-do-keypad "calc-keypd" (&optional full-display interactive))
152 (declare-function calcFunc-unixtime "calc-forms" (date &optional zone))
153 (declare-function math-parse-date "calc-forms" (math-pd-str))
154 (declare-function math-lessp "calc-ext" (a b))
155 (declare-function math-compare "calc-ext" (a b))
156 (declare-function math-zerop "calc-misc" (a))
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 "emacs-devel@gnu.org"
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 (ignore-errors
1108 (define-key calc-digit-map x 'calcDigit-backspace)
1109 (define-key calc-mode-map x 'calc-pop)
1110 (define-key calc-mode-map
1111 (if (and (vectorp x) (featurep 'xemacs))
1112 (if (= (length x) 1)
1113 (vector (if (consp (aref x 0))
1114 (cons 'meta (aref x 0))
1115 (list 'meta (aref x 0))))
1116 "\e\C-d")
1117 (vconcat "\e" x))
1118 'calc-pop-above)))
1119 (if calc-scan-for-dels
1120 (append (where-is-internal 'delete-backward-char global-map)
1121 (where-is-internal 'backward-delete-char global-map)
1122 (where-is-internal 'backward-delete-char-untabify global-map)
1123 '("\C-d"))
1124 '("\177" "\C-d")))
1126 (defvar calc-dispatch-map
1127 (let ((map (make-keymap)))
1128 (mapc (lambda (x)
1129 (let* ((x-chr (car x))
1130 (x-str (char-to-string x-chr))
1131 (x-def (cdr x)))
1132 (define-key map x-str x-def)
1133 (when (string-match "[a-z]" x-str)
1134 ;; Map upper case char to same definition.
1135 (define-key map (upcase x-str) x-def)
1136 (unless (string-match "[gmv]" x-str)
1137 ;; Map control prefixed char to same definition.
1138 (define-key map (vector (list 'control x-chr)) x-def)))
1139 (define-key map (format "\e%c" x-chr) x-def)))
1140 '( ( ?a . calc-embedded-activate )
1141 ( ?b . calc-big-or-small )
1142 ( ?c . calc )
1143 ( ?d . calc-embedded-duplicate )
1144 ( ?e . calc-embedded )
1145 ( ?f . calc-embedded-new-formula )
1146 ( ?g . calc-grab-region )
1147 ( ?h . calc-dispatch-help )
1148 ( ?i . calc-info )
1149 ( ?j . calc-embedded-select )
1150 ( ?k . calc-keypad )
1151 ( ?l . calc-load-everything )
1152 ( ?m . read-kbd-macro )
1153 ( ?n . calc-embedded-next )
1154 ( ?o . calc-other-window )
1155 ( ?p . calc-embedded-previous )
1156 ( ?q . quick-calc )
1157 ( ?r . calc-grab-rectangle )
1158 ( ?s . calc-info-summary )
1159 ( ?t . calc-tutorial )
1160 ( ?u . calc-embedded-update-formula )
1161 ( ?w . calc-embedded-word )
1162 ( ?x . calc-quit )
1163 ( ?y . calc-copy-to-buffer )
1164 ( ?z . calc-user-invocation )
1165 ( ?\' . calc-embedded-new-formula )
1166 ( ?\` . calc-embedded-edit )
1167 ( ?: . calc-grab-sum-down )
1168 ( ?_ . calc-grab-sum-across )
1169 ( ?0 . calc-reset )
1170 ( ?? . calc-dispatch-help )
1171 ( ?# . calc-same-interface )
1172 ( ?& . calc-same-interface )
1173 ( ?\\ . calc-same-interface )
1174 ( ?= . calc-same-interface )
1175 ( ?* . calc-same-interface )
1176 ( ?/ . calc-same-interface )
1177 ( ?+ . calc-same-interface )
1178 ( ?- . calc-same-interface ) ))
1179 map)
1180 "The key map for starting Calc.")
1183 ;;;; (Autoloads here)
1184 (load "calc-loaddefs.el" nil t)
1186 ;;;###autoload (define-key ctl-x-map "*" 'calc-dispatch)
1188 ;;;###autoload
1189 (defun calc-dispatch (&optional _arg)
1190 "Invoke the GNU Emacs Calculator. See \\[calc-dispatch-help] for details."
1191 (interactive)
1192 ; (sit-for echo-keystrokes)
1193 (ignore-errors ; look for other keys bound to calc-dispatch
1194 (let ((keys (this-command-keys)))
1195 (unless (or (not (stringp keys))
1196 (string-match "\\`\C-u\\|\\`\e[-0-9#]\\|`[\M--\M-0-\M-9]" keys)
1197 (eq (lookup-key calc-dispatch-map keys) 'calc-same-interface))
1198 (when (and (string-match "\\`[\C-@-\C-_]" keys)
1199 (symbolp
1200 (lookup-key calc-dispatch-map (substring keys 0 1))))
1201 (define-key calc-dispatch-map (substring keys 0 1) nil))
1202 (define-key calc-dispatch-map keys 'calc-same-interface))))
1203 (calc-do-dispatch))
1205 (defvar calc-dispatch-help nil)
1206 (defun calc-do-dispatch (&optional _arg)
1207 "Start the Calculator."
1208 (let ((key (calc-read-key-sequence
1209 (if calc-dispatch-help
1210 "Calc options: Calc, Keypad, Quick, Embed; eXit; Info, Tutorial; Grab; ?=more"
1211 (format "%s (Type ? for a list of Calc options)"
1212 (key-description (this-command-keys))))
1213 calc-dispatch-map)))
1214 (setq key (lookup-key calc-dispatch-map key))
1215 (message "")
1216 (if key
1217 (progn
1218 (or (commandp key) (require 'calc-ext))
1219 (call-interactively key))
1220 (beep))))
1222 (defun calc-read-key-sequence (prompt map)
1223 "Read keys, with prompt PROMPT and keymap MAP."
1224 (let ((glob (current-global-map))
1225 (loc (current-local-map)))
1226 (or (input-pending-p) (message "%s" prompt))
1227 (let ((key (calc-read-key t))
1228 (input-method-function nil))
1229 (calc-unread-command (cdr key))
1230 (unwind-protect
1231 (progn
1232 (use-global-map map)
1233 (use-local-map nil)
1234 (read-key-sequence nil))
1235 (use-global-map glob)
1236 (use-local-map loc)))))
1238 (defvar calc-alg-map) ; Defined in calc-ext.el
1241 (defvar calc-embedded-modes) ; Defined in calc-embed.el
1242 (defvar calc-override-minor-modes) ; Defined in calc-embed.el
1243 (defun calc-kill-stack-buffer ()
1244 "Check to see if user wants to kill the Calc stack buffer.
1245 This will look for buffers using the Calc buffer for embedded mode,
1246 and inform the user if there are any.
1247 If the user wants to kill the Calc buffer, this will remove
1248 embedded information from the appropriate buffers and tidy up
1249 the trail buffer."
1250 (let ((cb (current-buffer))
1251 (info-list nil)
1252 ; (plural nil)
1253 (cea calc-embedded-active))
1254 ;; Get a list of all buffers using this buffer for
1255 ;; embedded Calc.
1256 (while cea
1257 (when (and (eq cb (aref (nth 1 (car cea)) 1))
1258 (buffer-name (car (car cea))))
1259 (setq info-list (cons (car cea) info-list)))
1260 (setq cea (cdr cea)))
1261 ;; Eventually, prompt user with a list of buffers using embedded mode.
1262 (when (and
1263 info-list
1264 (yes-or-no-p
1265 (concat "This Calc stack is being used for embedded mode. Kill anyway?")))
1266 (while info-list
1267 (with-current-buffer (car (car info-list))
1268 (when calc-embedded-info
1269 (setq calc-embedded-info nil
1270 mode-line-buffer-identification (car calc-embedded-modes)
1271 truncate-lines (nth 2 calc-embedded-modes)
1272 buffer-read-only nil)
1273 (use-local-map (nth 1 calc-embedded-modes))
1274 (setq minor-mode-overriding-map-alist
1275 (remq calc-override-minor-modes minor-mode-overriding-map-alist))
1276 (let ((str mode-line-buffer-identification))
1277 (setq mode-line-buffer-identification str))
1278 (set-buffer-modified-p (buffer-modified-p))))
1279 (setq calc-embedded-active
1280 (delete (car info-list) calc-embedded-active))
1281 (setq info-list (cdr info-list))))
1282 (if (not info-list)
1283 (progn
1284 (setq calc-buffer-list (delete cb calc-buffer-list))
1285 (if (buffer-live-p calc-trail-buffer)
1286 (with-current-buffer calc-trail-buffer
1287 (if (eq cb calc-main-buffer)
1288 ;; If there are other Calc stacks, make another one
1289 ;; the calc-main-buffer ...
1290 (if calc-buffer-list
1291 (setq calc-main-buffer (car calc-buffer-list))
1292 ;; ... otherwise kill the trail and its windows.
1293 (let ((wl (get-buffer-window-list calc-trail-buffer)))
1294 (while wl
1295 (delete-window (car wl))
1296 (setq wl (cdr wl))))
1297 (kill-buffer calc-trail-buffer)))))
1298 (setq calc-trail-buffer nil)
1299 t))))
1301 (defun calc-mode ()
1302 "Calculator major mode.
1304 This is an RPN calculator featuring arbitrary-precision integer, rational,
1305 floating-point, complex, matrix, and symbolic arithmetic.
1307 RPN calculation: 2 RET 3 + produces 5.
1308 Algebraic style: \\=' 2+3 RET produces 5.
1310 Basic operators are +, -, *, /, ^, & (reciprocal), % (modulo), n (change-sign).
1312 Press ? repeatedly for more complete help. Press `h i' to read the
1313 Calc manual on-line, `h s' to read the summary, or `h t' for the tutorial.
1315 Notations: 3.14e6 3.14 * 10^6
1316 _23 negative number -23 (or type `23 n')
1317 17:3 the fraction 17/3
1318 5:2:3 the fraction 5 and 2/3
1319 16#12C the integer 12C base 16 = 300 base 10
1320 8#177:100 the fraction 177:100 base 8 = 127:64 base 10
1321 (2, 4) complex number 2 + 4i
1322 (2; 4) polar complex number (r; theta)
1323 [1, 2, 3] vector ([[1, 2], [3, 4]] is a matrix)
1324 [1 .. 4) semi-open interval, 1 <= x < 4
1325 2 +/- 3 (p key) number with mean 2, standard deviation 3
1326 2 mod 3 (M key) number 2 computed modulo 3
1327 <1 jan 91> Date form (enter using \\=' key)
1330 \\{calc-mode-map}
1332 (interactive)
1333 (mapc (function ;FIXME: Why (set-default v (symbol-value v)) ?!?!?
1334 (lambda (v) (set-default v (symbol-value v)))) calc-local-var-list)
1335 (kill-all-local-variables)
1336 (use-local-map (if (eq calc-algebraic-mode 'total)
1337 (progn (require 'calc-ext) calc-alg-map) calc-mode-map))
1338 (mapc #'make-local-variable calc-local-var-list)
1339 (make-local-variable 'overlay-arrow-position)
1340 (make-local-variable 'overlay-arrow-string)
1341 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
1342 (add-hook 'kill-buffer-query-functions
1343 'calc-kill-stack-buffer
1344 t t)
1345 (setq truncate-lines t)
1346 (setq buffer-read-only t)
1347 (setq major-mode 'calc-mode)
1348 (setq mode-name "Calculator")
1349 (setq calc-stack-top (length (or (memq (assq 'top-of-stack calc-stack)
1350 calc-stack)
1351 (setq calc-stack (list (list 'top-of-stack
1352 1 nil))))))
1353 (setq calc-stack-top (- (length calc-stack) calc-stack-top -1))
1354 (or calc-loaded-settings-file
1355 (null calc-settings-file)
1356 (equal calc-settings-file user-init-file)
1357 (progn
1358 (setq calc-loaded-settings-file t)
1359 (load (file-name-sans-extension calc-settings-file) t))) ; t = missing-ok
1360 (let ((p command-line-args))
1361 (while p
1362 (and (equal (car p) "-f")
1363 (string-match "calc" (nth 1 p))
1364 (string-match "full" (nth 1 p))
1365 (setq calc-standalone-flag t))
1366 (setq p (cdr p))))
1367 (require 'calc-menu)
1368 (run-mode-hooks 'calc-mode-hook)
1369 (calc-refresh t)
1370 (calc-set-mode-line)
1371 (calc-check-defines)
1372 (if calc-buffer-list (setq calc-stack (copy-sequence calc-stack)))
1373 (add-to-list 'calc-buffer-list (current-buffer) t))
1375 (defvar calc-check-defines 'calc-check-defines) ; Suitable for run-hooks.
1376 (defun calc-check-defines ()
1377 (if (symbol-plist 'calc-define)
1378 (let ((plist (copy-sequence (symbol-plist 'calc-define))))
1379 (while (and plist (null (nth 1 plist)))
1380 (setq plist (cdr (cdr plist))))
1381 (if plist
1382 (save-excursion
1383 (require 'calc-ext)
1384 (require 'calc-macs)
1385 (set-buffer "*Calculator*")
1386 (while plist
1387 (put 'calc-define (car plist) nil)
1388 (eval (nth 1 plist))
1389 (setq plist (cdr (cdr plist))))
1390 ;; See if this has added any more calc-define properties.
1391 (calc-check-defines))
1392 (setplist 'calc-define nil)))))
1394 (defvar calc-trail-mode-map
1395 (let ((map (make-sparse-keymap)))
1396 (set-keymap-parent map calc-mode-map)
1397 map))
1399 (define-derived-mode calc-trail-mode fundamental-mode "Calc Trail"
1400 "Calc Trail mode.
1401 This mode is used by the *Calc Trail* buffer, which records all results
1402 obtained by the GNU Emacs Calculator.
1404 Calculator commands beginning with the `t' key are used to manipulate
1405 the Trail.
1407 This buffer uses the same key map as the *Calculator* buffer; calculator
1408 commands given here will actually operate on the *Calculator* stack."
1409 (setq truncate-lines t)
1410 (setq buffer-read-only t)
1411 (make-local-variable 'overlay-arrow-position)
1412 (make-local-variable 'overlay-arrow-string)
1413 (when (= (buffer-size) 0)
1414 (let ((buffer-read-only nil))
1415 (insert (propertize "Emacs Calculator Trail\n" 'face 'italic)))))
1417 (defun calc-create-buffer ()
1418 "Create and initialize a buffer for the Calculator."
1419 (set-buffer (get-buffer-create "*Calculator*"))
1420 (or (derived-mode-p 'calc-mode)
1421 (calc-mode))
1422 (setq max-lisp-eval-depth (max max-lisp-eval-depth 1000))
1423 (when calc-always-load-extensions
1424 (require 'calc-ext))
1425 (when calc-language
1426 (require 'calc-ext)
1427 (calc-set-language calc-language calc-language-option t)))
1429 ;;;###autoload
1430 (defun calc (&optional arg full-display interactive)
1431 "The Emacs Calculator. Full documentation is listed under \"calc-mode\"."
1432 (interactive "P\ni\np")
1433 (if arg
1434 (unless (eq arg 0)
1435 (require 'calc-ext)
1436 (if (= (prefix-numeric-value arg) -1)
1437 (calc-grab-region (region-beginning) (region-end) nil)
1438 (when (= (prefix-numeric-value arg) -2)
1439 (calc-keypad))))
1440 (when (get-buffer-window "*Calc Keypad*")
1441 (calc-keypad)
1442 (set-buffer (window-buffer)))
1443 (if (derived-mode-p 'calc-mode)
1444 (calc-quit)
1445 (calc-create-buffer)
1446 (setq calc-was-keypad-mode nil)
1447 (if (or (eq full-display t)
1448 (and (null full-display) calc-full-mode))
1449 (switch-to-buffer (current-buffer) t)
1450 (if (get-buffer-window (current-buffer))
1451 (select-window (get-buffer-window (current-buffer)))
1452 (if calc-window-hook
1453 (run-hooks 'calc-window-hook)
1454 (let ((w (get-largest-window)))
1455 (if (and pop-up-windows
1456 (> (window-height w)
1457 (+ window-min-height calc-window-height 2)))
1458 (progn
1459 (setq w (split-window w
1460 (- (window-height w)
1461 calc-window-height 2)
1462 nil))
1463 (set-window-buffer w (current-buffer))
1464 (select-window w))
1465 (pop-to-buffer (current-buffer)))))))
1466 (with-current-buffer (calc-trail-buffer)
1467 (and calc-display-trail
1468 (= (window-width) (frame-width))
1469 (calc-trail-display 1 t)))
1470 (message "Welcome to the GNU Emacs Calculator! Press `?' or `h' for help, `q' to quit")
1471 (run-hooks 'calc-start-hook)
1472 (and (windowp full-display)
1473 (window-point full-display)
1474 (select-window full-display))
1475 (calc-check-defines)
1476 (when (and calc-said-hello interactive)
1477 (sit-for 2)
1478 (message ""))
1479 (setq calc-said-hello t))))
1481 ;;;###autoload
1482 (defun full-calc (&optional interactive)
1483 "Invoke the Calculator and give it a full-sized window."
1484 (interactive "p")
1485 (calc nil t interactive))
1487 (defun calc-same-interface (arg)
1488 "Invoke the Calculator using the most recent interface (calc or calc-keypad)."
1489 (interactive "P")
1490 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1491 (> (recursion-depth) 0))
1492 (exit-recursive-edit)
1493 (if (derived-mode-p 'calc-edit-mode)
1494 (calc-edit-finish arg)
1495 (if calc-was-keypad-mode
1496 (calc-keypad)
1497 (calc arg calc-full-mode t)))))
1499 (defun calc-quit (&optional non-fatal interactive)
1500 "Quit the Calculator in an appropriate manner."
1501 (interactive "i\np")
1502 (and calc-standalone-flag (not non-fatal)
1503 (save-buffers-kill-emacs nil))
1504 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1505 (> (recursion-depth) 0))
1506 (exit-recursive-edit))
1507 (if (derived-mode-p 'calc-edit-mode)
1508 (calc-edit-cancel)
1509 (if (and interactive
1510 calc-embedded-info
1511 (eq (current-buffer) (aref calc-embedded-info 0)))
1512 (calc-embedded nil)
1513 (unless (derived-mode-p 'calc-mode)
1514 (calc-create-buffer))
1515 (run-hooks 'calc-end-hook)
1516 (if (integerp calc-undo-length)
1517 (cond
1518 ((= calc-undo-length 0)
1519 (setq calc-undo-list nil calc-redo-list nil))
1520 ((> calc-undo-length 0)
1521 (let ((tail (nthcdr (1- calc-undo-length) calc-undo-list)))
1522 (if tail (setcdr tail nil)))
1523 (setq calc-redo-list nil))))
1524 (mapc (function (lambda (v) (set-default v (symbol-value v))))
1525 calc-local-var-list)
1526 (let ((buf (current-buffer))
1527 (win (get-buffer-window (current-buffer)))
1528 (kbuf (get-buffer "*Calc Keypad*")))
1529 (delete-windows-on (calc-trail-buffer))
1530 ;; The next few lines will set `calc-window-height' so that the
1531 ;; next time Calc is called, the window will be the same size
1532 ;; as the current window.
1533 (if (and win
1534 (not (window-full-height-p win))
1535 (window-full-width-p win) ; avoid calc-keypad
1536 (not (get-buffer-window "*Calc Keypad*")))
1537 (setq calc-window-height (- (window-height win) 2)))
1538 (progn
1539 (delete-windows-on buf)
1540 (and kbuf (delete-windows-on kbuf)))
1541 (bury-buffer buf)
1542 (bury-buffer calc-trail-buffer)
1543 (and kbuf (bury-buffer kbuf))))))
1545 ;;;###autoload
1546 (defun quick-calc (&optional insert)
1547 "Do a quick calculation in the minibuffer without invoking full Calculator.
1548 With prefix argument INSERT, insert the result in the current
1549 buffer. Otherwise, the result is copied into the kill ring."
1550 (interactive "P")
1551 (calc-do-quick-calc insert))
1553 ;;;###autoload
1554 (defun calc-eval (str &optional separator &rest args)
1555 "Do a quick calculation and return the result as a string.
1556 Return value will either be the formatted result in string form,
1557 or a list containing a character position and an error message in string form."
1558 (calc-do-calc-eval str separator args))
1560 ;;;###autoload
1561 (defun calc-keypad (&optional interactive)
1562 "Invoke the Calculator in \"visual keypad\" mode.
1563 This is most useful in the X window system.
1564 In this mode, click on the Calc \"buttons\" using the left mouse button.
1565 Or, position the cursor manually and do M-x calc-keypad-press."
1566 (interactive "p")
1567 (require 'calc-ext)
1568 (calc-do-keypad calc-full-mode interactive))
1570 ;;;###autoload
1571 (defun full-calc-keypad (&optional interactive)
1572 "Invoke the Calculator in full-screen \"visual keypad\" mode.
1573 See calc-keypad for details."
1574 (interactive "p")
1575 (require 'calc-ext)
1576 (calc-do-keypad t interactive))
1579 (defvar calc-aborted-prefix nil)
1580 (defvar calc-start-time nil)
1581 (defvar calc-command-flags nil)
1582 (defvar calc-final-point-line)
1583 (defvar calc-final-point-column)
1584 ;;; Note that modifications to this function may break calc-pass-errors.
1585 (defun calc-do (do-body &optional do-slow)
1586 (calc-check-defines)
1587 (let* ((calc-command-flags nil)
1588 (calc-start-time (and calc-timing (not calc-start-time)
1589 (require 'calc-ext)
1590 (current-time-string)))
1591 (gc-cons-threshold (max gc-cons-threshold
1592 (if calc-timing 2000000 100000)))
1593 calc-final-point-line calc-final-point-column)
1594 (setq calc-aborted-prefix "")
1595 (unwind-protect
1596 (condition-case err
1597 (save-excursion
1598 (if calc-embedded-info
1599 (calc-embedded-select-buffer)
1600 (calc-select-buffer))
1601 (and (eq calc-algebraic-mode 'total)
1602 (require 'calc-ext)
1603 (use-local-map calc-alg-map))
1604 (when (and do-slow calc-display-working-message)
1605 (message "Working...")
1606 (calc-set-command-flag 'clear-message))
1607 (funcall do-body)
1608 (setq calc-aborted-prefix nil)
1609 (when (memq 'renum-stack calc-command-flags)
1610 (calc-renumber-stack))
1611 (when (memq 'clear-message calc-command-flags)
1612 (message "")))
1613 (error
1614 (if (and (eq (car err) 'error)
1615 (stringp (nth 1 err))
1616 (string-match "max-specpdl-size\\|max-lisp-eval-depth"
1617 (nth 1 err)))
1618 (error "Computation got stuck or ran too long. Type `M' to increase the limit")
1619 (setq calc-aborted-prefix nil)
1620 (signal (car err) (cdr err)))))
1621 (when calc-aborted-prefix
1622 (calc-record "<Aborted>" calc-aborted-prefix))
1623 (and calc-start-time
1624 (let* ((calc-internal-prec 12)
1625 (calc-date-format nil)
1626 (end-time (current-time-string))
1627 (time (if (equal calc-start-time end-time)
1629 (math-sub
1630 (calcFunc-unixtime (math-parse-date end-time) 0)
1631 (calcFunc-unixtime (math-parse-date calc-start-time)
1632 0)))))
1633 (if (math-lessp 1 time)
1634 (calc-record time "(t)"))))
1635 (or (memq 'no-align calc-command-flags)
1636 (derived-mode-p 'calc-trail-mode)
1637 (calc-align-stack-window))
1638 (and (memq 'position-point calc-command-flags)
1639 (if (derived-mode-p 'calc-mode)
1640 (progn
1641 (goto-char (point-min))
1642 (forward-line (1- calc-final-point-line))
1643 (move-to-column calc-final-point-column))
1644 (save-current-buffer
1645 (calc-select-buffer)
1646 (goto-char (point-min))
1647 (forward-line (1- calc-final-point-line))
1648 (move-to-column calc-final-point-column))))
1649 (unless (memq 'keep-flags calc-command-flags)
1650 (save-excursion
1651 (calc-select-buffer)
1652 (setq calc-inverse-flag nil
1653 calc-hyperbolic-flag nil
1654 calc-option-flag nil
1655 calc-keep-args-flag nil)))
1656 (when (memq 'do-edit calc-command-flags)
1657 (switch-to-buffer (get-buffer-create "*Calc Edit*")))
1658 (calc-set-mode-line)
1659 (when calc-embedded-info
1660 (calc-embedded-finish-command))))
1661 (identity nil)) ; allow a GC after timing is done
1664 (defun calc-set-command-flag (f)
1665 (unless (memq f calc-command-flags)
1666 (setq calc-command-flags (cons f calc-command-flags))))
1668 (defun calc-select-buffer ()
1669 (or (derived-mode-p 'calc-mode)
1670 (if calc-main-buffer
1671 (set-buffer calc-main-buffer)
1672 (let ((buf (get-buffer "*Calculator*")))
1673 (if buf
1674 (set-buffer buf)
1675 (error "Calculator buffer not available"))))))
1677 (defun calc-cursor-stack-index (&optional index)
1678 (goto-char (point-max))
1679 (forward-line (- (calc-substack-height (or index 1)))))
1681 (defun calc-stack-size ()
1682 (- (length calc-stack) calc-stack-top))
1684 (defun calc-substack-height (n)
1685 (let ((sum 0)
1686 (stack calc-stack))
1687 (setq n (+ n calc-stack-top))
1688 (while (and (> n 0) stack)
1689 (setq sum (+ sum (nth 1 (car stack)))
1690 n (1- n)
1691 stack (cdr stack)))
1692 sum))
1694 (defun calc-set-mode-line ()
1695 (save-excursion
1696 (calc-select-buffer)
1697 (let* ((fmt (car calc-float-format))
1698 (figs (nth 1 calc-float-format))
1699 (new-mode-string
1700 (format "Calc%s%s: %d %s %-14s"
1701 (if (and calc-embedded-info
1702 (eq (aref calc-embedded-info 1) (current-buffer)))
1703 "Embed" "")
1704 (if (and (> (length (buffer-name)) 12)
1705 (equal (substring (buffer-name) 0 12)
1706 "*Calculator*"))
1707 (substring (buffer-name) 12)
1709 calc-internal-prec
1710 (capitalize (symbol-name calc-angle-mode))
1711 (concat
1713 ;; Input-related modes
1714 (if (eq calc-algebraic-mode 'total) "Alg* "
1715 (if calc-algebraic-mode "Alg "
1716 (if calc-incomplete-algebraic-mode "Alg[( " "")))
1718 ;; Computational modes
1719 (if calc-symbolic-mode "Symb " "")
1720 (cond ((eq calc-matrix-mode 'matrix) "Matrix ")
1721 ((integerp calc-matrix-mode)
1722 (format "Matrix%d " calc-matrix-mode))
1723 ((eq calc-matrix-mode 'sqmatrix) "SqMatrix ")
1724 ((eq calc-matrix-mode 'scalar) "Scalar ")
1725 (t ""))
1726 (if (eq calc-complex-mode 'polar) "Polar " "")
1727 (if calc-prefer-frac "Frac " "")
1728 (cond ((null calc-infinite-mode) "")
1729 ((eq calc-infinite-mode 1) "+Inf ")
1730 (t "Inf "))
1731 (cond ((eq calc-simplify-mode 'none) "NoSimp ")
1732 ((eq calc-simplify-mode 'num) "NumSimp ")
1733 ((eq calc-simplify-mode 'binary)
1734 (format "BinSimp%d " calc-word-size))
1735 ((eq calc-simplify-mode 'alg) "")
1736 ((eq calc-simplify-mode 'ext) "ExtSimp ")
1737 ((eq calc-simplify-mode 'units) "UnitSimp ")
1738 (t "BasicSimp "))
1740 ;; Display modes
1741 (cond ((= calc-number-radix 10) "")
1742 ((= calc-number-radix 2) "Bin ")
1743 ((= calc-number-radix 8) "Oct ")
1744 ((= calc-number-radix 16) "Hex ")
1745 (t (format "Radix%d " calc-number-radix)))
1746 (if calc-twos-complement-mode "TwosComp " "")
1747 (if calc-leading-zeros "Zero " "")
1748 (cond ((null calc-language) "")
1749 ((get calc-language 'math-lang-name)
1750 (concat (get calc-language 'math-lang-name) " "))
1751 (t (concat
1752 (capitalize (symbol-name calc-language))
1753 " ")))
1754 (cond ((eq fmt 'float)
1755 (if (zerop figs) "" (format "Norm%d " figs)))
1756 ((eq fmt 'fix) (format "Fix%d " figs))
1757 ((eq fmt 'sci)
1758 (if (zerop figs) "Sci " (format "Sci%d " figs)))
1759 ((eq fmt 'eng)
1760 (if (zerop figs) "Eng " (format "Eng%d " figs))))
1761 (cond ((not calc-display-just)
1762 (if calc-display-origin
1763 (format "Left%d " calc-display-origin) ""))
1764 ((eq calc-display-just 'right)
1765 (if calc-display-origin
1766 (format "Right%d " calc-display-origin)
1767 "Right "))
1769 (if calc-display-origin
1770 (format "Center%d " calc-display-origin)
1771 "Center ")))
1772 (cond ((integerp calc-line-breaking)
1773 (format "Wid%d " calc-line-breaking))
1774 (calc-line-breaking "")
1775 (t "Wide "))
1777 ;; Miscellaneous other modes/indicators
1778 (if calc-assoc-selections "" "Break ")
1779 (cond ((eq calc-mode-save-mode 'save) "Save ")
1780 ((not calc-embedded-info) "")
1781 ((eq calc-mode-save-mode 'local) "Local ")
1782 ((eq calc-mode-save-mode 'edit) "LocEdit ")
1783 ((eq calc-mode-save-mode 'perm) "LocPerm ")
1784 ((eq calc-mode-save-mode 'global) "Global ")
1785 (t ""))
1786 (if calc-auto-recompute "" "Manual ")
1787 (if (and (fboundp 'calc-gnuplot-alive)
1788 (calc-gnuplot-alive)) "Graph " "")
1789 (if (and calc-embedded-info
1790 (> (calc-stack-size) 0)
1791 (calc-top 1 'sel)) "Sel " "")
1792 (if calc-display-dirty "Dirty " "")
1793 (if calc-option-flag "Opt " "")
1794 (if calc-inverse-flag "Inv " "")
1795 (if calc-hyperbolic-flag "Hyp " "")
1796 (if calc-keep-args-flag "Keep " "")
1797 (if (/= calc-stack-top 1) "Narrow " "")
1798 (apply 'concat calc-other-modes)))))
1799 (if (equal new-mode-string mode-line-buffer-identification)
1801 (setq mode-line-buffer-identification new-mode-string)
1802 (set-buffer-modified-p (buffer-modified-p))
1803 (and calc-embedded-info (calc-embedded-mode-line-change))))))
1805 (defun calc-align-stack-window ()
1806 (if (derived-mode-p 'calc-mode)
1807 (progn
1808 (let ((win (get-buffer-window (current-buffer))))
1809 (if win
1810 (progn
1811 (calc-cursor-stack-index 0)
1812 (vertical-motion (- 2 (window-height win)))
1813 (set-window-start win (point)))))
1814 (calc-cursor-stack-index 0)
1815 (if (looking-at " *\\.$")
1816 (goto-char (1- (match-end 0)))))
1817 (save-excursion
1818 (calc-select-buffer)
1819 (calc-align-stack-window))))
1821 (defun calc-check-stack (n)
1822 (if (> n (calc-stack-size))
1823 (error "Too few elements on stack"))
1824 (if (< n 0)
1825 (error "Invalid argument")))
1827 (defun calc-push-list (vals &optional m sels)
1828 (while vals
1829 (if calc-executing-macro
1830 (calc-push-list-in-macro vals m sels)
1831 (save-excursion
1832 (calc-select-buffer)
1833 (let* ((val (car vals))
1834 (entry (list val 1 (car sels)))
1835 (mm (+ (or m 1) calc-stack-top)))
1836 (calc-cursor-stack-index (1- (or m 1)))
1837 (if (> mm 1)
1838 (setcdr (nthcdr (- mm 2) calc-stack)
1839 (cons entry (nthcdr (1- mm) calc-stack)))
1840 (setq calc-stack (cons entry calc-stack)))
1841 (let ((buffer-read-only nil))
1842 (insert (math-format-stack-value entry) "\n"))
1843 (calc-record-undo (list 'push mm))
1844 (calc-set-command-flag 'renum-stack))))
1845 (setq vals (cdr vals)
1846 sels (cdr sels))))
1848 (defun calc-pop-push-list (n vals &optional m sels)
1849 (if (and calc-any-selections (null sels))
1850 (calc-replace-selections n vals m)
1851 (calc-pop-stack n m sels)
1852 (calc-push-list vals m sels)))
1854 (defun calc-pop-push-record-list (n prefix vals &optional m sels)
1855 (or (and (consp vals)
1856 (or (integerp (car vals))
1857 (consp (car vals))))
1858 (and vals (setq vals (list vals)
1859 sels (and sels (list sels)))))
1860 (calc-check-stack (+ n (or m 1) -1))
1861 (if prefix
1862 (if (cdr vals)
1863 (calc-record-list vals prefix)
1864 (calc-record (car vals) prefix)))
1865 (calc-pop-push-list n vals m sels))
1867 (defun calc-enter-result (n prefix vals &optional m)
1868 (setq calc-aborted-prefix prefix)
1869 (if (and (consp vals)
1870 (or (integerp (car vals))
1871 (consp (car vals))))
1872 (setq vals (mapcar 'calc-normalize vals))
1873 (setq vals (calc-normalize vals)))
1874 (or (and (consp vals)
1875 (or (integerp (car vals))
1876 (consp (car vals))))
1877 (setq vals (list vals)))
1878 (if (equal vals '((nil)))
1879 (setq vals nil))
1880 (calc-pop-push-record-list n prefix vals m)
1881 (calc-handle-whys))
1883 (defun calc-normalize (val)
1884 (if (memq calc-simplify-mode '(nil none num))
1885 (math-normalize val)
1886 (require 'calc-ext)
1887 (calc-normalize-fancy val)))
1889 (defun calc-handle-whys ()
1890 (if calc-next-why
1891 (calc-do-handle-whys)))
1894 (defun calc-pop-stack (&optional n m sel-ok) ; pop N objs at level M of stack.
1895 (or n (setq n 1))
1896 (or m (setq m 1))
1897 (or calc-keep-args-flag
1898 (let ((mm (+ m calc-stack-top)))
1899 (if (and calc-any-selections (not sel-ok)
1900 (calc-top-selected n m))
1901 (calc-sel-error))
1902 (if calc-executing-macro
1903 (calc-pop-stack-in-macro n mm)
1904 (calc-record-undo (list 'pop mm (calc-top-list n m 'full)))
1905 (save-excursion
1906 (calc-select-buffer)
1907 (let ((buffer-read-only nil))
1908 (if (> mm 1)
1909 (progn
1910 (calc-cursor-stack-index (1- m))
1911 (let ((bot (point)))
1912 (calc-cursor-stack-index (+ n m -1))
1913 (delete-region (point) bot))
1914 (setcdr (nthcdr (- mm 2) calc-stack)
1915 (nthcdr (+ n mm -1) calc-stack)))
1916 (calc-cursor-stack-index n)
1917 (setq calc-stack (nthcdr n calc-stack))
1918 (delete-region (point) (point-max))))
1919 (calc-set-command-flag 'renum-stack))))))
1921 (defun calc-get-stack-element (x &optional sel-mode)
1922 (cond ((eq sel-mode 'entry)
1924 ((eq sel-mode 'sel)
1925 (nth 2 x))
1926 ((or (null (nth 2 x))
1927 (eq sel-mode 'full)
1928 (not calc-use-selections))
1929 (car x))
1930 (sel-mode
1931 (calc-sel-error))
1932 (t (nth 2 x))))
1934 ;; Get the Nth element of the stack (N=1 is the top element).
1935 (defun calc-top (&optional n sel-mode)
1936 (or n (setq n 1))
1937 (calc-check-stack n)
1938 (calc-get-stack-element (nth (+ n calc-stack-top -1) calc-stack) sel-mode))
1940 (defun calc-top-n (&optional n sel-mode) ; In case precision has changed.
1941 (math-check-complete (calc-normalize (calc-top n sel-mode))))
1943 (defun calc-top-list (&optional n m sel-mode)
1944 (or n (setq n 1))
1945 (or m (setq m 1))
1946 (calc-check-stack (+ n m -1))
1947 (and (> n 0)
1948 (let ((top (copy-sequence (nthcdr (+ m calc-stack-top -1)
1949 calc-stack))))
1950 (setcdr (nthcdr (1- n) top) nil)
1951 (nreverse
1952 (mapcar (lambda (x) (calc-get-stack-element x sel-mode)) top)))))
1954 (defun calc-top-list-n (&optional n m sel-mode)
1955 (mapcar 'math-check-complete
1956 (mapcar 'calc-normalize (calc-top-list n m sel-mode))))
1959 (defun calc-renumber-stack ()
1960 (if calc-line-numbering
1961 (save-excursion
1962 (calc-cursor-stack-index 0)
1963 (let ((lnum 1)
1964 (buffer-read-only nil)
1965 (stack (nthcdr calc-stack-top calc-stack)))
1966 (if (re-search-forward "^[0-9]+[:*]" nil t)
1967 (progn
1968 (beginning-of-line)
1969 (while (re-search-forward "^[0-9]+[:*]" nil t)
1970 (let ((buffer-read-only nil))
1971 (beginning-of-line)
1972 (delete-char 4)
1973 (insert " ")))
1974 (calc-cursor-stack-index 0)))
1975 (while (re-search-backward "^[0-9]+[:*]" nil t)
1976 (delete-char 4)
1977 (if (> lnum 999)
1978 (insert (format "%03d%s" (% lnum 1000)
1979 (if (and (nth 2 (car stack))
1980 calc-use-selections) "*" ":")))
1981 (let ((prefix (int-to-string lnum)))
1982 (insert prefix (if (and (nth 2 (car stack))
1983 calc-use-selections) "*" ":")
1984 (make-string (- 3 (length prefix)) 32))))
1985 (beginning-of-line)
1986 (setq lnum (1+ lnum)
1987 stack (cdr stack))))))
1988 (and calc-embedded-info (calc-embedded-stack-change)))
1990 (defvar calc-any-evaltos nil)
1991 (defun calc-refresh (&optional align)
1992 (interactive)
1993 (and (derived-mode-p 'calc-mode)
1994 (not calc-executing-macro)
1995 (let* ((inhibit-read-only t)
1996 (save-point (point))
1997 (save-mark (ignore-errors (mark)))
1998 (save-aligned (looking-at "\\.$"))
1999 (thing calc-stack)
2000 (calc-any-evaltos nil))
2001 (setq calc-any-selections nil)
2002 (erase-buffer)
2003 (when calc-show-banner
2004 (insert (propertize "--- Emacs Calculator Mode ---\n"
2005 'face 'italic)))
2006 (while thing
2007 (goto-char (point-min))
2008 (when calc-show-banner
2009 (forward-line 1))
2010 (insert (math-format-stack-value (car thing)) "\n")
2011 (setq thing (cdr thing)))
2012 (calc-renumber-stack)
2013 (if calc-display-dirty
2014 (calc-wrapper (setq calc-display-dirty nil)))
2015 (and calc-any-evaltos calc-auto-recompute
2016 (calc-wrapper (calc-refresh-evaltos)))
2017 (if (or align save-aligned)
2018 (calc-align-stack-window)
2019 (goto-char save-point))
2020 (if save-mark (set-mark save-mark))))
2021 (and calc-embedded-info (not (derived-mode-p 'calc-mode))
2022 (with-current-buffer (aref calc-embedded-info 1)
2023 (calc-refresh align)))
2024 (setq calc-refresh-count (1+ calc-refresh-count)))
2026 ;; Dates that are built-in options for `calc-gregorian-switch' should be
2027 ;; (YEAR MONTH DAY math-date-from-gregorian-dt(YEAR MONTH DAY)) for speed.
2028 (defcustom calc-gregorian-switch nil
2029 "The first day the Gregorian calendar is used by Calc's date forms.
2030 This is nil (the default) if the Gregorian calendar is the only one used.
2031 Otherwise, it should be a list `(YEAR MONTH DAY)' when Calc begins to use
2032 the Gregorian calendar; Calc will use the Julian calendar for earlier dates.
2033 The dates in which different regions of the world began to use the
2034 Gregorian calendar vary quite a bit, even within a single country.
2035 If you want Calc's date forms to switch between the Julian and
2036 Gregorian calendar, you can specify the date or choose from several
2037 common choices. Some of these choices should be taken with a grain
2038 of salt; for example different parts of France changed calendars at
2039 different times, and Sweden's change to the Gregorian calendar was
2040 complicated. Also, the boundaries of the countries were different at
2041 the times of the calendar changes than they are now.
2042 The Vatican decided that the Gregorian calendar should take effect
2043 on 15 October 1582 (Gregorian), and many Catholic countries made
2044 the change then. Great Britain and its colonies had the Gregorian
2045 calendar take effect on 14 September 1752 (Gregorian); this includes
2046 the United States."
2047 :group 'calc
2048 :version "24.4"
2049 :type '(choice (const :tag "Always use the Gregorian calendar" nil)
2050 (const :tag "1582-10-15 - Italy, Poland, Portugal, Spain" (1582 10 15 577736))
2051 (const :tag "1582-12-20 - France" (1582 12 20 577802))
2052 (const :tag "1582-12-25 - Luxemburg" (1582 12 25 577807))
2053 (const :tag "1584-01-17 - Bohemia and Moravia" (1584 1 17 578195))
2054 (const :tag "1587-11-01 - Hungary" (1587 11 1 579579))
2055 (const :tag "1700-03-01 - Denmark" (1700 3 1 620607))
2056 (const :tag "1701-01-12 - Protestant Switzerland" (1701 1 12 620924))
2057 (const :tag "1752-09-14 - Great Britain and dominions" (1752 9 14 639797))
2058 (const :tag "1753-03-01 - Sweden" (1753 3 1 639965))
2059 (const :tag "1918-02-14 - Russia" (1918 2 14 700214))
2060 (const :tag "1919-04-14 - Romania" (1919 4 14 700638))
2061 (list :tag "(YEAR MONTH DAY)"
2062 (integer :tag "Year")
2063 (integer :tag "Month (integer)")
2064 (integer :tag "Day")))
2065 :set (lambda (symbol value)
2066 (set-default symbol value)
2067 (setq math-format-date-cache nil)
2068 (calc-refresh)))
2070 ;;;; The Calc Trail buffer.
2072 (defun calc-check-trail-aligned ()
2073 (save-excursion
2074 (let ((win (get-buffer-window (current-buffer))))
2075 (and win
2076 (pos-visible-in-window-p (1- (point-max)) win)))))
2078 (defun calc-trail-buffer ()
2079 (and (or (null calc-trail-buffer)
2080 (null (buffer-name calc-trail-buffer)))
2081 (save-excursion
2082 (setq calc-trail-buffer (get-buffer-create "*Calc Trail*"))
2083 (let ((buf (or (and (not (derived-mode-p 'calc-mode))
2084 (get-buffer "*Calculator*"))
2085 (current-buffer))))
2086 (set-buffer calc-trail-buffer)
2087 (unless (derived-mode-p 'calc-trail-mode)
2088 (calc-trail-mode)
2089 (set (make-local-variable 'calc-main-buffer) buf)))))
2090 (or (and calc-trail-pointer
2091 (eq (marker-buffer calc-trail-pointer) calc-trail-buffer))
2092 (with-current-buffer calc-trail-buffer
2093 (goto-char (point-min))
2094 (forward-line 1)
2095 (setq calc-trail-pointer (point-marker))))
2096 calc-trail-buffer)
2098 (defvar calc-can-abbrev-vectors)
2100 (defun calc-record (val &optional prefix)
2101 (setq calc-aborted-prefix nil)
2102 (or calc-executing-macro
2103 (let* ((buf (calc-trail-buffer))
2104 (calc-display-raw nil)
2105 (calc-can-abbrev-vectors t)
2106 (fval (if val
2107 (if (stringp val)
2109 (math-showing-full-precision
2110 (math-format-flat-expr val 0)))
2111 "")))
2112 (with-current-buffer buf
2113 (let ((aligned (calc-check-trail-aligned))
2114 (buffer-read-only nil))
2115 (goto-char (point-max))
2116 (cond ((null prefix) (insert " "))
2117 ((and (> (length prefix) 4)
2118 (string-match " " prefix 4))
2119 (insert (substring prefix 0 4) " "))
2120 (t (insert (format "%4s " prefix))))
2121 (insert fval "\n")
2122 (let ((win (get-buffer-window buf)))
2123 (if (and aligned win (not (memq 'hold-trail calc-command-flags)))
2124 (calc-trail-here))
2125 (goto-char (1- (point-max))))))))
2126 val)
2129 (defun calc-trail-display (flag &optional no-refresh interactive)
2130 (interactive "P\ni\np")
2131 (let ((win (get-buffer-window (calc-trail-buffer))))
2132 (if (setq calc-display-trail
2133 (not (if flag (memq flag '(nil 0)) win)))
2134 (if (null win)
2135 (progn
2136 (if calc-trail-window-hook
2137 (run-hooks 'calc-trail-window-hook)
2138 (let ((w (split-window nil (/ (* (window-width) 2) 3) t)))
2139 (set-window-buffer w calc-trail-buffer)))
2140 (calc-wrapper
2141 (setq overlay-arrow-string calc-trail-overlay
2142 overlay-arrow-position calc-trail-pointer)
2143 (or no-refresh
2144 (if interactive
2145 (calc-do-refresh)
2146 (calc-refresh))))))
2147 (if win
2148 (progn
2149 (delete-window win)
2150 (calc-wrapper
2151 (or no-refresh
2152 (if interactive
2153 (calc-do-refresh)
2154 (calc-refresh))))))))
2155 calc-trail-buffer)
2157 (defun calc-trail-here ()
2158 (interactive)
2159 (if (derived-mode-p 'calc-trail-mode)
2160 (progn
2161 (beginning-of-line)
2162 (if (bobp)
2163 (forward-line 1)
2164 (if (eobp)
2165 (forward-line -1)))
2166 (if (or (bobp) (eobp))
2167 (setq overlay-arrow-position nil) ; trail is empty
2168 (set-marker calc-trail-pointer (point) (current-buffer))
2169 (setq calc-trail-overlay (concat (buffer-substring (point)
2170 (+ (point) 4))
2171 ">")
2172 overlay-arrow-string calc-trail-overlay
2173 overlay-arrow-position calc-trail-pointer)
2174 (forward-char 4)
2175 (let ((win (get-buffer-window (current-buffer))))
2176 (if win
2177 (save-excursion
2178 (forward-line (/ (window-height win) 2))
2179 (forward-line (- 1 (window-height win)))
2180 (set-window-start win (point))
2181 (set-window-point win (+ calc-trail-pointer 4))
2182 (set-buffer calc-main-buffer)
2183 (setq overlay-arrow-string calc-trail-overlay
2184 overlay-arrow-position calc-trail-pointer))))))
2185 (error "Not in Calc Trail buffer")))
2190 ;;;; The Undo list.
2192 (defun calc-record-undo (rec)
2193 (or calc-executing-macro
2194 (if (memq 'undo calc-command-flags)
2195 (setq calc-undo-list (cons (cons rec (car calc-undo-list))
2196 (cdr calc-undo-list)))
2197 (setq calc-undo-list (cons (list rec) calc-undo-list)
2198 calc-redo-list nil)
2199 (calc-set-command-flag 'undo))))
2204 ;;; Arithmetic commands.
2206 (defun calc-binary-op (name func arg &optional ident unary func2)
2207 (setq calc-aborted-prefix name)
2208 (if (null arg)
2209 (calc-enter-result 2 name (cons (or func2 func)
2210 (mapcar 'math-check-complete
2211 (calc-top-list 2))))
2212 (require 'calc-ext)
2213 (calc-binary-op-fancy name func arg ident unary)))
2215 (defun calc-unary-op (name func arg &optional func2)
2216 (setq calc-aborted-prefix name)
2217 (if (null arg)
2218 (calc-enter-result 1 name (list (or func2 func)
2219 (math-check-complete (calc-top 1))))
2220 (require 'calc-ext)
2221 (calc-unary-op-fancy name func arg)))
2224 (defun calc-plus (arg)
2225 (interactive "P")
2226 (calc-slow-wrapper
2227 (calc-binary-op "+" 'calcFunc-add arg 0 nil '+)))
2229 (defun calc-minus (arg)
2230 (interactive "P")
2231 (calc-slow-wrapper
2232 (calc-binary-op "-" 'calcFunc-sub arg 0 'neg '-)))
2234 (defun calc-times (arg)
2235 (interactive "P")
2236 (calc-slow-wrapper
2237 (calc-binary-op "*" 'calcFunc-mul arg 1 nil '*)))
2239 (defun calc-divide (arg)
2240 (interactive "P")
2241 (calc-slow-wrapper
2242 (calc-binary-op "/" 'calcFunc-div arg 0 'calcFunc-inv '/)))
2244 (defun calc-left-divide (arg)
2245 (interactive "P")
2246 (calc-slow-wrapper
2247 (calc-binary-op "ldiv" 'calcFunc-ldiv arg 0 nil nil)))
2249 (defun calc-change-sign (arg)
2250 (interactive "P")
2251 (calc-wrapper
2252 (calc-unary-op "chs" 'neg arg)))
2256 ;;; Stack management commands.
2258 (defun calc-enter (n)
2259 (interactive "p")
2260 (let ((num (if calc-context-sensitive-enter (max 1 (calc-locate-cursor-element (point))))))
2261 (calc-wrapper
2262 (cond ((< n 0)
2263 (calc-push-list (calc-top-list 1 (- n))))
2264 ((= n 0)
2265 (calc-push-list (calc-top-list (calc-stack-size))))
2266 (num
2267 (calc-push-list (calc-top-list n num)))
2269 (calc-push-list (calc-top-list n)))))
2270 (if (and calc-context-sensitive-enter (> n 0)) (calc-cursor-stack-index (+ num n)))))
2272 (defun calc-pop (n)
2273 (interactive "P")
2274 (let ((num (if calc-context-sensitive-enter (max 1 (calc-locate-cursor-element (point))))))
2275 (calc-wrapper
2276 (let* ((nn (prefix-numeric-value n))
2277 (top (and (null n) (calc-top 1))))
2278 (cond ((and calc-context-sensitive-enter (> num 1))
2279 (calc-pop-stack nn num))
2280 ((and (null n)
2281 (eq (car-safe top) 'incomplete)
2282 (> (length top) (if (eq (nth 1 top) 'intv) 3 2)))
2283 (calc-pop-push-list 1 (let ((tt (copy-sequence top)))
2284 (setcdr (nthcdr (- (length tt) 2) tt) nil)
2285 (list tt))))
2286 ((< nn 0)
2287 (if (and calc-any-selections
2288 (calc-top-selected 1 (- nn)))
2289 (calc-delete-selection (- nn))
2290 (calc-pop-stack 1 (- nn) t)))
2291 ((= nn 0)
2292 (calc-pop-stack (calc-stack-size) 1 t))
2294 (if (and calc-any-selections
2295 (= nn 1)
2296 (calc-top-selected 1 1))
2297 (calc-delete-selection 1)
2298 (calc-pop-stack nn))))))
2299 (if calc-context-sensitive-enter (calc-cursor-stack-index (1- num)))))
2305 ;;;; Reading a number using the minibuffer.
2306 (defun calc-digit-start-entry ()
2307 (cond ((eq last-command-event ?e)
2308 (if (> calc-number-radix 14) (format "%d.^" calc-number-radix) "1e"))
2309 ((eq last-command-event ?#) (format "%d#" calc-number-radix))
2310 ((eq last-command-event ?_) "-")
2311 ((eq last-command-event ?@) "0@ ")
2312 (t (char-to-string last-command-event))))
2314 (defvar calc-buffer)
2315 (defvar calc-prev-char)
2316 (defvar calc-prev-prev-char)
2317 (defvar calc-digit-value)
2318 (defun calcDigit-start ()
2319 (interactive)
2320 (calc-wrapper
2321 (if (or calc-algebraic-mode
2322 (and (> calc-number-radix 14) (eq last-command-event ?e)))
2323 (calc-alg-digit-entry)
2324 (setq calc-aborted-prefix nil)
2325 (let* ((calc-digit-value nil)
2326 (calc-prev-char nil)
2327 (calc-prev-prev-char nil)
2328 (calc-buffer (current-buffer))
2329 (buf (if (featurep 'xemacs)
2330 (catch 'calc-foo
2331 (catch 'execute-kbd-macro
2332 (throw 'calc-foo
2333 (read-from-minibuffer
2334 "Calc: " "" calc-digit-map)))
2335 (error "XEmacs requires RET after %s"
2336 "digit entry in kbd macro"))
2337 (let ((old-esc (lookup-key global-map "\e")))
2338 (unwind-protect
2339 (progn
2340 (define-key global-map "\e" nil)
2341 (read-from-minibuffer
2342 "Calc: " (calc-digit-start-entry) calc-digit-map))
2343 (define-key global-map "\e" old-esc))))))
2344 (or calc-digit-value (setq calc-digit-value (math-read-number buf)))
2345 (if (stringp calc-digit-value)
2346 (calc-alg-entry calc-digit-value)
2347 (if calc-digit-value
2348 (calc-push-list (list (calc-record (calc-normalize
2349 calc-digit-value))))))
2350 (if (eq calc-prev-char 'dots)
2351 (progn
2352 (require 'calc-ext)
2353 (calc-dots)))))))
2355 (defsubst calc-minibuffer-size ()
2356 (- (point-max) (minibuffer-prompt-end)))
2358 (defun calcDigit-nondigit ()
2359 (interactive)
2360 ;; Exercise for the reader: Figure out why this is a good precaution!
2361 (or (boundp 'calc-buffer)
2362 (use-local-map minibuffer-local-map))
2363 (let ((str (minibuffer-contents)))
2364 (setq calc-digit-value (with-current-buffer calc-buffer
2365 (math-read-number str))))
2366 (if (and (null calc-digit-value) (> (calc-minibuffer-size) 0))
2367 (progn
2368 (beep)
2369 (calc-temp-minibuffer-message " [Bad format]"))
2370 (or (memq last-command-event '(32 13))
2371 (progn (setq prefix-arg current-prefix-arg)
2372 (calc-unread-command (if (and (eq last-command-event 27)
2373 (>= last-input-event 128))
2374 last-input-event
2375 nil))))
2376 (exit-minibuffer)))
2379 (defun calc-minibuffer-contains (rex)
2380 (save-excursion
2381 (goto-char (minibuffer-prompt-end))
2382 (looking-at rex)))
2384 (defun calcDigit-key ()
2385 (interactive)
2386 (goto-char (point-max))
2387 (if (or (and (memq last-command-event '(?+ ?-))
2388 (> (buffer-size) 0)
2389 (/= (preceding-char) ?e))
2390 (and (memq last-command-event '(?m ?s))
2391 (not (calc-minibuffer-contains "[-+]?[0-9]+\\.?0*[@oh].*"))
2392 (not (calc-minibuffer-contains "[-+]?\\(1[1-9]\\|[2-9][0-9]\\)#.*"))))
2393 (calcDigit-nondigit)
2394 (if (calc-minibuffer-contains "\\([-+]?\\|.* \\)\\'")
2395 (cond ((memq last-command-event '(?. ?@)) (insert "0"))
2396 ((and (memq last-command-event '(?o ?h ?m))
2397 (not (calc-minibuffer-contains ".*#.*"))) (insert "0"))
2398 ((memq last-command-event '(?: ?e)) (insert "1"))
2399 ((eq last-command-event ?#)
2400 (insert (int-to-string calc-number-radix)))))
2401 (if (and (calc-minibuffer-contains "\\([-+]?[0-9]+#\\|[^:]*:\\)\\'")
2402 (eq last-command-event ?:))
2403 (insert "1"))
2404 (if (and (calc-minibuffer-contains "[-+]?[0-9]+#\\'")
2405 (eq last-command-event ?.))
2406 (insert "0"))
2407 (if (and (calc-minibuffer-contains "[-+]?0*\\([2-9]\\|1[0-4]\\)#\\'")
2408 (eq last-command-event ?e))
2409 (insert "1"))
2410 (if (or (and (memq last-command-event '(?h ?o ?m ?s ?p))
2411 (calc-minibuffer-contains ".*#.*"))
2412 (and (eq last-command-event ?e)
2413 (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2414 (and (eq last-command-event ?n)
2415 (calc-minibuffer-contains "[-+]?\\(2[4-9]\\|[3-9][0-9]\\)#.*")))
2416 (setq last-command-event (upcase last-command-event)))
2417 (cond
2418 ((memq last-command-event '(?_ ?n))
2419 (goto-char (minibuffer-prompt-end))
2420 (if (and (search-forward " +/- " nil t)
2421 (not (search-forward "e" nil t)))
2422 (beep)
2423 (and (not (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2424 (search-forward "e" nil t))
2425 (if (looking-at "+")
2426 (delete-char 1))
2427 (if (looking-at "-")
2428 (delete-char 1)
2429 (insert "-")))
2430 (goto-char (point-max)))
2431 ((eq last-command-event ?p)
2432 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2433 (calc-minibuffer-contains ".*mod.*")
2434 (calc-minibuffer-contains ".*#.*")
2435 (calc-minibuffer-contains ".*[-+e:]\\'"))
2436 (beep)
2437 (if (not (calc-minibuffer-contains ".* \\'"))
2438 (insert " "))
2439 (insert "+/- ")))
2440 ((and (eq last-command-event ?M)
2441 (not (calc-minibuffer-contains
2442 "[-+]?\\(2[3-9]\\|[3-9][0-9]\\)#.*")))
2443 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2444 (calc-minibuffer-contains ".*mod *[^ ]+")
2445 (calc-minibuffer-contains ".*[-+e:]\\'"))
2446 (beep)
2447 (if (calc-minibuffer-contains ".*mod \\'")
2448 (if calc-previous-modulo
2449 (insert (math-format-flat-expr calc-previous-modulo 0))
2450 (beep))
2451 (if (not (calc-minibuffer-contains ".* \\'"))
2452 (insert " "))
2453 (insert "mod "))))
2455 (insert (char-to-string last-command-event))
2456 (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]*\\)?\\)?\\'")
2457 (let ((radix (string-to-number
2458 (buffer-substring
2459 (match-beginning 2) (match-end 2)))))
2460 (and (>= radix 2)
2461 (<= radix 36)
2462 (or (memq last-command-event '(?# ?: ?. ?e ?+ ?-))
2463 (let ((dig (math-read-radix-digit
2464 (upcase last-command-event))))
2465 (and dig
2466 (< dig radix)))))))
2467 (calc-minibuffer-contains
2468 "[-+]?\\(.*\\+/- *\\|.*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]?\\'"))
2469 (if (and (memq last-command-event '(?@ ?o ?h ?\' ?m))
2470 (string-match " " calc-hms-format))
2471 (insert " "))
2472 (if (and (eq this-command last-command)
2473 (eq last-command-event ?.))
2474 (progn
2475 (require 'calc-ext)
2476 (calc-digit-dots))
2477 (delete-char -1)
2478 (beep)
2479 (calc-temp-minibuffer-message " [Bad format]"))))))
2480 (setq calc-prev-prev-char calc-prev-char
2481 calc-prev-char last-command-event))
2484 (defun calcDigit-backspace ()
2485 (interactive)
2486 (goto-char (point-max))
2487 (cond ((calc-minibuffer-contains ".* \\+/- \\'")
2488 (backward-delete-char 5))
2489 ((calc-minibuffer-contains ".* mod \\'")
2490 (backward-delete-char 5))
2491 ((calc-minibuffer-contains ".* \\'")
2492 (backward-delete-char 2))
2493 ((eq last-command 'calcDigit-start)
2494 (erase-buffer))
2495 (t (backward-delete-char 1)))
2496 (if (= (calc-minibuffer-size) 0)
2497 (progn
2498 (setq last-command-event 13)
2499 (calcDigit-nondigit))))
2504 (defconst math-bignum-digit-length
2505 (truncate (/ (log (/ most-positive-fixnum 2) 10) 2))
2506 "The length of a \"digit\" in Calc bignums.
2507 If a big integer is of the form (bigpos N0 N1 ...), this is the
2508 length of the allowable Emacs integers N0, N1,...
2509 The value of 2*10^(2*MATH-BIGNUM-DIGIT-LENGTH) must be less than the
2510 largest Emacs integer.")
2512 (defconst math-bignum-digit-size
2513 (expt 10 math-bignum-digit-length)
2514 "An upper bound for the size of the \"digit\"s in Calc bignums.")
2516 (defconst math-small-integer-size
2517 (expt math-bignum-digit-size 2)
2518 "An upper bound for the size of \"small integer\"s in Calc.")
2521 ;;;; Arithmetic routines.
2523 ;; An object as manipulated by one of these routines may take any of the
2524 ;; following forms:
2526 ;; integer An integer. For normalized numbers, this format
2527 ;; is used only for
2528 ;; negative math-small-integer-size + 1 to
2529 ;; math-small-integer-size - 1
2531 ;; (bigpos N0 N1 N2 ...) A big positive integer,
2532 ;; N0 + N1*math-bignum-digit-size
2533 ;; + N2*(math-bignum-digit-size)^2 ...
2534 ;; (bigneg N0 N1 N2 ...) A big negative integer,
2535 ;; - N0 - N1*math-bignum-digit-size ...
2536 ;; Each digit N is in the range
2537 ;; 0 ... math-bignum-digit-size -1.
2538 ;; Normalized, always at least three N present,
2539 ;; and the most significant N is nonzero.
2541 ;; (frac NUM DEN) A fraction. NUM and DEN are small or big integers.
2542 ;; Normalized, DEN > 1.
2544 ;; (float NUM EXP) A floating-point number, NUM * 10^EXP;
2545 ;; NUM is a small or big integer, EXP is a small int.
2546 ;; Normalized, NUM is not a multiple of 10, and
2547 ;; abs(NUM) < 10^calc-internal-prec.
2548 ;; Normalized zero is stored as (float 0 0).
2550 ;; (cplx REAL IMAG) A complex number; REAL and IMAG are any of above.
2551 ;; Normalized, IMAG is nonzero.
2553 ;; (polar R THETA) Polar complex number. Normalized, R > 0 and THETA
2554 ;; is neither zero nor 180 degrees (pi radians).
2556 ;; (vec A B C ...) Vector of objects A, B, C, ... A matrix is a
2557 ;; vector of vectors.
2559 ;; (hms H M S) Angle in hours-minutes-seconds form. All three
2560 ;; components have the same sign; H and M must be
2561 ;; numerically integers; M and S are expected to
2562 ;; lie in the range [0,60).
2564 ;; (date N) A date or date/time object. N is an integer to
2565 ;; store a date only, or a fraction or float to
2566 ;; store a date and time.
2568 ;; (sdev X SIGMA) Error form, X +/- SIGMA. When normalized,
2569 ;; SIGMA > 0. X is any complex number and SIGMA
2570 ;; is real numbers; or these may be symbolic
2571 ;; expressions where SIGMA is assumed real.
2573 ;; (intv MASK LO HI) Interval form. MASK is 0=(), 1=(], 2=[), or 3=[].
2574 ;; LO and HI are any real numbers, or symbolic
2575 ;; expressions which are assumed real, and LO < HI.
2576 ;; For [LO..HI], if LO = HI normalization produces LO,
2577 ;; and if LO > HI normalization produces [LO..LO).
2578 ;; For other intervals, if LO > HI normalization
2579 ;; sets HI equal to LO.
2581 ;; (mod N M) Number modulo M. When normalized, 0 <= N < M.
2582 ;; N and M are real numbers.
2584 ;; (var V S) Symbolic variable. V is a Lisp symbol which
2585 ;; represents the variable's visible name. S is
2586 ;; the symbol which actually stores the variable's
2587 ;; value: (var pi var-pi).
2589 ;; In general, combining rational numbers in a calculation always produces
2590 ;; a rational result, but if either argument is a float, result is a float.
2592 ;; In the following comments, [x y z] means result is x, args must be y, z,
2593 ;; respectively, where the code letters are:
2595 ;; O Normalized object (vector or number)
2596 ;; V Normalized vector
2597 ;; N Normalized number of any type
2598 ;; N Normalized complex number
2599 ;; R Normalized real number (float or rational)
2600 ;; F Normalized floating-point number
2601 ;; T Normalized rational number
2602 ;; I Normalized integer
2603 ;; B Normalized big integer
2604 ;; S Normalized small integer
2605 ;; D Digit (small integer, 0..999)
2606 ;; L Normalized bignum digit list (without "bigpos" or "bigneg" symbol)
2607 ;; or normalized vector element list (without "vec")
2608 ;; P Predicate (truth value)
2609 ;; X Any Lisp object
2610 ;; Z "nil"
2612 ;; Lower-case letters signify possibly un-normalized values.
2613 ;; "L.D" means a cons of an L and a D.
2614 ;; [N N; n n] means result will be normalized if argument is.
2615 ;; Also, [Public] marks routines intended to be called from outside.
2616 ;; [This notation has been neglected in many recent routines.]
2618 (defvar math-eval-rules-cache)
2619 (defvar math-eval-rules-cache-other)
2620 ;;; Reduce an object to canonical (normalized) form. [O o; Z Z] [Public]
2622 (defvar math-normalize-a)
2623 (defvar math-normalize-error nil
2624 "Non-nil if the last call the `math-normalize' returned an error.")
2626 (defun math-normalize (math-normalize-a)
2627 (setq math-normalize-error nil)
2628 (cond
2629 ((not (consp math-normalize-a))
2630 (if (integerp math-normalize-a)
2631 (if (or (>= math-normalize-a math-small-integer-size)
2632 (<= math-normalize-a (- math-small-integer-size)))
2633 (math-bignum math-normalize-a)
2634 math-normalize-a)
2635 math-normalize-a))
2636 ((eq (car math-normalize-a) 'bigpos)
2637 (if (eq (nth (1- (length math-normalize-a)) math-normalize-a) 0)
2638 (let* ((last (setq math-normalize-a
2639 (copy-sequence math-normalize-a))) (digs math-normalize-a))
2640 (while (setq digs (cdr digs))
2641 (or (eq (car digs) 0) (setq last digs)))
2642 (setcdr last nil)))
2643 (if (cdr (cdr (cdr math-normalize-a)))
2644 math-normalize-a
2645 (cond
2646 ((cdr (cdr math-normalize-a)) (+ (nth 1 math-normalize-a)
2647 (* (nth 2 math-normalize-a)
2648 math-bignum-digit-size)))
2649 ((cdr math-normalize-a) (nth 1 math-normalize-a))
2650 (t 0))))
2651 ((eq (car math-normalize-a) 'bigneg)
2652 (if (eq (nth (1- (length math-normalize-a)) math-normalize-a) 0)
2653 (let* ((last (setq math-normalize-a (copy-sequence math-normalize-a)))
2654 (digs math-normalize-a))
2655 (while (setq digs (cdr digs))
2656 (or (eq (car digs) 0) (setq last digs)))
2657 (setcdr last nil)))
2658 (if (cdr (cdr (cdr math-normalize-a)))
2659 math-normalize-a
2660 (cond
2661 ((cdr (cdr math-normalize-a)) (- (+ (nth 1 math-normalize-a)
2662 (* (nth 2 math-normalize-a)
2663 math-bignum-digit-size))))
2664 ((cdr math-normalize-a) (- (nth 1 math-normalize-a)))
2665 (t 0))))
2666 ((eq (car math-normalize-a) 'float)
2667 (math-make-float (math-normalize (nth 1 math-normalize-a))
2668 (nth 2 math-normalize-a)))
2669 ((or (memq (car math-normalize-a)
2670 '(frac cplx polar hms date mod sdev intv vec var quote
2671 special-const calcFunc-if calcFunc-lambda
2672 calcFunc-quote calcFunc-condition
2673 calcFunc-evalto))
2674 (integerp (car math-normalize-a))
2675 (and (consp (car math-normalize-a))
2676 (not (eq (car (car math-normalize-a)) 'lambda))))
2677 (require 'calc-ext)
2678 (math-normalize-fancy math-normalize-a))
2680 (or (and calc-simplify-mode
2681 (require 'calc-ext)
2682 (math-normalize-nonstandard))
2683 (let ((args (mapcar 'math-normalize (cdr math-normalize-a))))
2684 (or (condition-case err
2685 (let ((func
2686 (assq (car math-normalize-a) '( ( + . math-add )
2687 ( - . math-sub )
2688 ( * . math-mul )
2689 ( / . math-div )
2690 ( % . math-mod )
2691 ( ^ . math-pow )
2692 ( neg . math-neg )
2693 ( | . math-concat ) ))))
2694 (or (and var-EvalRules
2695 (progn
2696 (or (eq var-EvalRules math-eval-rules-cache-tag)
2697 (progn
2698 (require 'calc-ext)
2699 (math-recompile-eval-rules)))
2700 (and (or math-eval-rules-cache-other
2701 (assq (car math-normalize-a)
2702 math-eval-rules-cache))
2703 (math-apply-rewrites
2704 (cons (car math-normalize-a) args)
2705 (cdr math-eval-rules-cache)
2706 nil math-eval-rules-cache))))
2707 (if func
2708 (apply (cdr func) args)
2709 (and (or (consp (car math-normalize-a))
2710 (fboundp (car math-normalize-a))
2711 (and (not (featurep 'calc-ext))
2712 (require 'calc-ext)
2713 (fboundp (car math-normalize-a))))
2714 (apply (car math-normalize-a) args)))))
2715 (wrong-number-of-arguments
2716 (setq math-normalize-error t)
2717 (calc-record-why "*Wrong number of arguments"
2718 (cons (car math-normalize-a) args))
2719 nil)
2720 (wrong-type-argument
2721 (or calc-next-why
2722 (calc-record-why "Wrong type of argument"
2723 (cons (car math-normalize-a) args)))
2724 nil)
2725 (args-out-of-range
2726 (setq math-normalize-error t)
2727 (calc-record-why "*Argument out of range"
2728 (cons (car math-normalize-a) args))
2729 nil)
2730 (inexact-result
2731 (calc-record-why "No exact representation for result"
2732 (cons (car math-normalize-a) args))
2733 nil)
2734 (math-overflow
2735 (setq math-normalize-error t)
2736 (calc-record-why "*Floating-point overflow occurred"
2737 (cons (car math-normalize-a) args))
2738 nil)
2739 (math-underflow
2740 (setq math-normalize-error t)
2741 (calc-record-why "*Floating-point underflow occurred"
2742 (cons (car math-normalize-a) args))
2743 nil)
2744 (void-variable
2745 (setq math-normalize-error t)
2746 (if (eq (nth 1 err) 'var-EvalRules)
2747 (progn
2748 (setq var-EvalRules nil)
2749 (math-normalize (cons (car math-normalize-a) args)))
2750 (calc-record-why "*Variable is void" (nth 1 err)))))
2751 (if (consp (car math-normalize-a))
2752 (math-dimension-error)
2753 (cons (car math-normalize-a) args))))))))
2757 ;; True if A is a floating-point real or complex number. [P x] [Public]
2758 (defun math-floatp (a)
2759 (cond ((eq (car-safe a) 'float) t)
2760 ((memq (car-safe a) '(cplx polar mod sdev intv))
2761 (or (math-floatp (nth 1 a))
2762 (math-floatp (nth 2 a))
2763 (and (eq (car a) 'intv) (math-floatp (nth 3 a)))))
2764 ((eq (car-safe a) 'date)
2765 (math-floatp (nth 1 a)))))
2769 ;; Verify that A is a complete object and return A. [x x] [Public]
2770 (defun math-check-complete (a)
2771 (cond ((integerp a) a)
2772 ((eq (car-safe a) 'incomplete)
2773 (calc-incomplete-error a))
2774 ((consp a) a)
2775 (t (error "Invalid data object encountered"))))
2779 ;; Coerce integer A to be a bignum. [B S]
2780 (defun math-bignum (a)
2781 (cond
2782 ((>= a 0)
2783 (cons 'bigpos (math-bignum-big a)))
2784 ((= a most-negative-fixnum)
2785 ;; Note: cannot get the negation directly because
2786 ;; (- most-negative-fixnum) is most-negative-fixnum.
2788 ;; most-negative-fixnum := -most-positive-fixnum - 1
2789 (math-sub (cons 'bigneg (math-bignum-big most-positive-fixnum))
2792 (cons 'bigneg (math-bignum-big (- a))))))
2794 (defun math-bignum-big (a) ; [L s]
2795 (if (= a 0)
2797 (cons (% a math-bignum-digit-size)
2798 (math-bignum-big (/ a math-bignum-digit-size)))))
2801 ;; Build a normalized floating-point number. [F I S]
2802 (defun math-make-float (mant exp)
2803 (if (eq mant 0)
2804 '(float 0 0)
2805 (let* ((ldiff (- calc-internal-prec (math-numdigs mant))))
2806 (if (< ldiff 0)
2807 (setq mant (math-scale-rounding mant ldiff)
2808 exp (- exp ldiff))))
2809 (if (consp mant)
2810 (let ((digs (cdr mant)))
2811 (if (= (% (car digs) 10) 0)
2812 (progn
2813 (while (= (car digs) 0)
2814 (setq digs (cdr digs)
2815 exp (+ exp math-bignum-digit-length)))
2816 (while (= (% (car digs) 10) 0)
2817 (setq digs (math-div10-bignum digs)
2818 exp (1+ exp)))
2819 (setq mant (math-normalize (cons (car mant) digs))))))
2820 (while (= (% mant 10) 0)
2821 (setq mant (/ mant 10)
2822 exp (1+ exp))))
2823 (if (and (<= exp -4000000)
2824 (<= (+ exp (math-numdigs mant) -1) -4000000))
2825 (signal 'math-underflow nil)
2826 (if (and (>= exp 3000000)
2827 (>= (+ exp (math-numdigs mant) -1) 4000000))
2828 (signal 'math-overflow nil)
2829 (list 'float mant exp)))))
2831 (defun math-div10-bignum (a) ; [l l]
2832 (if (cdr a)
2833 (cons (+ (/ (car a) 10) (* (% (nth 1 a) 10)
2834 (expt 10 (1- math-bignum-digit-length))))
2835 (math-div10-bignum (cdr a)))
2836 (list (/ (car a) 10))))
2838 ;;; Coerce A to be a float. [F N; V V] [Public]
2839 (defun math-float (a)
2840 (cond ((Math-integerp a) (math-make-float a 0))
2841 ((eq (car a) 'frac) (math-div (math-float (nth 1 a)) (nth 2 a)))
2842 ((eq (car a) 'float) a)
2843 ((memq (car a) '(cplx polar vec hms date sdev mod))
2844 (cons (car a) (mapcar 'math-float (cdr a))))
2845 (t (math-float-fancy a))))
2848 (defun math-neg (a)
2849 (cond ((not (consp a)) (- a))
2850 ((eq (car a) 'bigpos) (cons 'bigneg (cdr a)))
2851 ((eq (car a) 'bigneg) (cons 'bigpos (cdr a)))
2852 ((memq (car a) '(frac float))
2853 (list (car a) (Math-integer-neg (nth 1 a)) (nth 2 a)))
2854 ((memq (car a) '(cplx vec hms date calcFunc-idn))
2855 (cons (car a) (mapcar 'math-neg (cdr a))))
2856 (t (math-neg-fancy a))))
2859 ;;; Compute the number of decimal digits in integer A. [S I]
2860 (defun math-numdigs (a)
2861 (if (consp a)
2862 (if (cdr a)
2863 (let* ((len (1- (length a)))
2864 (top (nth len a)))
2865 (+ (* (1- len) math-bignum-digit-length) (math-numdigs top)))
2867 (cond ((>= a 100) (+ (math-numdigs (/ a 1000)) 3))
2868 ((>= a 10) 2)
2869 ((>= a 1) 1)
2870 ((= a 0) 0)
2871 ((> a -10) 1)
2872 ((> a -100) 2)
2873 (t (math-numdigs (- a))))))
2875 ;;; Multiply (with truncation toward 0) the integer A by 10^N. [I i S]
2876 (defun math-scale-int (a n)
2877 (cond ((= n 0) a)
2878 ((> n 0) (math-scale-left a n))
2879 (t (math-normalize (math-scale-right a (- n))))))
2881 (defun math-scale-left (a n) ; [I I S]
2882 (if (= n 0)
2884 (if (consp a)
2885 (cons (car a) (math-scale-left-bignum (cdr a) n))
2886 (if (>= n math-bignum-digit-length)
2887 (if (or (>= a math-bignum-digit-size)
2888 (<= a (- math-bignum-digit-size)))
2889 (math-scale-left (math-bignum a) n)
2890 (math-scale-left (* a math-bignum-digit-size)
2891 (- n math-bignum-digit-length)))
2892 (let ((sz (expt 10 (- (* 2 math-bignum-digit-length) n))))
2893 (if (or (>= a sz) (<= a (- sz)))
2894 (math-scale-left (math-bignum a) n)
2895 (* a (expt 10 n))))))))
2897 (defun math-scale-left-bignum (a n)
2898 (if (>= n math-bignum-digit-length)
2899 (while (>= (setq a (cons 0 a)
2900 n (- n math-bignum-digit-length))
2901 math-bignum-digit-length)))
2902 (if (> n 0)
2903 (math-mul-bignum-digit a (expt 10 n) 0)
2906 (defun math-scale-right (a n) ; [i i S]
2907 (if (= n 0)
2909 (if (consp a)
2910 (cons (car a) (math-scale-right-bignum (cdr a) n))
2911 (if (<= a 0)
2912 (if (= a 0)
2914 (- (math-scale-right (- a) n)))
2915 (if (>= n math-bignum-digit-length)
2916 (while (and (> (setq a (/ a math-bignum-digit-size)) 0)
2917 (>= (setq n (- n math-bignum-digit-length))
2918 math-bignum-digit-length))))
2919 (if (> n 0)
2920 (/ a (expt 10 n))
2921 a)))))
2923 (defun math-scale-right-bignum (a n) ; [L L S; l l S]
2924 (if (>= n math-bignum-digit-length)
2925 (setq a (nthcdr (/ n math-bignum-digit-length) a)
2926 n (% n math-bignum-digit-length)))
2927 (if (> n 0)
2928 (cdr (math-mul-bignum-digit a (expt 10 (- math-bignum-digit-length n)) 0))
2931 ;;; Multiply (with rounding) the integer A by 10^N. [I i S]
2932 (defun math-scale-rounding (a n)
2933 (cond ((>= n 0)
2934 (math-scale-left a n))
2935 ((consp a)
2936 (math-normalize
2937 (cons (car a)
2938 (let ((val (if (< n (- math-bignum-digit-length))
2939 (math-scale-right-bignum
2940 (cdr a)
2941 (- (- math-bignum-digit-length) n))
2942 (if (< n 0)
2943 (math-mul-bignum-digit
2944 (cdr a)
2945 (expt 10 (+ math-bignum-digit-length n)) 0)
2946 (cdr a))))) ; n = -math-bignum-digit-length
2947 (if (and val (>= (car val) (/ math-bignum-digit-size 2)))
2948 (if (cdr val)
2949 (if (eq (car (cdr val)) (1- math-bignum-digit-size))
2950 (math-add-bignum (cdr val) '(1))
2951 (cons (1+ (car (cdr val))) (cdr (cdr val))))
2952 '(1))
2953 (cdr val))))))
2955 (if (< a 0)
2956 (- (math-scale-rounding (- a) n))
2957 (if (= n -1)
2958 (/ (+ a 5) 10)
2959 (/ (+ (math-scale-right a (- -1 n)) 5) 10))))))
2962 ;;; Compute the sum of A and B. [O O O] [Public]
2963 (defun math-add (a b)
2965 (and (not (or (consp a) (consp b)))
2966 (progn
2967 (setq a (+ a b))
2968 (if (or (<= a (- math-small-integer-size)) (>= a math-small-integer-size))
2969 (math-bignum a)
2970 a)))
2971 (and (Math-zerop a) (not (eq (car-safe a) 'mod))
2972 (if (and (math-floatp a) (Math-ratp b)) (math-float b) b))
2973 (and (Math-zerop b) (not (eq (car-safe b) 'mod))
2974 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a))
2975 (and (Math-objvecp a) (Math-objvecp b)
2977 (and (Math-integerp a) (Math-integerp b)
2978 (progn
2979 (or (consp a) (setq a (math-bignum a)))
2980 (or (consp b) (setq b (math-bignum b)))
2981 (if (eq (car a) 'bigneg)
2982 (if (eq (car b) 'bigneg)
2983 (cons 'bigneg (math-add-bignum (cdr a) (cdr b)))
2984 (math-normalize
2985 (let ((diff (math-sub-bignum (cdr b) (cdr a))))
2986 (if (eq diff 'neg)
2987 (cons 'bigneg (math-sub-bignum (cdr a) (cdr b)))
2988 (cons 'bigpos diff)))))
2989 (if (eq (car b) 'bigneg)
2990 (math-normalize
2991 (let ((diff (math-sub-bignum (cdr a) (cdr b))))
2992 (if (eq diff 'neg)
2993 (cons 'bigneg (math-sub-bignum (cdr b) (cdr a)))
2994 (cons 'bigpos diff))))
2995 (cons 'bigpos (math-add-bignum (cdr a) (cdr b)))))))
2996 (and (Math-ratp a) (Math-ratp b)
2997 (require 'calc-ext)
2998 (calc-add-fractions a b))
2999 (and (Math-realp a) (Math-realp b)
3000 (progn
3001 (or (and (consp a) (eq (car a) 'float))
3002 (setq a (math-float a)))
3003 (or (and (consp b) (eq (car b) 'float))
3004 (setq b (math-float b)))
3005 (math-add-float a b)))
3006 (and (require 'calc-ext)
3007 (math-add-objects-fancy a b))))
3008 (and (require 'calc-ext)
3009 (math-add-symb-fancy a b))))
3011 (defun math-add-bignum (a b) ; [L L L; l l l]
3012 (if a
3013 (if b
3014 (let* ((a (copy-sequence a)) (aa a) (carry nil) sum)
3015 (while (and aa b)
3016 (if carry
3017 (if (< (setq sum (+ (car aa) (car b)))
3018 (1- math-bignum-digit-size))
3019 (progn
3020 (setcar aa (1+ sum))
3021 (setq carry nil))
3022 (setcar aa (- sum (1- math-bignum-digit-size))))
3023 (if (< (setq sum (+ (car aa) (car b))) math-bignum-digit-size)
3024 (setcar aa sum)
3025 (setcar aa (- sum math-bignum-digit-size))
3026 (setq carry t)))
3027 (setq aa (cdr aa)
3028 b (cdr b)))
3029 (if carry
3030 (if b
3031 (nconc a (math-add-bignum b '(1)))
3032 (while (eq (car aa) (1- math-bignum-digit-size))
3033 (setcar aa 0)
3034 (setq aa (cdr aa)))
3035 (if aa
3036 (progn
3037 (setcar aa (1+ (car aa)))
3039 (nconc a '(1))))
3040 (if b
3041 (nconc a b)
3042 a)))
3046 (defun math-sub-bignum (a b) ; [l l l]
3047 (if b
3048 (if a
3049 (let* ((a (copy-sequence a)) (aa a) (borrow nil) diff)
3050 (while (and aa b)
3051 (if borrow
3052 (if (>= (setq diff (- (car aa) (car b))) 1)
3053 (progn
3054 (setcar aa (1- diff))
3055 (setq borrow nil))
3056 (setcar aa (+ diff (1- math-bignum-digit-size))))
3057 (if (>= (setq diff (- (car aa) (car b))) 0)
3058 (setcar aa diff)
3059 (setcar aa (+ diff math-bignum-digit-size))
3060 (setq borrow t)))
3061 (setq aa (cdr aa)
3062 b (cdr b)))
3063 (if borrow
3064 (progn
3065 (while (eq (car aa) 0)
3066 (setcar aa (1- math-bignum-digit-size))
3067 (setq aa (cdr aa)))
3068 (if aa
3069 (progn
3070 (setcar aa (1- (car aa)))
3072 'neg))
3073 (while (eq (car b) 0)
3074 (setq b (cdr b)))
3075 (if b
3076 'neg
3077 a)))
3078 (while (eq (car b) 0)
3079 (setq b (cdr b)))
3080 (and b
3081 'neg))
3084 (defun math-add-float (a b) ; [F F F]
3085 (let ((ediff (- (nth 2 a) (nth 2 b))))
3086 (if (>= ediff 0)
3087 (if (>= ediff (+ calc-internal-prec calc-internal-prec))
3089 (math-make-float (math-add (nth 1 b)
3090 (if (eq ediff 0)
3091 (nth 1 a)
3092 (math-scale-left (nth 1 a) ediff)))
3093 (nth 2 b)))
3094 (if (>= (setq ediff (- ediff))
3095 (+ calc-internal-prec calc-internal-prec))
3097 (math-make-float (math-add (nth 1 a)
3098 (math-scale-left (nth 1 b) ediff))
3099 (nth 2 a))))))
3101 ;;; Compute the difference of A and B. [O O O] [Public]
3102 (defun math-sub (a b)
3103 (if (or (consp a) (consp b))
3104 (math-add a (math-neg b))
3105 (setq a (- a b))
3106 (if (or (<= a (- math-small-integer-size)) (>= a math-small-integer-size))
3107 (math-bignum a)
3108 a)))
3110 (defun math-sub-float (a b) ; [F F F]
3111 (let ((ediff (- (nth 2 a) (nth 2 b))))
3112 (if (>= ediff 0)
3113 (if (>= ediff (+ calc-internal-prec calc-internal-prec))
3115 (math-make-float (math-add (Math-integer-neg (nth 1 b))
3116 (if (eq ediff 0)
3117 (nth 1 a)
3118 (math-scale-left (nth 1 a) ediff)))
3119 (nth 2 b)))
3120 (if (>= (setq ediff (- ediff))
3121 (+ calc-internal-prec calc-internal-prec))
3123 (math-make-float (math-add (nth 1 a)
3124 (Math-integer-neg
3125 (math-scale-left (nth 1 b) ediff)))
3126 (nth 2 a))))))
3129 ;;; Compute the product of A and B. [O O O] [Public]
3130 (defun math-mul (a b)
3132 (and (not (consp a)) (not (consp b))
3133 (< a math-bignum-digit-size) (> a (- math-bignum-digit-size))
3134 (< b math-bignum-digit-size) (> b (- math-bignum-digit-size))
3135 (* a b))
3136 (and (Math-zerop a) (not (eq (car-safe b) 'mod))
3137 (if (Math-scalarp b)
3138 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
3139 (require 'calc-ext)
3140 (math-mul-zero a b)))
3141 (and (Math-zerop b) (not (eq (car-safe a) 'mod))
3142 (if (Math-scalarp a)
3143 (if (and (math-floatp a) (Math-ratp b)) (math-float b) b)
3144 (require 'calc-ext)
3145 (math-mul-zero b a)))
3146 (and (Math-objvecp a) (Math-objvecp b)
3148 (and (Math-integerp a) (Math-integerp b)
3149 (progn
3150 (or (consp a) (setq a (math-bignum a)))
3151 (or (consp b) (setq b (math-bignum b)))
3152 (math-normalize
3153 (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
3154 (if (cdr (cdr a))
3155 (if (cdr (cdr b))
3156 (math-mul-bignum (cdr a) (cdr b))
3157 (math-mul-bignum-digit (cdr a) (nth 1 b) 0))
3158 (math-mul-bignum-digit (cdr b) (nth 1 a) 0))))))
3159 (and (Math-ratp a) (Math-ratp b)
3160 (require 'calc-ext)
3161 (calc-mul-fractions a b))
3162 (and (Math-realp a) (Math-realp b)
3163 (progn
3164 (or (and (consp a) (eq (car a) 'float))
3165 (setq a (math-float a)))
3166 (or (and (consp b) (eq (car b) 'float))
3167 (setq b (math-float b)))
3168 (math-make-float (math-mul (nth 1 a) (nth 1 b))
3169 (+ (nth 2 a) (nth 2 b)))))
3170 (and (require 'calc-ext)
3171 (math-mul-objects-fancy a b))))
3172 (and (require 'calc-ext)
3173 (math-mul-symb-fancy a b))))
3175 (defun math-infinitep (a &optional undir)
3176 (while (and (consp a) (memq (car a) '(* / neg)))
3177 (if (or (not (eq (car a) '*)) (math-infinitep (nth 1 a)))
3178 (setq a (nth 1 a))
3179 (setq a (nth 2 a))))
3180 (and (consp a)
3181 (eq (car a) 'var)
3182 (memq (nth 2 a) '(var-inf var-uinf var-nan))
3183 (if (and undir (eq (nth 2 a) 'var-inf))
3184 '(var uinf var-uinf)
3185 a)))
3187 ;;; Multiply digit lists A and B. [L L L; l l l]
3188 (defun math-mul-bignum (a b)
3189 (and a b
3190 (let* ((sum (if (<= (car b) 1)
3191 (if (= (car b) 0)
3192 (list 0)
3193 (copy-sequence a))
3194 (math-mul-bignum-digit a (car b) 0)))
3195 (sump sum) c d aa ss prod)
3196 (while (setq b (cdr b))
3197 (setq ss (setq sump (or (cdr sump) (setcdr sump (list 0))))
3198 d (car b)
3200 aa a)
3201 (while (progn
3202 (setcar ss (% (setq prod (+ (+ (car ss) (* (car aa) d))
3204 math-bignum-digit-size))
3205 (setq aa (cdr aa)))
3206 (setq c (/ prod math-bignum-digit-size)
3207 ss (or (cdr ss) (setcdr ss (list 0)))))
3208 (if (>= prod math-bignum-digit-size)
3209 (if (cdr ss)
3210 (setcar (cdr ss) (+ (/ prod math-bignum-digit-size) (car (cdr ss))))
3211 (setcdr ss (list (/ prod math-bignum-digit-size))))))
3212 sum)))
3214 ;;; Multiply digit list A by digit D. [L L D D; l l D D]
3215 (defun math-mul-bignum-digit (a d c)
3216 (if a
3217 (if (<= d 1)
3218 (and (= d 1) a)
3219 (let* ((a (copy-sequence a)) (aa a) prod)
3220 (while (progn
3221 (setcar aa
3222 (% (setq prod (+ (* (car aa) d) c))
3223 math-bignum-digit-size))
3224 (cdr aa))
3225 (setq aa (cdr aa)
3226 c (/ prod math-bignum-digit-size)))
3227 (if (>= prod math-bignum-digit-size)
3228 (setcdr aa (list (/ prod math-bignum-digit-size))))
3230 (and (> c 0)
3231 (list c))))
3234 ;;; Compute the integer (quotient . remainder) of A and B, which may be
3235 ;;; small or big integers. Type and consistency of truncation is undefined
3236 ;;; if A or B is negative. B must be nonzero. [I.I I I] [Public]
3237 (defun math-idivmod (a b)
3238 (if (eq b 0)
3239 (math-reject-arg a "*Division by zero"))
3240 (if (or (consp a) (consp b))
3241 (if (and (natnump b) (< b math-bignum-digit-size))
3242 (let ((res (math-div-bignum-digit (cdr a) b)))
3243 (cons
3244 (math-normalize (cons (car a) (car res)))
3245 (cdr res)))
3246 (or (consp a) (setq a (math-bignum a)))
3247 (or (consp b) (setq b (math-bignum b)))
3248 (let ((res (math-div-bignum (cdr a) (cdr b))))
3249 (cons
3250 (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
3251 (car res)))
3252 (math-normalize (cons (car a) (cdr res))))))
3253 (cons (/ a b) (% a b))))
3255 (defun math-quotient (a b) ; [I I I] [Public]
3256 (if (and (not (consp a)) (not (consp b)))
3257 (if (= b 0)
3258 (math-reject-arg a "*Division by zero")
3259 (/ a b))
3260 (if (and (natnump b) (< b math-bignum-digit-size))
3261 (if (= b 0)
3262 (math-reject-arg a "*Division by zero")
3263 (math-normalize (cons (car a)
3264 (car (math-div-bignum-digit (cdr a) b)))))
3265 (or (consp a) (setq a (math-bignum a)))
3266 (or (consp b) (setq b (math-bignum b)))
3267 (let* ((alen (1- (length a)))
3268 (blen (1- (length b)))
3269 (d (/ math-bignum-digit-size (1+ (nth (1- blen) (cdr b)))))
3270 (res (math-div-bignum-big (math-mul-bignum-digit (cdr a) d 0)
3271 (math-mul-bignum-digit (cdr b) d 0)
3272 alen blen)))
3273 (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
3274 (car res)))))))
3277 ;;; Divide a bignum digit list by another. [l.l l L]
3278 ;;; The following division algorithm is borrowed from Knuth vol. II, sec. 4.3.1
3279 (defun math-div-bignum (a b)
3280 (if (cdr b)
3281 (let* ((alen (length a))
3282 (blen (length b))
3283 (d (/ math-bignum-digit-size (1+ (nth (1- blen) b))))
3284 (res (math-div-bignum-big (math-mul-bignum-digit a d 0)
3285 (math-mul-bignum-digit b d 0)
3286 alen blen)))
3287 (if (= d 1)
3289 (cons (car res)
3290 (car (math-div-bignum-digit (cdr res) d)))))
3291 (let ((res (math-div-bignum-digit a (car b))))
3292 (cons (car res) (list (cdr res))))))
3294 ;;; Divide a bignum digit list by a digit. [l.D l D]
3295 (defun math-div-bignum-digit (a b)
3296 (if a
3297 (let* ((res (math-div-bignum-digit (cdr a) b))
3298 (num (+ (* (cdr res) math-bignum-digit-size) (car a))))
3299 (cons
3300 (cons (/ num b) (car res))
3301 (% num b)))
3302 '(nil . 0)))
3304 (defun math-div-bignum-big (a b alen blen) ; [l.l l L]
3305 (if (< alen blen)
3306 (cons nil a)
3307 (let* ((res (math-div-bignum-big (cdr a) b (1- alen) blen))
3308 (num (cons (car a) (cdr res)))
3309 (res2 (math-div-bignum-part num b blen)))
3310 (cons
3311 (cons (car res2) (car res))
3312 (cdr res2)))))
3314 (defun math-div-bignum-part (a b blen) ; a < b*math-bignum-digit-size [D.l l L]
3315 (let* ((num (+ (* (or (nth blen a) 0) math-bignum-digit-size)
3316 (or (nth (1- blen) a) 0)))
3317 (den (nth (1- blen) b))
3318 (guess (min (/ num den) (1- math-bignum-digit-size))))
3319 (math-div-bignum-try a b (math-mul-bignum-digit b guess 0) guess)))
3321 (defun math-div-bignum-try (a b c guess) ; [D.l l l D]
3322 (let ((rem (math-sub-bignum a c)))
3323 (if (eq rem 'neg)
3324 (math-div-bignum-try a b (math-sub-bignum c b) (1- guess))
3325 (cons guess rem))))
3328 ;;; Compute the quotient of A and B. [O O N] [Public]
3329 (defun math-div (a b)
3331 (and (Math-zerop b)
3332 (require 'calc-ext)
3333 (math-div-by-zero a b))
3334 (and (Math-zerop a) (not (eq (car-safe b) 'mod))
3335 (if (Math-scalarp b)
3336 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
3337 (require 'calc-ext)
3338 (math-div-zero a b)))
3339 (and (Math-objvecp a) (Math-objvecp b)
3341 (and (Math-integerp a) (Math-integerp b)
3342 (let ((q (math-idivmod a b)))
3343 (if (eq (cdr q) 0)
3344 (car q)
3345 (if calc-prefer-frac
3346 (progn
3347 (require 'calc-ext)
3348 (math-make-frac a b))
3349 (math-div-float (math-make-float a 0)
3350 (math-make-float b 0))))))
3351 (and (Math-ratp a) (Math-ratp b)
3352 (require 'calc-ext)
3353 (calc-div-fractions a b))
3354 (and (Math-realp a) (Math-realp b)
3355 (progn
3356 (or (and (consp a) (eq (car a) 'float))
3357 (setq a (math-float a)))
3358 (or (and (consp b) (eq (car b) 'float))
3359 (setq b (math-float b)))
3360 (math-div-float a b)))
3361 (and (require 'calc-ext)
3362 (math-div-objects-fancy a b))))
3363 (and (require 'calc-ext)
3364 (math-div-symb-fancy a b))))
3366 (defun math-div-float (a b) ; [F F F]
3367 (let ((ldiff (max (- (1+ calc-internal-prec)
3368 (- (math-numdigs (nth 1 a)) (math-numdigs (nth 1 b))))
3369 0)))
3370 (math-make-float (math-quotient (math-scale-int (nth 1 a) ldiff) (nth 1 b))
3371 (- (- (nth 2 a) (nth 2 b)) ldiff))))
3376 (defvar calc-selection-cache-entry)
3377 ;;; Format the number A as a string. [X N; X Z] [Public]
3378 (defun math-format-stack-value (entry)
3379 (setq calc-selection-cache-entry calc-selection-cache-default-entry)
3380 (let* ((a (car entry))
3381 (math-comp-selected (nth 2 entry))
3382 (c (cond ((null a) "<nil>")
3383 ((eq calc-display-raw t) (format "%s" a))
3384 ((stringp a) a)
3385 ((eq a 'top-of-stack) (propertize "." 'font-lock-face 'bold))
3386 (calc-prepared-composition
3387 calc-prepared-composition)
3388 ((and (Math-scalarp a)
3389 (memq calc-language '(nil flat unform))
3390 (null math-comp-selected))
3391 (math-format-number a))
3392 (t (require 'calc-ext)
3393 (math-compose-expr a 0))))
3394 (off (math-stack-value-offset c))
3395 s w)
3396 (and math-comp-selected (setq calc-any-selections t))
3397 (setq w (cdr off)
3398 off (car off))
3399 (when (> off 0)
3400 (setq c (math-comp-concat (make-string off ?\s) c)))
3401 (or (equal calc-left-label "")
3402 (setq c (math-comp-concat (if (eq a 'top-of-stack)
3403 (make-string (length calc-left-label) ?\s)
3404 calc-left-label)
3405 c)))
3406 (when calc-line-numbering
3407 (setq c (math-comp-concat (if (eq calc-language 'big)
3408 (if math-comp-selected
3409 '(tag t "1: ")
3410 "1: ")
3411 " ")
3412 c)))
3413 (unless (or (equal calc-right-label "")
3414 (eq a 'top-of-stack))
3415 (require 'calc-ext)
3416 (setq c (list 'horiz c
3417 (make-string (max (- w (math-comp-width c)
3418 (length calc-right-label)) 0) ?\s)
3419 '(break -1)
3420 calc-right-label)))
3421 (setq s (if (stringp c)
3422 (if calc-display-raw
3423 (prin1-to-string c)
3425 (math-composition-to-string c w)))
3426 (when calc-language-output-filter
3427 (setq s (funcall calc-language-output-filter s)))
3428 (if (eq calc-language 'big)
3429 (setq s (concat s "\n"))
3430 (when calc-line-numbering
3431 (setq s (concat "1:" (substring s 2)))))
3432 (setcar (cdr entry) (calc-count-lines s))
3435 ;; The variables math-svo-c, math-svo-wid and math-svo-off are local
3436 ;; to math-stack-value-offset, but are used by math-stack-value-offset-fancy
3437 ;; in calccomp.el.
3439 (defvar math-svo-c)
3440 (defvar math-svo-wid)
3441 (defvar math-svo-off)
3443 (defun math-stack-value-offset (math-svo-c)
3444 (let* ((num (if calc-line-numbering 4 0))
3445 (math-svo-wid (calc-window-width))
3446 math-svo-off)
3447 (if calc-display-just
3448 (progn
3449 (require 'calc-ext)
3450 (math-stack-value-offset-fancy))
3451 (setq math-svo-off (or calc-display-origin 0))
3452 (when (integerp calc-line-breaking)
3453 (setq math-svo-wid calc-line-breaking)))
3454 (cons (max (- math-svo-off (length calc-left-label)) 0)
3455 (+ math-svo-wid num))))
3457 (defun calc-count-lines (s)
3458 (let ((pos 0)
3459 (num 1))
3460 (while (setq pos (string-match "\n" s pos))
3461 (setq pos (1+ pos)
3462 num (1+ num)))
3463 num))
3465 (defun math-format-value (a &optional w)
3466 (if (and (Math-scalarp a)
3467 (memq calc-language '(nil flat unform)))
3468 (math-format-number a)
3469 (require 'calc-ext)
3470 (let ((calc-line-breaking nil))
3471 (math-composition-to-string (math-compose-expr a 0) w))))
3473 (defun calc-window-width ()
3474 (if calc-embedded-info
3475 (let ((win (get-buffer-window (aref calc-embedded-info 0))))
3476 (1- (if win (window-width win) (frame-width))))
3477 (- (window-width (get-buffer-window (current-buffer)))
3478 (if calc-line-numbering 5 1))))
3480 (defun math-comp-concat (c1 c2)
3481 (if (and (stringp c1) (stringp c2))
3482 (concat c1 c2)
3483 (list 'horiz c1 c2)))
3487 ;;; Format an expression as a one-line string suitable for re-reading.
3489 (defun math-format-flat-expr (a prec)
3490 (cond
3491 ((or (not (or (consp a) (integerp a)))
3492 (eq calc-display-raw t))
3493 (let ((print-escape-newlines t))
3494 (concat "'" (prin1-to-string a))))
3495 ((Math-scalarp a)
3496 (let ((calc-group-digits nil)
3497 (calc-point-char ".")
3498 (calc-frac-format (if (> (length (car calc-frac-format)) 1)
3499 '("::" nil) '(":" nil)))
3500 (calc-complex-format nil)
3501 (calc-hms-format "%s@ %s' %s\"")
3502 (calc-language nil))
3503 (math-format-number a)))
3505 (require 'calc-ext)
3506 (math-format-flat-expr-fancy a prec))))
3510 ;;; Format a number as a string.
3511 (defvar math-half-2-word-size)
3512 (defun math-format-number (a &optional prec) ; [X N] [Public]
3513 (cond
3514 ((eq calc-display-raw t) (format "%s" a))
3515 ((and calc-twos-complement-mode
3516 math-radix-explicit-format
3517 (Math-integerp a)
3518 (or (eq a 0)
3519 (and (Math-integer-posp a)
3520 (Math-lessp a math-half-2-word-size))
3521 (and (Math-integer-negp a)
3522 (require 'calc-ext)
3523 (let ((comparison
3524 (math-compare (Math-integer-neg a) math-half-2-word-size)))
3525 (or (= comparison 0)
3526 (= comparison -1))))))
3527 (require 'calc-bin)
3528 (math-format-twos-complement a))
3529 ((and (nth 1 calc-frac-format) (Math-integerp a))
3530 (require 'calc-ext)
3531 (math-format-number (math-adjust-fraction a)))
3532 ((integerp a)
3533 (if (not (or calc-group-digits calc-leading-zeros))
3534 (if (= calc-number-radix 10)
3535 (int-to-string a)
3536 (if (< a 0)
3537 (concat "-" (math-format-number (- a)))
3538 (require 'calc-ext)
3539 (if math-radix-explicit-format
3540 (if calc-radix-formatter
3541 (funcall calc-radix-formatter
3542 calc-number-radix
3543 (if (= calc-number-radix 2)
3544 (math-format-binary a)
3545 (math-format-radix a)))
3546 (format "%d#%s" calc-number-radix
3547 (if (= calc-number-radix 2)
3548 (math-format-binary a)
3549 (math-format-radix a))))
3550 (math-format-radix a))))
3551 (math-format-number (math-bignum a))))
3552 ((stringp a) a)
3553 ((not (consp a)) (prin1-to-string a))
3554 ((eq (car a) 'bigpos) (math-format-bignum (cdr a)))
3555 ((eq (car a) 'bigneg) (concat "-" (math-format-bignum (cdr a))))
3556 ((and (eq (car a) 'float) (= calc-number-radix 10))
3557 (if (Math-integer-negp (nth 1 a))
3558 (concat "-" (math-format-number (math-neg a)))
3559 (let ((mant (nth 1 a))
3560 (exp (nth 2 a))
3561 (fmt (car calc-float-format))
3562 (figs (nth 1 calc-float-format))
3563 (point calc-point-char)
3564 str)
3565 (if (and (eq fmt 'fix)
3566 (or (and (< figs 0) (setq figs (- figs)))
3567 (> (+ exp (math-numdigs mant)) (- figs))))
3568 (progn
3569 (setq mant (math-scale-rounding mant (+ exp figs))
3570 str (if (integerp mant)
3571 (int-to-string mant)
3572 (math-format-bignum-decimal (cdr mant))))
3573 (if (<= (length str) figs)
3574 (setq str (concat (make-string (1+ (- figs (length str))) ?0)
3575 str)))
3576 (if (> figs 0)
3577 (setq str (concat (substring str 0 (- figs)) point
3578 (substring str (- figs))))
3579 (setq str (concat str point)))
3580 (when calc-group-digits
3581 (require 'calc-ext)
3582 (setq str (math-group-float str))))
3583 (when (< figs 0)
3584 (setq figs (+ calc-internal-prec figs)))
3585 (when (> figs 0)
3586 (let ((adj (- figs (math-numdigs mant))))
3587 (when (< adj 0)
3588 (setq mant (math-scale-rounding mant adj)
3589 exp (- exp adj)))))
3590 (setq str (if (integerp mant)
3591 (int-to-string mant)
3592 (math-format-bignum-decimal (cdr mant))))
3593 (let* ((len (length str))
3594 (dpos (+ exp len)))
3595 (if (and (eq fmt 'float)
3596 (<= dpos (+ calc-internal-prec calc-display-sci-high))
3597 (>= dpos (+ calc-display-sci-low 2)))
3598 (progn
3599 (cond
3600 ((= dpos 0)
3601 (setq str (concat "0" point str)))
3602 ((and (<= exp 0) (> dpos 0))
3603 (setq str (concat (substring str 0 dpos) point
3604 (substring str dpos))))
3605 ((> exp 0)
3606 (setq str (concat str (make-string exp ?0) point)))
3607 (t ; (< dpos 0)
3608 (setq str (concat "0" point
3609 (make-string (- dpos) ?0) str))))
3610 (when calc-group-digits
3611 (require 'calc-ext)
3612 (setq str (math-group-float str))))
3613 (let* ((eadj (+ exp len))
3614 (scale (if (eq fmt 'eng)
3615 (1+ (math-mod (+ eadj 300002) 3))
3616 1)))
3617 (if (> scale (length str))
3618 (setq str (concat str (make-string (- scale (length str))
3619 ?0))))
3620 (if (< scale (length str))
3621 (setq str (concat (substring str 0 scale) point
3622 (substring str scale))))
3623 (when calc-group-digits
3624 (require 'calc-ext)
3625 (setq str (math-group-float str)))
3626 (setq str (format (if (memq calc-language '(math maple))
3627 (if (and prec (> prec 191))
3628 "(%s*10.^%d)" "%s*10.^%d")
3629 "%se%d")
3630 str (- eadj scale)))))))
3631 str)))
3633 (require 'calc-ext)
3634 (math-format-number-fancy a prec))))
3636 (defun math-format-bignum (a) ; [X L]
3637 (if (and (= calc-number-radix 10)
3638 (not calc-leading-zeros)
3639 (not calc-group-digits))
3640 (math-format-bignum-decimal a)
3641 (require 'calc-ext)
3642 (math-format-bignum-fancy a)))
3644 (defun math-format-bignum-decimal (a) ; [X L]
3645 (if a
3646 (let ((s ""))
3647 (while (cdr (cdr a))
3648 (setq s (concat
3649 (format
3650 (concat "%0"
3651 (number-to-string (* 2 math-bignum-digit-length))
3652 "d")
3653 (+ (* (nth 1 a) math-bignum-digit-size) (car a))) s)
3654 a (cdr (cdr a))))
3655 (concat (int-to-string
3656 (+ (* (or (nth 1 a) 0) math-bignum-digit-size) (car a))) s))
3657 "0"))
3661 ;;; Parse a simple number in string form. [N X] [Public]
3662 (defun math-read-number (s &optional decimal)
3663 "Convert the string S into a Calc number."
3664 (math-normalize
3665 (save-match-data
3666 (cond
3668 ;; Integers (most common case)
3669 ((string-match "\\` *\\([0-9]+\\) *\\'" s)
3670 (let ((digs (math-match-substring s 1)))
3671 (if (and (memq calc-language calc-lang-c-type-hex)
3672 (> (length digs) 1)
3673 (eq (aref digs 0) ?0)
3674 (null decimal))
3675 (math-read-number (concat "8#" digs))
3676 (if (<= (length digs) (* 2 math-bignum-digit-length))
3677 (string-to-number digs)
3678 (cons 'bigpos (math-read-bignum digs))))))
3680 ;; Clean up the string if necessary
3681 ((string-match "\\`\\(.*\\)[ \t\n]+\\([^\001]*\\)\\'" s)
3682 (math-read-number (concat (math-match-substring s 1)
3683 (math-match-substring s 2))))
3685 ;; Plus and minus signs
3686 ((string-match "^[-_+]\\(.*\\)$" s)
3687 (let ((val (math-read-number (math-match-substring s 1))))
3688 (and val (if (eq (aref s 0) ?+) val (math-neg val)))))
3690 ;; Forms that require extensions module
3691 ((string-match "[^-+0-9eE.]" s)
3692 (require 'calc-ext)
3693 (math-read-number-fancy s))
3695 ;; Decimal point
3696 ((string-match "^\\([0-9]*\\)\\.\\([0-9]*\\)$" s)
3697 (let ((int (math-match-substring s 1))
3698 (frac (math-match-substring s 2)))
3699 (let ((ilen (length int))
3700 (flen (length frac)))
3701 (let ((int (if (> ilen 0) (math-read-number int t) 0))
3702 (frac (if (> flen 0) (math-read-number frac t) 0)))
3703 (and int frac (or (> ilen 0) (> flen 0))
3704 (list 'float
3705 (math-add (math-scale-int int flen) frac)
3706 (- flen)))))))
3708 ;; "e" notation
3709 ((string-match "^\\(.*\\)[eE]\\([-+]?[0-9]+\\)$" s)
3710 (let ((mant (math-match-substring s 1))
3711 (exp (math-match-substring s 2)))
3712 (let ((mant (if (> (length mant) 0) (math-read-number mant t) 1))
3713 (exp (if (<= (length exp) (if (memq (aref exp 0) '(?+ ?-)) 8 7))
3714 (string-to-number exp))))
3715 (and mant exp (Math-realp mant) (> exp -4000000) (< exp 4000000)
3716 (let ((mant (math-float mant)))
3717 (list 'float (nth 1 mant) (+ (nth 2 mant) exp)))))))
3719 ;; Syntax error!
3720 (t nil)))))
3722 ;;; Parse a very simple number, keeping all digits.
3723 (defun math-read-number-simple (s)
3724 "Convert the string S into a Calc number.
3725 S is assumed to be a simple number (integer or float without an exponent)
3726 and all digits are kept, regardless of Calc's current precision."
3727 (save-match-data
3728 (cond
3729 ;; Integer
3730 ((string-match "^[0-9]+$" s)
3731 (if (string-match "^\\(0+\\)" s)
3732 (setq s (substring s (match-end 0))))
3733 (if (<= (length s) (* 2 math-bignum-digit-length))
3734 (string-to-number s)
3735 (cons 'bigpos (math-read-bignum s))))
3736 ;; Minus sign
3737 ((string-match "^-[0-9]+$" s)
3738 (if (<= (length s) (1+ (* 2 math-bignum-digit-length)))
3739 (string-to-number s)
3740 (cons 'bigneg (math-read-bignum (substring s 1)))))
3741 ;; Decimal point
3742 ((string-match "^\\(-?[0-9]*\\)\\.\\([0-9]*\\)$" s)
3743 (let ((int (math-match-substring s 1))
3744 (frac (math-match-substring s 2)))
3745 (list 'float (math-read-number-simple (concat int frac))
3746 (- (length frac)))))
3747 ;; Syntax error!
3748 (t nil))))
3750 (defun math-match-substring (s n)
3751 (if (match-beginning n)
3752 (substring s (match-beginning n) (match-end n))
3753 ""))
3755 (defun math-read-bignum (s) ; [l X]
3756 (if (> (length s) math-bignum-digit-length)
3757 (cons (string-to-number (substring s (- math-bignum-digit-length)))
3758 (math-read-bignum (substring s 0 (- math-bignum-digit-length))))
3759 (list (string-to-number s))))
3761 (defconst math-standard-opers
3762 '( ( "_" calcFunc-subscr 1200 1201 )
3763 ( "%" calcFunc-percent 1100 -1 )
3764 ( "u!" calcFunc-lnot -1 1000 )
3765 ( "mod" mod 400 400 185 )
3766 ( "+/-" sdev 300 300 185 )
3767 ( "!!" calcFunc-dfact 210 -1 )
3768 ( "!" calcFunc-fact 210 -1 )
3769 ( "^" ^ 201 200 )
3770 ( "**" ^ 201 200 )
3771 ( "u+" ident -1 197 )
3772 ( "u-" neg -1 197 )
3773 ( "/" / 190 191 )
3774 ( "%" % 190 191 )
3775 ( "\\" calcFunc-idiv 190 191 )
3776 ( "+" + 180 181 )
3777 ( "-" - 180 181 )
3778 ( "|" | 170 171 )
3779 ( "<" calcFunc-lt 160 161 )
3780 ( ">" calcFunc-gt 160 161 )
3781 ( "<=" calcFunc-leq 160 161 )
3782 ( ">=" calcFunc-geq 160 161 )
3783 ( "=" calcFunc-eq 160 161 )
3784 ( "==" calcFunc-eq 160 161 )
3785 ( "!=" calcFunc-neq 160 161 )
3786 ( "&&" calcFunc-land 110 111 )
3787 ( "||" calcFunc-lor 100 101 )
3788 ( "?" (math-read-if) 91 90 )
3789 ( "!!!" calcFunc-pnot -1 85 )
3790 ( "&&&" calcFunc-pand 80 81 )
3791 ( "|||" calcFunc-por 75 76 )
3792 ( ":=" calcFunc-assign 51 50 )
3793 ( "::" calcFunc-condition 45 46 )
3794 ( "=>" calcFunc-evalto 40 41 )
3795 ( "=>" calcFunc-evalto 40 -1 )))
3797 (defun math-standard-ops ()
3798 (if calc-multiplication-has-precedence
3799 (cons
3800 '( "*" * 196 195 )
3801 (cons
3802 '( "2x" * 196 195 )
3803 math-standard-opers))
3804 (cons
3805 '( "*" * 190 191 )
3806 (cons
3807 '( "2x" * 190 191 )
3808 math-standard-opers))))
3810 (defvar math-expr-opers (math-standard-ops))
3812 (defun math-standard-ops-p ()
3813 (let ((meo (caar math-expr-opers)))
3814 (and (stringp meo)
3815 (string= meo "*"))))
3817 (defun math-expr-ops ()
3818 (if (math-standard-ops-p)
3819 (math-standard-ops)
3820 math-expr-opers))
3822 ;;;###autoload
3823 (defun calc-grab-region (top bot arg)
3824 "Parse the region as a vector of numbers and push it on the Calculator stack."
3825 (interactive "r\nP")
3826 (require 'calc-ext)
3827 (calc-do-grab-region top bot arg))
3829 ;;;###autoload
3830 (defun calc-grab-rectangle (top bot arg)
3831 "Parse a rectangle as a matrix of numbers and push it on the Calculator stack."
3832 (interactive "r\nP")
3833 (require 'calc-ext)
3834 (calc-do-grab-rectangle top bot arg))
3836 (defun calc-grab-sum-down (top bot arg)
3837 "Parse a rectangle as a matrix of numbers and sum its columns."
3838 (interactive "r\nP")
3839 (require 'calc-ext)
3840 (calc-do-grab-rectangle top bot arg 'calcFunc-reduced))
3842 (defun calc-grab-sum-across (top bot arg)
3843 "Parse a rectangle as a matrix of numbers and sum its rows."
3844 (interactive "r\nP")
3845 (require 'calc-ext)
3846 (calc-do-grab-rectangle top bot arg 'calcFunc-reducea))
3849 ;;;###autoload
3850 (defun calc-embedded (arg &optional end obeg oend)
3851 "Start Calc Embedded mode on the formula surrounding point."
3852 (interactive "P")
3853 (require 'calc-ext)
3854 (calc-do-embedded arg end obeg oend))
3856 ;;;###autoload
3857 (defun calc-embedded-activate (&optional arg cbuf)
3858 "Scan the current editing buffer for all embedded := and => formulas.
3859 Also looks for the equivalent TeX words, \\gets and \\evalto."
3860 (interactive "P")
3861 (calc-do-embedded-activate arg cbuf))
3863 (defun calc-user-invocation ()
3864 (interactive)
3865 (unless calc-invocation-macro
3866 (error "Use `Z I' inside Calc to define a `C-x * Z' keyboard macro"))
3867 (execute-kbd-macro calc-invocation-macro nil))
3869 ;;; User-programmability.
3871 ;;;###autoload
3872 (defmacro defmath (func args &rest body) ; [Public]
3873 "Define Calc function.
3875 Like `defun' except that code in the body of the definition can
3876 make use of the full range of Calc data types and the usual
3877 arithmetic operations are converted to their Calc equivalents.
3879 The prefix `calcFunc-' is added to the specified name to get the
3880 actual Lisp function name.
3882 See Info node `(calc)Defining Functions'."
3883 (declare (doc-string 3))
3884 (require 'calc-ext)
3885 (math-do-defmath func args body))
3887 ;;; Functions needed for Lucid Emacs support.
3889 (defun calc-read-key (&optional optkey)
3890 (cond ((featurep 'xemacs)
3891 (let ((event (next-command-event)))
3892 (let ((key (event-to-character event t t)))
3893 (or key optkey (error "Expected a plain keystroke"))
3894 (cons key event))))
3896 (let ((key (read-event)))
3897 (cons key key)))))
3899 (defun calc-unread-command (&optional input)
3900 (if (featurep 'xemacs)
3901 (setq unread-command-event
3902 (if (integerp input) (character-to-event input)
3903 (or input last-command-event)))
3904 (push (or input last-command-event) unread-command-events)))
3906 (defun calc-clear-unread-commands ()
3907 (if (featurep 'xemacs)
3908 (setq unread-command-event nil)
3909 (setq unread-command-events nil)))
3911 (defcalcmodevar math-2-word-size
3912 (math-read-number-simple "4294967296")
3913 "Two to the power of `calc-word-size'.")
3915 (defcalcmodevar math-half-2-word-size
3916 (math-read-number-simple "2147483648")
3917 "One-half of two to the power of `calc-word-size'.")
3919 (when calc-always-load-extensions
3920 (require 'calc-ext)
3921 (calc-load-everything))
3924 (run-hooks 'calc-load-hook)
3926 (provide 'calc)
3928 ;;; calc.el ends here