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