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