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