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