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