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