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