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