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