]> code.delx.au - gnu-emacs/blob - lisp/calc/calc.el
6e191c9cdd73c224f625dd9ea89b7ddc9e7aa832
[gnu-emacs] / lisp / calc / calc.el
1 ;;; calc.el --- the GNU Emacs calculator
2
3 ;; Copyright (C) 1990, 1991, 1992, 1993, 2001, 2002, 2003, 2004, 2005,
4 ;; 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
5
6 ;; Author: David Gillespie <daveg@synaptics.com>
7 ;; Maintainer: Jay Belanger <jay.p.belanger@gmail.com>
8 ;; Keywords: convenience, extensions
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; Calc is split into many files. This file is the main entry point.
28 ;; This file includes autoload commands for various other basic Calc
29 ;; facilities. The more advanced features are based in calc-ext, which
30 ;; in turn contains autoloads for the rest of the Calc files. This
31 ;; odd set of interactions is designed to make Calc's loading time
32 ;; be as short as possible when only simple calculations are needed.
33
34 ;; Original author's address:
35 ;; Dave Gillespie, daveg@synaptics.com, uunet!synaptx!daveg.
36 ;; Synaptics, Inc., 2698 Orchard Parkway, San Jose, CA 95134.
37 ;;
38 ;; The old address daveg@csvax.cs.caltech.edu will continue to
39 ;; work for the foreseeable future.
40 ;;
41 ;; Bug reports and suggestions are always welcome! (Type M-x
42 ;; report-calc-bug to send them).
43
44 ;; All functions, macros, and Lisp variables defined here begin with one
45 ;; of the prefixes "math", "Math", or "calc", with the exceptions of
46 ;; "full-calc", "full-calc-keypad", "another-calc", "quick-calc",
47 ;; "report-calc-bug", and "defmath". User-accessible variables begin
48 ;; with "var-".
49
50 ;;; TODO:
51
52 ;; Fix rewrite mechanism to do less gratuitous rearrangement of terms.
53 ;; Implement a pattern-based "refers" predicate.
54 ;;
55 ;; Make it possible to Undo a selection command.
56 ;; Figure out how to allow selecting rows of matrices.
57 ;; If cursor was in selection before, move it after j n, j p, j L, etc.
58 ;; Consider reimplementing calc-delete-selection using rewrites.
59 ;;
60 ;; Implement line-breaking in non-flat compositions (is this desirable?).
61 ;; Implement matrix formatting with multi-line components.
62 ;;
63 ;; Have "Z R" define a user command based on a set of rewrite rules.
64 ;; Support "incf" and "decf" in defmath definitions.
65 ;; Have defmath generate calls to calc-binary-op or calc-unary-op.
66 ;; Make some way to define algebraic functions using keyboard macros.
67 ;;
68 ;; Allow calc-word-size=0 => Common Lisp-style signed bitwise arithmetic.
69 ;; Consider digamma function (and thus arb. prec. Euler's gamma constant).
70 ;; May as well make continued-fractions stuff available to the user.
71 ;;
72 ;; How about matrix eigenvalues, SVD, pseudo-inverse, etc.?
73 ;; Should cache matrix inverses as well as decompositions.
74 ;; If dividing by a non-square matrix, use least-squares automatically.
75 ;; Consider supporting matrix exponentials.
76 ;;
77 ;; Have ninteg detect and work around singularities at the endpoints.
78 ;; Use an adaptive subdivision algorithm for ninteg.
79 ;; Provide nsum and nprod to go along with ninteg.
80 ;;
81 ;; Handle TeX-mode parsing of \matrix{ ... } where ... contains braces.
82 ;; Support AmS-TeX's \{d,t,}frac, \{d,t,}binom notations.
83 ;; Format and parse sums and products in Eqn and Math modes.
84 ;;
85 ;; Get math-read-big-expr to read sums, products, etc.
86 ;; Change calc-grab-region to use math-read-big-expr.
87 ;; Have a way to define functions using := in Embedded Mode.
88 ;;
89 ;; Support polar plotting with GNUPLOT.
90 ;; Make a calc-graph-histogram function.
91 ;;
92 ;; Replace hokey formulas for complex functions with formulas designed
93 ;; to minimize roundoff while maintaining the proper branch cuts.
94 ;; Test accuracy of advanced math functions over whole complex plane.
95 ;; Extend Bessel functions to provide arbitrary precision.
96 ;; Extend advanced math functions to handle error forms and intervals.
97 ;; Provide a better implementation for math-sin-cos-raw.
98 ;; Provide a better implementation for math-hypot.
99 ;; Provide a better implementation for math-make-frac.
100 ;; Provide a better implementation for calcFunc-prfac.
101 ;; Provide a better implementation for calcFunc-factor.
102 ;;
103 ;; Provide more examples in the tutorial section of the manual.
104 ;; Cover in the tutorial: simplification modes, declarations,
105 ;; bitwise stuff, selections, matrix mapping, financial functions.
106 ;; Provide more Lisp programming examples in the manual.
107 ;; Finish the Internals section of the manual (and bring it up to date).
108 ;;
109 ;; Tim suggests adding spreadsheet-like features.
110 ;; Implement language modes for Gnuplot, Lisp, Ada, APL, ...?
111 ;;
112 ;; For atan series, if x > tan(pi/12) (about 0.268) reduce using the identity
113 ;; atan(x) = atan((x * sqrt(3) - 1) / (sqrt(3) + x)) + pi/6.
114 ;;
115 ;; A better integration algorithm:
116 ;; Use breadth-first instead of depth-first search, as follows:
117 ;; The integral cache allows unfinished integrals in symbolic notation
118 ;; on the righthand side. An entry with no unfinished integrals on the
119 ;; RHS is "complete"; references to it elsewhere are replaced by the
120 ;; integrated value. More than one cache entry for the same integral
121 ;; may exist, though if one becomes complete, the others may be deleted.
122 ;; The integrator works by using every applicable rule (such as
123 ;; substitution, parts, linearity, etc.) to generate possible righthand
124 ;; sides, all of which are entered into the cache. Now, as long as the
125 ;; target integral is not complete (and the time limit has not run out)
126 ;; choose an incomplete integral from the cache and, for every integral
127 ;; appearing in its RHS's, add those integrals to the cache using the
128 ;; same substitition, parts, etc. rules. The cache should be organized
129 ;; as a priority queue, choosing the "simplest" incomplete integral at
130 ;; each step, or choosing randomly among equally simple integrals.
131 ;; Simplicity equals small size, and few steps removed from the original
132 ;; target integral. Note that when the integrator finishes, incomplete
133 ;; integrals can be left in the cache, so the algorithm can start where
134 ;; it left off if another similar integral is later requested.
135 ;; Breadth-first search would avoid the nagging problem of, e.g., whether
136 ;; to use parts or substitution first, and which decomposition is best.
137 ;; All are tried, and any path that diverges will quickly be put on the
138 ;; back burner by the priority queue.
139 ;; Note: Probably a good idea to call math-simplify-extended before
140 ;; measuring a formula's simplicity.
141
142 ;;; Code:
143
144 (require 'calc-macs)
145
146 ;; Declare functions which are defined elsewhere.
147 (declare-function calc-set-language "calc-lang" (lang &optional option no-refresh))
148 (declare-function calc-edit-finish "calc-yank" (&optional keep))
149 (declare-function calc-edit-cancel "calc-yank" ())
150 (declare-function calc-do-quick-calc "calc-aent" ())
151 (declare-function calc-do-calc-eval "calc-aent" (str separator args))
152 (declare-function calc-do-keypad "calc-keypd" (&optional full-display interactive))
153 (declare-function calcFunc-unixtime "calc-forms" (date &optional zone))
154 (declare-function math-parse-date "calc-forms" (math-pd-str))
155 (declare-function math-lessp "calc-ext" (a b))
156 (declare-function math-compare "calc-ext" (a b))
157 (declare-function calc-embedded-finish-command "calc-embed" ())
158 (declare-function calc-embedded-select-buffer "calc-embed" ())
159 (declare-function calc-embedded-mode-line-change "calc-embed" ())
160 (declare-function calc-push-list-in-macro "calc-prog" (vals m sels))
161 (declare-function calc-replace-selections "calc-sel" (n vals m))
162 (declare-function calc-record-list "calc-misc" (vals &optional prefix))
163 (declare-function calc-normalize-fancy "calc-ext" (val))
164 (declare-function calc-do-handle-whys "calc-misc" ())
165 (declare-function calc-top-selected "calc-sel" (&optional n m))
166 (declare-function calc-sel-error "calc-sel" ())
167 (declare-function calc-pop-stack-in-macro "calc-prog" (n mm))
168 (declare-function calc-embedded-stack-change "calc-embed" ())
169 (declare-function calc-refresh-evaltos "calc-ext" (&optional which-var))
170 (declare-function calc-do-refresh "calc-misc" ())
171 (declare-function calc-binary-op-fancy "calc-ext" (name func arg ident unary))
172 (declare-function calc-unary-op-fancy "calc-ext" (name func arg))
173 (declare-function calc-delete-selection "calc-sel" (n))
174 (declare-function calc-alg-digit-entry "calc-aent" ())
175 (declare-function calc-alg-entry "calc-aent" (&optional initial prompt))
176 (declare-function calc-dots "calc-incom" ())
177 (declare-function calc-temp-minibuffer-message "calc-misc" (m))
178 (declare-function math-read-radix-digit "calc-misc" (dig))
179 (declare-function calc-digit-dots "calc-incom" ())
180 (declare-function math-normalize-fancy "calc-ext" (a))
181 (declare-function math-normalize-nonstandard "calc-ext" ())
182 (declare-function math-recompile-eval-rules "calc-alg" ())
183 (declare-function math-apply-rewrites "calc-rewr" (expr rules &optional heads math-apply-rw-ruleset))
184 (declare-function calc-record-why "calc-misc" (&rest stuff))
185 (declare-function math-dimension-error "calc-vec" ())
186 (declare-function calc-incomplete-error "calc-incom" (a))
187 (declare-function math-float-fancy "calc-arith" (a))
188 (declare-function math-neg-fancy "calc-arith" (a))
189 (declare-function calc-add-fractions "calc-frac" (a b))
190 (declare-function math-add-objects-fancy "calc-arith" (a b))
191 (declare-function math-add-symb-fancy "calc-arith" (a b))
192 (declare-function math-mul-zero "calc-arith" (a b))
193 (declare-function calc-mul-fractions "calc-frac" (a b))
194 (declare-function math-mul-objects-fancy "calc-arith" (a b))
195 (declare-function math-mul-symb-fancy "calc-arith" (a b))
196 (declare-function math-reject-arg "calc-misc" (&optional a p option))
197 (declare-function math-div-by-zero "calc-arith" (a b))
198 (declare-function math-div-zero "calc-arith" (a b))
199 (declare-function math-make-frac "calc-frac" (num den))
200 (declare-function calc-div-fractions "calc-frac" (a b))
201 (declare-function math-div-objects-fancy "calc-arith" (a b))
202 (declare-function math-div-symb-fancy "calc-arith" (a b))
203 (declare-function math-compose-expr "calccomp" (a prec))
204 (declare-function math-comp-width "calccomp" (c))
205 (declare-function math-composition-to-string "calccomp" (c &optional width))
206 (declare-function math-stack-value-offset-fancy "calccomp" ())
207 (declare-function math-format-flat-expr-fancy "calc-ext" (a prec))
208 (declare-function math-adjust-fraction "calc-ext" (a))
209 (declare-function math-format-binary "calc-bin" (a))
210 (declare-function math-format-radix "calc-bin" (a))
211 (declare-function math-format-twos-complement "calc-bin" (a))
212 (declare-function math-group-float "calc-ext" (str))
213 (declare-function math-mod "calc-misc" (a b))
214 (declare-function math-format-number-fancy "calc-ext" (a prec))
215 (declare-function math-format-bignum-fancy "calc-ext" (a))
216 (declare-function math-read-number-fancy "calc-ext" (s))
217 (declare-function calc-do-grab-region "calc-yank" (top bot arg))
218 (declare-function calc-do-grab-rectangle "calc-yank" (top bot arg &optional reduce))
219 (declare-function calc-do-embedded "calc-embed" (calc-embed-arg end obeg oend))
220 (declare-function calc-do-embedded-activate "calc-embed" (calc-embed-arg cbuf))
221 (declare-function math-do-defmath "calc-prog" (func args body))
222 (declare-function calc-load-everything "calc-ext" ())
223
224
225 (defgroup calc nil
226 "GNU Calc."
227 :prefix "calc-"
228 :tag "Calc"
229 :group 'applications)
230
231 ;; Do not autoload, so it is evaluated at run-time rather than at dump time.
232 ;; ;;;###autoload
233 (defcustom calc-settings-file
234 (locate-user-emacs-file "calc.el" ".calc.el")
235 "File in which to record permanent settings."
236 :group 'calc
237 :type '(file))
238
239 (defcustom calc-language-alist
240 '((latex-mode . latex)
241 (tex-mode . tex)
242 (plain-tex-mode . tex)
243 (context-mode . tex)
244 (nroff-mode . eqn)
245 (pascal-mode . pascal)
246 (c-mode . c)
247 (c++-mode . c)
248 (fortran-mode . fortran)
249 (f90-mode . fortran)
250 (texinfo-mode . calc-normal-language))
251 "Alist of major modes with appropriate Calc languages."
252 :group 'calc
253 :type '(alist :key-type (symbol :tag "Major mode")
254 :value-type (symbol :tag "Calc language")))
255
256 (defcustom calc-embedded-announce-formula
257 "%Embed\n\\(% .*\n\\)*"
258 "A regular expression which is sure to be followed by a calc-embedded formula."
259 :group 'calc
260 :type '(regexp))
261
262 (defcustom calc-embedded-announce-formula-alist
263 '((c++-mode . "//Embed\n\\(// .*\n\\)*")
264 (c-mode . "/\\*Embed\\*/\n\\(/\\* .*\\*/\n\\)*")
265 (f90-mode . "!Embed\n\\(! .*\n\\)*")
266 (fortran-mode . "C Embed\n\\(C .*\n\\)*")
267 (html-helper-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
268 (html-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
269 (nroff-mode . "\\\\\"Embed\n\\(\\\\\" .*\n\\)*")
270 (pascal-mode . "{Embed}\n\\({.*}\n\\)*")
271 (sgml-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
272 (xml-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
273 (texinfo-mode . "@c Embed\n\\(@c .*\n\\)*"))
274 "Alist of major modes with appropriate values for `calc-embedded-announce-formula'."
275 :group 'calc
276 :type '(alist :key-type (symbol :tag "Major mode")
277 :value-type (regexp :tag "Regexp to announce formula")))
278
279 (defcustom calc-embedded-open-formula
280 "\\`\\|^\n\\|\\$\\$?\\|\\\\\\[\\|^\\\\begin[^{].*\n\\|^\\\\begin{.*[^x]}.*\n\\|^@.*\n\\|^\\.EQ.*\n\\|\\\\(\\|^%\n\\|^\\.\\\\\"\n"
281 "A regular expression for the opening delimiter of a formula used by calc-embedded."
282 :group 'calc
283 :type '(regexp))
284
285 (defcustom calc-embedded-close-formula
286 "\\'\\|\n$\\|\\$\\$?\\|\\\\]\\|^\\\\end[^{].*\n\\|^\\\\end{.*[^x]}.*\n\\|^@.*\n\\|^\\.EN.*\n\\|\\\\)\\|\n%\n\\|^\\.\\\\\"\n"
287 "A regular expression for the closing delimiter of a formula used by calc-embedded."
288 :group 'calc
289 :type '(regexp))
290
291 (defcustom calc-embedded-open-close-formula-alist
292 nil
293 "Alist of major modes with pairs of formula delimiters used by calc-embedded."
294 :group 'calc
295 :type '(alist :key-type (symbol :tag "Major mode")
296 :value-type (list (regexp :tag "Opening formula delimiter")
297 (regexp :tag "Closing formula delimiter"))))
298
299 (defcustom calc-embedded-word-regexp
300 "[-+]?[0-9]+\\(\\.[0-9]+\\)?\\([eE][-+]?[0-9]+\\)?"
301 "A regular expression determining a word for calc-embedded-word."
302 :group 'calc
303 :type '(regexp))
304
305 (defcustom calc-embedded-word-regexp-alist
306 nil
307 "Alist of major modes with word regexps used by calc-embedded-word."
308 :group 'calc
309 :type '(alist :key-type (symbol :tag "Major mode")
310 :value-type (regexp :tag "Regexp for word")))
311
312 (defcustom calc-embedded-open-plain
313 "%%% "
314 "A string which is the opening delimiter for a \"plain\" formula.
315 If calc-show-plain mode is enabled, this is inserted at the front of
316 each formula."
317 :group 'calc
318 :type '(string))
319
320 (defcustom calc-embedded-close-plain
321 " %%%\n"
322 "A string which is the closing delimiter for a \"plain\" formula.
323 See calc-embedded-open-plain."
324 :group 'calc
325 :type '(string))
326
327 (defcustom calc-embedded-open-close-plain-alist
328 '((c++-mode "// %% " " %%\n")
329 (c-mode "/* %% " " %% */\n")
330 (f90-mode "! %% " " %%\n")
331 (fortran-mode "C %% " " %%\n")
332 (html-helper-mode "<!-- %% " " %% -->\n")
333 (html-mode "<!-- %% " " %% -->\n")
334 (nroff-mode "\\\" %% " " %%\n")
335 (pascal-mode "{%% " " %%}\n")
336 (sgml-mode "<!-- %% " " %% -->\n")
337 (xml-mode "<!-- %% " " %% -->\n")
338 (texinfo-mode "@c %% " " %%\n"))
339 "Alist of major modes with pairs of delimiters for \"plain\" formulas."
340 :group 'calc
341 :type '(alist :key-type (symbol :tag "Major mode")
342 :value-type (list (string :tag "Opening \"plain\" delimiter")
343 (string :tag "Closing \"plain\" delimiter"))))
344
345 (defcustom calc-embedded-open-new-formula
346 "\n\n"
347 "A string which is inserted at front of formula by calc-embedded-new-formula."
348 :group 'calc
349 :type '(string))
350
351 (defcustom calc-embedded-close-new-formula
352 "\n\n"
353 "A string which is inserted at end of formula by calc-embedded-new-formula."
354 :group 'calc
355 :type '(string))
356
357 (defcustom calc-embedded-open-close-new-formula-alist
358 nil
359 "Alist of major modes with pairs of new formula delimiters used by calc-embedded."
360 :group 'calc
361 :type '(alist :key-type (symbol :tag "Major mode")
362 :value-type (list (string :tag "Opening new formula delimiter")
363 (string :tag "Closing new formula delimiter"))))
364
365 (defcustom calc-embedded-open-mode
366 "% "
367 "A string which should precede calc-embedded mode annotations.
368 This is not required to be present for user-written mode annotations."
369 :group 'calc
370 :type '(string))
371
372 (defcustom calc-embedded-close-mode
373 "\n"
374 "A string which should follow calc-embedded mode annotations.
375 This is not required to be present for user-written mode annotations."
376 :group 'calc
377 :type '(string))
378
379 (defcustom calc-embedded-open-close-mode-alist
380 '((c++-mode "// " "\n")
381 (c-mode "/* " " */\n")
382 (f90-mode "! " "\n")
383 (fortran-mode "C " "\n")
384 (html-helper-mode "<!-- " " -->\n")
385 (html-mode "<!-- " " -->\n")
386 (nroff-mode "\\\" " "\n")
387 (pascal-mode "{ " " }\n")
388 (sgml-mode "<!-- " " -->\n")
389 (xml-mode "<!-- " " -->\n")
390 (texinfo-mode "@c " "\n"))
391 "Alist of major modes with pairs of strings to delimit annotations."
392 :group 'calc
393 :type '(alist :key-type (symbol :tag "Major mode")
394 :value-type (list (string :tag "Opening annotation delimiter")
395 (string :tag "Closing annotation delimiter"))))
396
397 (defcustom calc-gnuplot-name
398 (if (eq system-type 'windows-nt) "pgnuplot" "gnuplot")
399 "Name of GNUPLOT program, for calc-graph features."
400 :group 'calc
401 :type '(string))
402
403 (defcustom calc-gnuplot-plot-command
404 nil
405 "Name of command for displaying GNUPLOT output; %s = file name to print."
406 :group 'calc
407 :type '(choice (string) (sexp)))
408
409 (defcustom calc-gnuplot-print-command
410 "lp %s"
411 "Name of command for printing GNUPLOT output; %s = file name to print."
412 :group 'calc
413 :type '(choice (string) (sexp)))
414
415 (defcustom calc-multiplication-has-precedence
416 t
417 "If non-nil, multiplication has precedence over division
418 in normal mode."
419 :group 'calc
420 :type 'boolean)
421
422 (defcustom calc-undo-length
423 100
424 "The number of undo steps that will be preserved when Calc is quit."
425 :group 'calc
426 :type 'integer)
427
428 (defcustom calc-highlight-selections-with-faces
429 nil
430 "If non-nil, use a separate face to indicate selected sub-formulas.
431 If `calc-show-selections' is non-nil, then selected sub-formulas are shown
432 by displaying the rest of the formula in `calc-nonselected-face'.
433 If `calc-show-selections' is nil, then selected sub-formulas are shown
434 by displaying the sub-formula in `calc-selected-face'."
435 :group 'calc
436 :type 'boolean)
437
438 (defcustom calc-default-field-reference-level
439 "20 uPa"
440 "The default reference level for logarithmic units (field)."
441 :group 'calc
442 :type '(string))
443
444 (defcustom calc-default-power-reference-level
445 "mW"
446 "The default reference level for logarithmic units (power)."
447 :group 'calc
448 :type '(string))
449
450
451 (defface calc-nonselected-face
452 '((t :inherit shadow
453 :slant italic))
454 "Face used to show the non-selected portion of a formula."
455 :group 'calc)
456
457 (defface calc-selected-face
458 '((t :weight bold))
459 "Face used to show the selected portion of a formula."
460 :group 'calc)
461
462 (defvar calc-bug-address "jay.p.belanger@gmail.com"
463 "Address of the maintainer of Calc, for use by `report-calc-bug'.")
464
465 (defvar calc-scan-for-dels t
466 "If t, scan keymaps to find all DEL-like keys.
467 if nil, only DEL itself is mapped to calc-pop.")
468
469 (defvar calc-stack '((top-of-stack 1 nil))
470 "Calculator stack.
471 Entries are 3-lists: Formula, Height (in lines), Selection (or nil).")
472
473 (defvar calc-stack-top 1
474 "Index into `calc-stack' of \"top\" of stack.
475 This is 1 unless `calc-truncate-stack' has been used.")
476
477 (defvar calc-display-sci-high 0
478 "Floating-point numbers with this positive exponent or higher above the
479 current precision are displayed in scientific notation in calc-mode.")
480
481 (defvar calc-display-sci-low -3
482 "Floating-point numbers with this negative exponent or lower are displayed
483 scientific notation in calc-mode.")
484
485 (defvar calc-other-modes nil
486 "List of used-defined strings to append to Calculator mode line.")
487
488 (defvar calc-Y-help-msgs nil
489 "List of strings for Y prefix help.")
490
491 (defvar calc-loaded-settings-file nil
492 "t if `calc-settings-file' has been loaded yet.")
493
494
495 (defvar calc-mode-var-list '()
496 "List of variables used in customizing GNU Calc.")
497
498 (defmacro defcalcmodevar (var defval &optional doc)
499 "Declare VAR as a Calc variable, with default value DEFVAL
500 and doc-string DOC.
501 The variable VAR will be added to `calc-mode-var-list'."
502 `(progn
503 (defvar ,var ,defval ,doc)
504 (add-to-list 'calc-mode-var-list (list (quote ,var) ,defval))))
505
506 (defun calc-mode-var-list-restore-default-values ()
507 "Restore the default values of the variables in `calc-mode-var-list'."
508 (mapcar (function (lambda (v) (set (car v) (nth 1 v))))
509 calc-mode-var-list))
510
511 (defun calc-mode-var-list-restore-saved-values ()
512 "Restore the user-saved values of the variables in `calc-mode-var-list'."
513 (let ((newvarlist '()))
514 (save-excursion
515 (let (pos
516 (file (substitute-in-file-name calc-settings-file)))
517 (when (and
518 (file-regular-p file)
519 (set-buffer (find-file-noselect file))
520 (goto-char (point-min))
521 (search-forward ";;; Mode settings stored by Calc" nil t)
522 (progn
523 (forward-line 1)
524 (setq pos (point))
525 (search-forward "\n;;; End of mode settings" nil t)))
526 (beginning-of-line)
527 (calc-mode-var-list-restore-default-values)
528 (eval-region pos (point))
529 (let ((varlist calc-mode-var-list))
530 (while varlist
531 (let ((var (car varlist)))
532 (setq newvarlist
533 (cons (list (car var) (symbol-value (car var)))
534 newvarlist)))
535 (setq varlist (cdr varlist)))))))
536 (if newvarlist
537 (mapcar (function (lambda (v) (set (car v) (nth 1 v))))
538 newvarlist)
539 (calc-mode-var-list-restore-default-values))))
540
541 (defcalcmodevar calc-always-load-extensions nil
542 "If non-nil, load the calc-ext module automatically when Calc is loaded.")
543
544 (defcalcmodevar calc-line-numbering t
545 "If non-nil, display line numbers in Calculator stack.")
546
547 (defcalcmodevar calc-line-breaking t
548 "If non-nil, break long values across multiple lines in Calculator stack.")
549
550 (defcalcmodevar calc-display-just nil
551 "If nil, stack display is left-justified.
552 If `right', stack display is right-justified.
553 If `center', stack display is centered.")
554
555 (defcalcmodevar calc-display-origin nil
556 "Horizontal origin of displayed stack entries.
557 In left-justified mode, this is effectively indentation. (Default 0).
558 In right-justified mode, this is effectively window width.
559 In centered mode, center of stack entry is placed here.")
560
561 (defcalcmodevar calc-number-radix 10
562 "Radix for entry and display of numbers in calc-mode, 2-36.")
563
564 (defcalcmodevar calc-leading-zeros nil
565 "If non-nil, leading zeros are provided to pad integers to calc-word-size.")
566
567 (defcalcmodevar calc-group-digits nil
568 "If non-nil, group digits in large displayed integers by inserting spaces.
569 If an integer, group that many digits at a time.
570 If t, use 4 for binary and hex, 3 otherwise.")
571
572 (defcalcmodevar calc-group-char ","
573 "The character (in the form of a string) to be used for grouping digits.
574 This is used only when calc-group-digits mode is on.")
575
576 (defcalcmodevar calc-point-char "."
577 "The character (in the form of a string) to be used as a decimal point.")
578
579 (defcalcmodevar calc-frac-format '(":" nil)
580 "Format of displayed fractions; a string of one or two of \":\" or \"/\".")
581
582 (defcalcmodevar calc-prefer-frac nil
583 "If non-nil, prefer fractional over floating-point results.")
584
585 (defcalcmodevar calc-hms-format "%s@ %s' %s\""
586 "Format of displayed hours-minutes-seconds angles, a format string.
587 String must contain three %s marks for hours, minutes, seconds respectively.")
588
589 (defcalcmodevar calc-date-format '((H ":" mm C SS pp " ")
590 Www " " Mmm " " D ", " YYYY)
591 "Format of displayed date forms.")
592
593 (defcalcmodevar calc-float-format '(float 0)
594 "Format to use for display of floating-point numbers in calc-mode.
595 Must be a list of one of the following forms:
596 (float 0) Floating point format, display full precision.
597 (float N) N > 0: Floating point format, at most N significant figures.
598 (float -N) -N < 0: Floating point format, calc-internal-prec - N figs.
599 (fix N) N >= 0: Fixed point format, N places after decimal point.
600 (sci 0) Scientific notation, full precision.
601 (sci N) N > 0: Scientific notation, N significant figures.
602 (sci -N) -N < 0: Scientific notation, calc-internal-prec - N figs.
603 (eng 0) Engineering notation, full precision.
604 (eng N) N > 0: Engineering notation, N significant figures.
605 (eng -N) -N < 0: Engineering notation, calc-internal-prec - N figs.")
606
607 (defcalcmodevar calc-full-float-format '(float 0)
608 "Format to use when full precision must be displayed.")
609
610 (defcalcmodevar calc-complex-format nil
611 "Format to use for display of complex numbers in calc-mode. Must be one of:
612 nil Use (x, y) form.
613 i Use x + yi form.
614 j Use x + yj form.")
615
616 (defcalcmodevar calc-complex-mode 'cplx
617 "Preferred form, either `cplx' or `polar', for complex numbers.")
618
619 (defcalcmodevar calc-infinite-mode nil
620 "If nil, 1 / 0 is left unsimplified.
621 If 0, 1 / 0 is changed to inf (zeros are considered positive).
622 Otherwise, 1 / 0 is changed to uinf (undirected infinity).")
623
624 (defcalcmodevar calc-display-strings nil
625 "If non-nil, display vectors of byte-sized integers as strings.")
626
627 (defcalcmodevar calc-matrix-just 'center
628 "If nil, vector elements are left-justified.
629 If `right', vector elements are right-justified.
630 If `center', vector elements are centered.")
631
632 (defcalcmodevar calc-break-vectors nil
633 "If non-nil, display vectors one element per line.")
634
635 (defcalcmodevar calc-full-vectors t
636 "If non-nil, display long vectors in full. If nil, use abbreviated form.")
637
638 (defcalcmodevar calc-full-trail-vectors t
639 "If non-nil, display long vectors in full in the trail.")
640
641 (defcalcmodevar calc-vector-commas ","
642 "If non-nil, separate elements of displayed vectors with this string.")
643
644 (defcalcmodevar calc-vector-brackets "[]"
645 "If non-nil, surround displayed vectors with these characters.")
646
647 (defcalcmodevar calc-matrix-brackets '(R O)
648 "A list of code-letter symbols that control \"big\" matrix display.
649 If `R' is present, display inner brackets for matrices.
650 If `O' is present, display outer brackets for matrices (above/below).
651 If `C' is present, display outer brackets for matrices (centered).")
652
653 (defcalcmodevar calc-language nil
654 "Language or format for entry and display of stack values. Must be one of:
655 nil Use standard Calc notation.
656 flat Use standard Calc notation, one-line format.
657 big Display formulas in 2-d notation (enter w/std notation).
658 unform Use unformatted display: add(a, mul(b,c)).
659 c Use C language notation.
660 pascal Use Pascal language notation.
661 fortran Use Fortran language notation.
662 tex Use TeX notation.
663 latex Use LaTeX notation.
664 eqn Use eqn notation.
665 yacas Use Yacas notation.
666 maxima Use Maxima notation.
667 giac Use Giac notation.
668 math Use Mathematica(tm) notation.
669 maple Use Maple notation.")
670
671 (defcalcmodevar calc-language-option nil
672 "Numeric prefix argument for the command that set `calc-language'.")
673
674 (defcalcmodevar calc-left-label ""
675 "Label to display at left of formula.")
676
677 (defcalcmodevar calc-right-label ""
678 "Label to display at right of formula.")
679
680 (defcalcmodevar calc-word-size 32
681 "Minimum number of bits per word, if any, for binary operations in calc-mode.")
682
683 (defcalcmodevar calc-previous-modulo nil
684 "Most recently used value of M in a modulo form.")
685
686 (defcalcmodevar calc-simplify-mode nil
687 "Type of simplification applied to results.
688 If `none', results are not simplified when pushed on the stack.
689 If `num', functions are simplified only when args are constant.
690 If nil, only fast simplifications are applied.
691 If `binary', `math-clip' is applied if appropriate.
692 If `alg', `math-simplify' is applied.
693 If `ext', `math-simplify-extended' is applied.
694 If `units', `math-simplify-units' is applied.")
695
696 (defcalcmodevar calc-auto-recompute t
697 "If non-nil, recompute evalto's automatically when necessary.")
698
699 (defcalcmodevar calc-display-raw nil
700 "If non-nil, display shows unformatted Lisp exprs. (For debugging)")
701
702 (defcalcmodevar calc-internal-prec 12
703 "Number of digits of internal precision for calc-mode calculations.")
704
705 (defcalcmodevar calc-angle-mode 'deg
706 "If deg, angles are in degrees; if rad, angles are in radians.
707 If hms, angles are in degrees-minutes-seconds.")
708
709 (defcalcmodevar calc-algebraic-mode nil
710 "If non-nil, numeric entry accepts whole algebraic expressions.
711 If nil, algebraic expressions must be preceded by \"'\".")
712
713 (defcalcmodevar calc-incomplete-algebraic-mode nil
714 "Like calc-algebraic-mode except only affects ( and [ keys.")
715
716 (defcalcmodevar calc-symbolic-mode nil
717 "If non-nil, inexact numeric computations like sqrt(2) are postponed.
718 If nil, computations on numbers always yield numbers where possible.")
719
720 (defcalcmodevar calc-matrix-mode nil
721 "If `matrix', variables are assumed to be matrix-valued.
722 If a number, variables are assumed to be NxN matrices.
723 If `sqmatrix', variables are assumed to be square matrices of an unspecified size.
724 If `scalar', variables are assumed to be scalar-valued.
725 If nil, symbolic math routines make no assumptions about variables.")
726
727 (defcalcmodevar calc-twos-complement-mode nil
728 "If non-nil, display integers in two's complement mode.")
729
730
731 (defcalcmodevar calc-shift-prefix nil
732 "If non-nil, shifted letter keys are prefix keys rather than normal meanings.")
733
734 (defcalcmodevar calc-window-height 7
735 "Initial height of Calculator window.")
736
737 (defcalcmodevar calc-display-trail t
738 "If non-nil, M-x calc creates a window to display Calculator trail.")
739
740 (defcalcmodevar calc-show-selections t
741 "If non-nil, selected sub-formulas are shown by obscuring rest of formula.
742 If nil, selected sub-formulas are highlighted by obscuring the sub-formulas.")
743
744 (defcalcmodevar calc-use-selections t
745 "If non-nil, commands operate only on selected portions of formulas.
746 If nil, selections displayed but ignored.")
747
748 (defcalcmodevar calc-assoc-selections t
749 "If non-nil, selection hides deep structure of associative formulas.")
750
751 (defcalcmodevar calc-display-working-message 'lots
752 "If non-nil, display \"Working...\" for potentially slow Calculator commands.")
753
754 (defcalcmodevar calc-auto-why 'maybe
755 "If non-nil, automatically execute a \"why\" command to explain odd results.")
756
757 (defcalcmodevar calc-timing nil
758 "If non-nil, display timing information on each slow command.")
759
760 (defcalcmodevar calc-mode-save-mode 'local)
761
762 (defcalcmodevar calc-standard-date-formats
763 '("N"
764 "<H:mm:SSpp >Www Mmm D, YYYY"
765 "D Mmm YYYY<, h:mm:SS>"
766 "Www Mmm BD< hh:mm:ss> YYYY"
767 "M/D/Y< H:mm:SSpp>"
768 "D.M.Y< h:mm:SS>"
769 "M-D-Y< H:mm:SSpp>"
770 "D-M-Y< h:mm:SS>"
771 "j<, h:mm:SS>"
772 "YYddd< hh:mm:ss>"))
773
774 (defcalcmodevar calc-autorange-units nil
775 "If non-nil, automatically set unit prefixes to keep units in a reasonable range.")
776
777 (defcalcmodevar calc-was-keypad-mode nil
778 "Non-nil if Calc was last invoked in keypad mode.")
779
780 (defcalcmodevar calc-full-mode nil
781 "Non-nil if Calc was last invoked in full-screen mode.")
782
783 (defcalcmodevar calc-user-parse-tables nil
784 "Alist of languages with user-defined parse rules.")
785
786 (defcalcmodevar calc-gnuplot-default-device "default"
787 "The default device name for GNUPLOT plotting.")
788
789 (defcalcmodevar calc-gnuplot-default-output "STDOUT"
790 "The default output file for GNUPLOT plotting.")
791
792 (defcalcmodevar calc-gnuplot-print-device "postscript"
793 "The default device name for GNUPLOT printing.")
794
795 (defcalcmodevar calc-gnuplot-print-output "auto"
796 "The default output for GNUPLOT printing.")
797
798 (defcalcmodevar calc-gnuplot-geometry nil
799 "The default geometry for the GNUPLOT window.")
800
801 (defcalcmodevar calc-graph-default-resolution 15
802 "The default number of data points when plotting curves.")
803
804 (defcalcmodevar calc-graph-default-resolution-3d 5
805 "The default number of x- and y- data points when plotting surfaces.")
806
807 (defcalcmodevar calc-invocation-macro nil
808 "A user defined macro for starting Calc.
809 Used by `calc-user-invocation'.")
810
811 (defcalcmodevar calc-show-banner t
812 "*If non-nil, show a friendly greeting above the stack.")
813
814 (defconst calc-local-var-list '(calc-stack
815 calc-stack-top
816 calc-undo-list
817 calc-redo-list
818 calc-always-load-extensions
819 calc-mode-save-mode
820 calc-display-raw
821 calc-line-numbering
822 calc-line-breaking
823 calc-display-just
824 calc-display-origin
825 calc-left-label
826 calc-right-label
827 calc-auto-why
828 calc-algebraic-mode
829 calc-incomplete-algebraic-mode
830 calc-symbolic-mode
831 calc-matrix-mode
832 calc-inverse-flag
833 calc-hyperbolic-flag
834 calc-option-flag
835 calc-keep-args-flag
836 calc-angle-mode
837 calc-number-radix
838 calc-leading-zeros
839 calc-group-digits
840 calc-group-char
841 calc-point-char
842 calc-frac-format
843 calc-prefer-frac
844 calc-hms-format
845 calc-date-format
846 calc-standard-date-formats
847 calc-float-format
848 calc-full-float-format
849 calc-complex-format
850 calc-matrix-just
851 calc-full-vectors
852 calc-full-trail-vectors
853 calc-break-vectors
854 calc-vector-commas
855 calc-vector-brackets
856 calc-matrix-brackets
857 calc-complex-mode
858 calc-infinite-mode
859 calc-display-strings
860 calc-simplify-mode
861 calc-auto-recompute
862 calc-autorange-units
863 calc-show-plain
864 calc-show-selections
865 calc-use-selections
866 calc-assoc-selections
867 calc-word-size
868 calc-internal-prec))
869
870 (defvar calc-mode-hook nil
871 "Hook run when entering calc-mode.")
872
873 (defvar calc-trail-mode-hook nil
874 "Hook run when entering calc-trail-mode.")
875
876 (defvar calc-start-hook nil
877 "Hook run when calc is started.")
878
879 (defvar calc-end-hook nil
880 "Hook run when calc is quit.")
881
882 (defvar calc-load-hook nil
883 "Hook run when calc.el is loaded.")
884
885 (defvar calc-window-hook nil
886 "Hook called to create the Calc window.")
887
888 (defvar calc-trail-window-hook nil
889 "Hook called to create the Calc trail window.")
890
891 (defvar calc-embedded-new-buffer-hook nil
892 "Hook run when starting embedded mode in a new buffer.")
893
894 (defvar calc-embedded-new-formula-hook nil
895 "Hook run when starting embedded mode in a new formula.")
896
897 (defvar calc-embedded-mode-hook nil
898 "Hook run when starting embedded mode.")
899
900 ;; Set up the autoloading linkage.
901 (let ((name (and (fboundp 'calc-dispatch)
902 (eq (car-safe (symbol-function 'calc-dispatch)) 'autoload)
903 (nth 1 (symbol-function 'calc-dispatch))))
904 (p load-path))
905
906 ;; If Calc files exist on the load-path, we're all set.
907 (while (and p (not (file-exists-p
908 (expand-file-name "calc-misc.elc" (car p)))))
909 (setq p (cdr p)))
910 (or p
911
912 ;; If Calc is autoloaded using a path name, look there for Calc files.
913 ;; This works for both relative ("calc/calc.elc") and absolute paths.
914 (and name (file-name-directory name)
915 (let ((p2 load-path)
916 (name2 (concat (file-name-directory name)
917 "calc-misc.elc")))
918 (while (and p2 (not (file-exists-p
919 (expand-file-name name2 (car p2)))))
920 (setq p2 (cdr p2)))
921 (when p2
922 (setq load-path (nconc load-path
923 (list
924 (directory-file-name
925 (file-name-directory
926 (expand-file-name
927 name (car p2))))))))))))
928
929 ;; The following modes use specially-formatted data.
930 (put 'calc-mode 'mode-class 'special)
931 (put 'calc-trail-mode 'mode-class 'special)
932
933 ;; Define "inexact-result" as an e-lisp error symbol.
934 (put 'inexact-result 'error-conditions '(error inexact-result calc-error))
935 (put 'inexact-result 'error-message "Calc internal error (inexact-result)")
936
937 ;; Define "math-overflow" and "math-underflow" as e-lisp error symbols.
938 (put 'math-overflow 'error-conditions '(error math-overflow calc-error))
939 (put 'math-overflow 'error-message "Floating-point overflow occurred")
940 (put 'math-underflow 'error-conditions '(error math-underflow calc-error))
941 (put 'math-underflow 'error-message "Floating-point underflow occurred")
942
943 (defvar calc-trail-pointer nil
944 "The \"current\" entry in trail buffer.")
945 (defvar calc-trail-overlay nil
946 "The value of overlay-arrow-string.")
947 (defvar calc-undo-list nil
948 "The list of previous operations for undo.")
949 (defvar calc-redo-list nil
950 "The list of recent undo operations.")
951 (defvar calc-main-buffer nil
952 "A pointer to Calculator buffer.")
953 (defvar calc-buffer-list nil
954 "A list of all Calc buffers.")
955 (defvar calc-trail-buffer nil
956 "A pointer to Calc Trail buffer.")
957 (defvar calc-why nil
958 "Explanations of most recent errors.")
959 (defvar calc-next-why nil)
960 (defvar calc-inverse-flag nil
961 "If non-nil, next operation is Inverse.")
962 (defvar calc-hyperbolic-flag nil
963 "If non-nil, next operation is Hyperbolic.")
964 (defvar calc-option-flag nil
965 "If non-nil, next operation has Optional behavior.")
966 (defvar calc-keep-args-flag nil
967 "If non-nil, next operation should not remove its arguments from stack.")
968 (defvar calc-function-open "("
969 "Open-parenthesis string for function call notation.")
970 (defvar calc-function-close ")"
971 "Close-parenthesis string for function call notation.")
972 (defvar calc-language-output-filter nil
973 "Function through which to pass strings after formatting.")
974 (defvar calc-language-input-filter nil
975 "Function through which to pass strings before parsing.")
976 (defvar calc-radix-formatter nil
977 "Formatting function used for non-decimal numbers.")
978 (defvar calc-lang-slash-idiv nil
979 "A list of languages in which / might represent integer division.")
980 (defvar calc-lang-allow-underscores nil
981 "A list of languages which allow underscores in variable names.")
982 (defvar calc-lang-allow-percentsigns nil
983 "A list of languages which allow percent signs in variable names.")
984 (defvar calc-lang-c-type-hex nil
985 "Languages in which octal and hex numbers are written with leading 0 and 0x,")
986 (defvar calc-lang-brackets-are-subscripts nil
987 "Languages in which subscripts are indicated by brackets.")
988 (defvar calc-lang-parens-are-subscripts nil
989 "Languages in which subscripts are indicated by parentheses.")
990
991 (defvar calc-last-kill nil
992 "The last number killed in calc-mode.")
993 (defvar calc-dollar-values nil
994 "Values to be used for '$'.")
995 (defvar calc-dollar-used nil
996 "The highest order of '$' that occurred.")
997 (defvar calc-hashes-used nil
998 "The highest order of '#' that occurred.")
999 (defvar calc-quick-prev-results nil
1000 "Previous results from Quick Calc.")
1001 (defvar calc-said-hello nil
1002 "Non-nil if the welcomd message has been displayed.")
1003 (defvar calc-executing-macro nil
1004 "Non-nil if a keyboard macro is executing from the \"K\" key.")
1005 (defvar calc-any-selections nil
1006 "Non-nil if there are selections present.")
1007 (defvar calc-help-phase 0
1008 "The number of consecutive \"?\" keystrokes.")
1009 (defvar calc-full-help-flag nil
1010 "Non-nil if `calc-full-help' is being executed.")
1011 (defvar calc-refresh-count 0
1012 "The number of `calc-refresh' calls.")
1013 (defvar calc-display-dirty nil
1014 "Non-nil if the stack display might not reflect the latest mode settings.")
1015 (defvar calc-prepared-composition nil)
1016 (defvar calc-selection-cache-default-entry nil)
1017 (defvar calc-embedded-info nil
1018 "If non-nil, a vector consisting of information for embedded mode.")
1019 (defvar calc-embedded-active nil
1020 "Alist of buffers with sorted lists of calc-embedded-infos.")
1021 (defvar calc-standalone-flag nil
1022 "Non-nil if Emacs started with standalone Calc.")
1023 (defvar var-EvalRules nil
1024 "User defined rules that Calc will apply automatically.")
1025 (defvar math-eval-rules-cache-tag t)
1026 (defvar math-radix-explicit-format t)
1027 (defvar math-expr-function-mapping nil
1028 "Alist of language specific functions with Calc functions.")
1029 (defvar math-expr-variable-mapping nil
1030 "Alist of language specific variables with Calc variables.")
1031 (defvar math-read-expr-quotes nil)
1032 (defvar math-working-step nil)
1033 (defvar math-working-step-2 nil)
1034 (defvar var-i '(special-const (math-imaginary 1)))
1035 (defvar var-pi '(special-const (math-pi)))
1036 (defvar var-Ï€ '(special-const (math-pi)))
1037 (defvar var-e '(special-const (math-e)))
1038 (defvar var-phi '(special-const (math-phi)))
1039 (defvar var-φ '(special-const (math-phi)))
1040 (defvar var-gamma '(special-const (math-gamma-const)))
1041 (defvar var-γ '(special-const (math-gamma-const)))
1042 (defvar var-Modes '(special-const (math-get-modes-vec)))
1043
1044 (mapc (lambda (v) (or (boundp v) (set v nil)))
1045 calc-local-var-list)
1046
1047 (defvar calc-mode-map
1048 (let ((map (make-keymap)))
1049 (suppress-keymap map t)
1050 (define-key map "+" 'calc-plus)
1051 (define-key map "-" 'calc-minus)
1052 (define-key map "*" 'calc-times)
1053 (define-key map "/" 'calc-divide)
1054 (define-key map "%" 'calc-mod)
1055 (define-key map "&" 'calc-inv)
1056 (define-key map "^" 'calc-power)
1057 (define-key map "\M-%" 'calc-percent)
1058 (define-key map "e" 'calcDigit-start)
1059 (define-key map "i" 'calc-info)
1060 (define-key map "n" 'calc-change-sign)
1061 (define-key map "q" 'calc-quit)
1062 (define-key map "Y" 'nil)
1063 (define-key map "Y?" 'calc-shift-Y-prefix-help)
1064 (define-key map "?" 'calc-help)
1065 (define-key map " " 'calc-enter)
1066 (define-key map "'" 'calc-algebraic-entry)
1067 (define-key map "$" 'calc-auto-algebraic-entry)
1068 (define-key map "\"" 'calc-auto-algebraic-entry)
1069 (define-key map "\t" 'calc-roll-down)
1070 (define-key map "\M-\t" 'calc-roll-up)
1071 (define-key map "\C-x\C-t" 'calc-transpose-lines)
1072 (define-key map "\C-m" 'calc-enter)
1073 (define-key map "\M-\C-m" 'calc-last-args-stub)
1074 (define-key map "\C-j" 'calc-over)
1075 (define-key map "\C-y" 'calc-yank)
1076 (define-key map [mouse-2] 'calc-yank)
1077 (define-key map [remap undo] 'calc-undo)
1078
1079 (mapc (lambda (x) (define-key map (char-to-string x) 'undefined))
1080 "lOW")
1081 (mapc (lambda (x) (define-key map (char-to-string x) 'calc-missing-key))
1082 (concat "ABCDEFGHIJKLMNOPQRSTUVXZabcdfghjkmoprstuvwxyz"
1083 ":\\|!()[]<>{},;=~`\C-k\C-w\C-_"))
1084 (define-key map "\M-w" 'calc-missing-key)
1085 (define-key map "\M-k" 'calc-missing-key)
1086 (define-key map "\M-\C-w" 'calc-missing-key)
1087 (mapc (lambda (x) (define-key map (char-to-string x) 'calcDigit-start))
1088 "_0123456789.#@")
1089 map)
1090 "The key map for Calc.")
1091
1092 (defvar calc-digit-map
1093 (let ((map (make-keymap)))
1094 (map-keymap (lambda (key bind)
1095 (define-key map (vector key)
1096 (if (eq bind 'undefined)
1097 'undefined 'calcDigit-nondigit)))
1098 calc-mode-map)
1099 (mapc (lambda (x) (define-key map (char-to-string x) 'calcDigit-key))
1100 "_0123456789.e+-:n#@oh'\"mspM")
1101 (mapc (lambda (x) (define-key map (char-to-string x) 'calcDigit-letter))
1102 "abcdfgijklqrtuvwxyzABCDEFGHIJKLNOPQRSTUVWXYZ")
1103 (define-key map "'" 'calcDigit-algebraic)
1104 (define-key map "`" 'calcDigit-edit)
1105 (define-key map "\C-g" 'abort-recursive-edit)
1106 map)
1107 "The key map for entering Calc digits.")
1108
1109 (mapc (lambda (x)
1110 (condition-case err
1111 (progn
1112 (define-key calc-digit-map x 'calcDigit-backspace)
1113 (define-key calc-mode-map x 'calc-pop)
1114 (define-key calc-mode-map
1115 (if (and (vectorp x) (featurep 'xemacs))
1116 (if (= (length x) 1)
1117 (vector (if (consp (aref x 0))
1118 (cons 'meta (aref x 0))
1119 (list 'meta (aref x 0))))
1120 "\e\C-d")
1121 (vconcat "\e" x))
1122 'calc-pop-above))
1123 (error nil)))
1124 (if calc-scan-for-dels
1125 (append (where-is-internal 'delete-backward-char global-map)
1126 (where-is-internal 'backward-delete-char global-map)
1127 (where-is-internal 'backward-delete-char-untabify global-map)
1128 '("\C-d"))
1129 '("\177" "\C-d")))
1130
1131 (defvar calc-dispatch-map
1132 (let ((map (make-keymap)))
1133 (mapc (lambda (x)
1134 (let* ((x-chr (car x))
1135 (x-str (char-to-string x-chr))
1136 (x-def (cdr x)))
1137 (define-key map x-str x-def)
1138 (when (string-match "[a-z]" x-str)
1139 ;; Map upper case char to same definition.
1140 (define-key map (upcase x-str) x-def)
1141 (unless (string-match "[gmv]" x-str)
1142 ;; Map control prefixed char to same definition.
1143 (define-key map (vector (list 'control x-chr)) x-def)))
1144 (define-key map (format "\e%c" x-chr) x-def)))
1145 '( ( ?a . calc-embedded-activate )
1146 ( ?b . calc-big-or-small )
1147 ( ?c . calc )
1148 ( ?d . calc-embedded-duplicate )
1149 ( ?e . calc-embedded )
1150 ( ?f . calc-embedded-new-formula )
1151 ( ?g . calc-grab-region )
1152 ( ?h . calc-dispatch-help )
1153 ( ?i . calc-info )
1154 ( ?j . calc-embedded-select )
1155 ( ?k . calc-keypad )
1156 ( ?l . calc-load-everything )
1157 ( ?m . read-kbd-macro )
1158 ( ?n . calc-embedded-next )
1159 ( ?o . calc-other-window )
1160 ( ?p . calc-embedded-previous )
1161 ( ?q . quick-calc )
1162 ( ?r . calc-grab-rectangle )
1163 ( ?s . calc-info-summary )
1164 ( ?t . calc-tutorial )
1165 ( ?u . calc-embedded-update-formula )
1166 ( ?w . calc-embedded-word )
1167 ( ?x . calc-quit )
1168 ( ?y . calc-copy-to-buffer )
1169 ( ?z . calc-user-invocation )
1170 ( ?\' . calc-embedded-new-formula )
1171 ( ?\` . calc-embedded-edit )
1172 ( ?: . calc-grab-sum-down )
1173 ( ?_ . calc-grab-sum-across )
1174 ( ?0 . calc-reset )
1175 ( ?? . calc-dispatch-help )
1176 ( ?# . calc-same-interface )
1177 ( ?& . calc-same-interface )
1178 ( ?\\ . calc-same-interface )
1179 ( ?= . calc-same-interface )
1180 ( ?* . calc-same-interface )
1181 ( ?/ . calc-same-interface )
1182 ( ?+ . calc-same-interface )
1183 ( ?- . calc-same-interface ) ))
1184 map)
1185 "The key map for starting Calc.")
1186
1187
1188 ;;;; (Autoloads here)
1189 (load "calc-loaddefs.el" nil t)
1190
1191 ;;;###autoload (define-key ctl-x-map "*" 'calc-dispatch)
1192
1193 ;;;###autoload
1194 (defun calc-dispatch (&optional arg)
1195 "Invoke the GNU Emacs Calculator. See `calc-dispatch-help' for details."
1196 (interactive "P")
1197 ; (sit-for echo-keystrokes)
1198 (condition-case err ; look for other keys bound to calc-dispatch
1199 (let ((keys (this-command-keys)))
1200 (unless (or (not (stringp keys))
1201 (string-match "\\`\C-u\\|\\`\e[-0-9#]\\|`[\M--\M-0-\M-9]" keys)
1202 (eq (lookup-key calc-dispatch-map keys) 'calc-same-interface))
1203 (when (and (string-match "\\`[\C-@-\C-_]" keys)
1204 (symbolp
1205 (lookup-key calc-dispatch-map (substring keys 0 1))))
1206 (define-key calc-dispatch-map (substring keys 0 1) nil))
1207 (define-key calc-dispatch-map keys 'calc-same-interface)))
1208 (error nil))
1209 (calc-do-dispatch arg))
1210
1211 (defvar calc-dispatch-help nil)
1212 (defun calc-do-dispatch (arg)
1213 "Start the Calculator."
1214 (let ((key (calc-read-key-sequence
1215 (if calc-dispatch-help
1216 "Calc options: Calc, Keypad, Quick, Embed; eXit; Info, Tutorial; Grab; ?=more"
1217 (format "%s (Type ? for a list of Calc options)"
1218 (key-description (this-command-keys))))
1219 calc-dispatch-map)))
1220 (setq key (lookup-key calc-dispatch-map key))
1221 (message "")
1222 (if key
1223 (progn
1224 (or (commandp key) (require 'calc-ext))
1225 (call-interactively key))
1226 (beep))))
1227
1228 (defun calc-read-key-sequence (prompt map)
1229 "Read keys, with prompt PROMPT and keymap MAP."
1230 (let ((prompt2 (format "%s " (key-description (this-command-keys))))
1231 (glob (current-global-map))
1232 (loc (current-local-map)))
1233 (or (input-pending-p) (message "%s" prompt))
1234 (let ((key (calc-read-key t)))
1235 (calc-unread-command (cdr key))
1236 (unwind-protect
1237 (progn
1238 (use-global-map map)
1239 (use-local-map nil)
1240 (read-key-sequence nil))
1241 (use-global-map glob)
1242 (use-local-map loc)))))
1243
1244 (defvar calc-alg-map) ; Defined in calc-ext.el
1245
1246
1247 (defvar calc-embedded-modes) ; Defined in calc-embed.el
1248 (defvar calc-override-minor-modes) ; Defined in calc-embed.el
1249 (defun calc-kill-stack-buffer ()
1250 "Check to see if user wants to kill the Calc stack buffer.
1251 This will look for buffers using the Calc buffer for embedded mode,
1252 and inform the user if there are any.
1253 If the user wants to kill the Calc buffer, this will remove
1254 embedded information from the appropriate buffers and tidy up
1255 the trail buffer."
1256 (let ((cb (current-buffer))
1257 (info-list nil)
1258 (buflist)
1259 ; (plural nil)
1260 (cea calc-embedded-active))
1261 ;; Get a list of all buffers using this buffer for
1262 ;; embedded Calc.
1263 (while cea
1264 (when (and (eq cb (aref (nth 1 (car cea)) 1))
1265 (buffer-name (car (car cea))))
1266 (setq info-list (cons (car cea) info-list)))
1267 (setq cea (cdr cea)))
1268 ;; Eventually, prompt user with a list of buffers using embedded mode.
1269 (when (and
1270 info-list
1271 (yes-or-no-p
1272 (concat "This Calc stack is being used for embedded mode. Kill anyway?")))
1273 (while info-list
1274 (with-current-buffer (car (car info-list))
1275 (when calc-embedded-info
1276 (setq calc-embedded-info nil
1277 mode-line-buffer-identification (car calc-embedded-modes)
1278 truncate-lines (nth 2 calc-embedded-modes)
1279 buffer-read-only nil)
1280 (use-local-map (nth 1 calc-embedded-modes))
1281 (setq minor-mode-overriding-map-alist
1282 (remq calc-override-minor-modes minor-mode-overriding-map-alist))
1283 (let ((str mode-line-buffer-identification))
1284 (setq mode-line-buffer-identification str))
1285 (set-buffer-modified-p (buffer-modified-p))))
1286 (setq calc-embedded-active
1287 (delete (car info-list) calc-embedded-active))
1288 (setq info-list (cdr info-list))))
1289 (if (not info-list)
1290 (progn
1291 (setq calc-buffer-list (delete cb calc-buffer-list))
1292 (with-current-buffer calc-trail-buffer
1293 (if (eq cb calc-main-buffer)
1294 ;; If there are other Calc stacks, make another one
1295 ;; the calc-main-buffer ...
1296 (if calc-buffer-list
1297 (setq calc-main-buffer (car calc-buffer-list))
1298 ;; ... otherwise kill the trail and its windows.
1299 (let ((wl (get-buffer-window-list calc-trail-buffer)))
1300 (while wl
1301 (delete-window (car wl))
1302 (setq wl (cdr wl))))
1303 (kill-buffer calc-trail-buffer)
1304 (setq calc-trail-buffer nil))))
1305 t))))
1306
1307 (defun calc-mode ()
1308 "Calculator major mode.
1309
1310 This is an RPN calculator featuring arbitrary-precision integer, rational,
1311 floating-point, complex, matrix, and symbolic arithmetic.
1312
1313 RPN calculation: 2 RET 3 + produces 5.
1314 Algebraic style: ' 2+3 RET produces 5.
1315
1316 Basic operators are +, -, *, /, ^, & (reciprocal), % (modulo), n (change-sign).
1317
1318 Press ? repeatedly for more complete help. Press `h i' to read the
1319 Calc manual on-line, `h s' to read the summary, or `h t' for the tutorial.
1320
1321 Notations: 3.14e6 3.14 * 10^6
1322 _23 negative number -23 (or type `23 n')
1323 17:3 the fraction 17/3
1324 5:2:3 the fraction 5 and 2/3
1325 16#12C the integer 12C base 16 = 300 base 10
1326 8#177:100 the fraction 177:100 base 8 = 127:64 base 10
1327 (2, 4) complex number 2 + 4i
1328 (2; 4) polar complex number (r; theta)
1329 [1, 2, 3] vector ([[1, 2], [3, 4]] is a matrix)
1330 [1 .. 4) semi-open interval, 1 <= x < 4
1331 2 +/- 3 (p key) number with mean 2, standard deviation 3
1332 2 mod 3 (M key) number 2 computed modulo 3
1333 <1 jan 91> Date form (enter using ' key)
1334
1335
1336 \\{calc-mode-map}
1337 "
1338 (interactive)
1339 (mapc (function
1340 (lambda (v) (set-default v (symbol-value v)))) calc-local-var-list)
1341 (kill-all-local-variables)
1342 (use-local-map (if (eq calc-algebraic-mode 'total)
1343 (progn (require 'calc-ext) calc-alg-map) calc-mode-map))
1344 (mapc (function (lambda (v) (make-local-variable v))) calc-local-var-list)
1345 (make-local-variable 'overlay-arrow-position)
1346 (make-local-variable 'overlay-arrow-string)
1347 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
1348 (add-hook 'kill-buffer-query-functions
1349 'calc-kill-stack-buffer
1350 t t)
1351 (setq truncate-lines t)
1352 (setq buffer-read-only t)
1353 (setq major-mode 'calc-mode)
1354 (setq mode-name "Calculator")
1355 (setq calc-stack-top (length (or (memq (assq 'top-of-stack calc-stack)
1356 calc-stack)
1357 (setq calc-stack (list (list 'top-of-stack
1358 1 nil))))))
1359 (setq calc-stack-top (- (length calc-stack) calc-stack-top -1))
1360 (or calc-loaded-settings-file
1361 (null calc-settings-file)
1362 (equal calc-settings-file user-init-file)
1363 (progn
1364 (setq calc-loaded-settings-file t)
1365 (load (file-name-sans-extension calc-settings-file) t))) ; t = missing-ok
1366 (let ((p command-line-args))
1367 (while p
1368 (and (equal (car p) "-f")
1369 (string-match "calc" (nth 1 p))
1370 (string-match "full" (nth 1 p))
1371 (setq calc-standalone-flag t))
1372 (setq p (cdr p))))
1373 (require 'calc-menu)
1374 (run-mode-hooks 'calc-mode-hook)
1375 (calc-refresh t)
1376 (calc-set-mode-line)
1377 (calc-check-defines)
1378 (if calc-buffer-list (setq calc-stack (copy-sequence calc-stack)))
1379 (add-to-list 'calc-buffer-list (current-buffer) t))
1380
1381 (defvar calc-check-defines 'calc-check-defines) ; suitable for run-hooks
1382 (defun calc-check-defines ()
1383 (if (symbol-plist 'calc-define)
1384 (let ((plist (copy-sequence (symbol-plist 'calc-define))))
1385 (while (and plist (null (nth 1 plist)))
1386 (setq plist (cdr (cdr plist))))
1387 (if plist
1388 (save-excursion
1389 (require 'calc-ext)
1390 (require 'calc-macs)
1391 (set-buffer "*Calculator*")
1392 (while plist
1393 (put 'calc-define (car plist) nil)
1394 (eval (nth 1 plist))
1395 (setq plist (cdr (cdr plist))))
1396 ;; See if this has added any more calc-define properties.
1397 (calc-check-defines))
1398 (setplist 'calc-define nil)))))
1399
1400 (defun calc-trail-mode (&optional buf)
1401 "Calc Trail mode.
1402 This mode is used by the *Calc Trail* buffer, which records all results
1403 obtained by the GNU Emacs Calculator.
1404
1405 Calculator commands beginning with the `t' key are used to manipulate
1406 the Trail.
1407
1408 This buffer uses the same key map as the *Calculator* buffer; calculator
1409 commands given here will actually operate on the *Calculator* stack."
1410 (interactive)
1411 (fundamental-mode)
1412 (use-local-map calc-mode-map)
1413 (setq major-mode 'calc-trail-mode)
1414 (setq mode-name "Calc Trail")
1415 (setq truncate-lines t)
1416 (setq buffer-read-only t)
1417 (make-local-variable 'overlay-arrow-position)
1418 (make-local-variable 'overlay-arrow-string)
1419 (when buf
1420 (set (make-local-variable 'calc-main-buffer) buf))
1421 (when (= (buffer-size) 0)
1422 (let ((buffer-read-only nil))
1423 (insert (propertize "Emacs Calculator Trail\n" 'face 'italic))))
1424 (run-mode-hooks 'calc-trail-mode-hook))
1425
1426 (defun calc-create-buffer ()
1427 "Create and initialize a buffer for the Calculator."
1428 (set-buffer (get-buffer-create "*Calculator*"))
1429 (or (eq major-mode 'calc-mode)
1430 (calc-mode))
1431 (setq max-lisp-eval-depth (max max-lisp-eval-depth 1000))
1432 (when calc-always-load-extensions
1433 (require 'calc-ext))
1434 (when calc-language
1435 (require 'calc-ext)
1436 (calc-set-language calc-language calc-language-option t)))
1437
1438 ;;;###autoload
1439 (defun calc (&optional arg full-display interactive)
1440 "The Emacs Calculator. Full documentation is listed under \"calc-mode\"."
1441 (interactive "P\ni\np")
1442 (if arg
1443 (unless (eq arg 0)
1444 (require 'calc-ext)
1445 (if (= (prefix-numeric-value arg) -1)
1446 (calc-grab-region (region-beginning) (region-end) nil)
1447 (when (= (prefix-numeric-value arg) -2)
1448 (calc-keypad))))
1449 (when (get-buffer-window "*Calc Keypad*")
1450 (calc-keypad)
1451 (set-buffer (window-buffer (selected-window))))
1452 (if (eq major-mode 'calc-mode)
1453 (calc-quit)
1454 (let ((oldbuf (current-buffer)))
1455 (calc-create-buffer)
1456 (setq calc-was-keypad-mode nil)
1457 (if (or (eq full-display t)
1458 (and (null full-display) calc-full-mode))
1459 (switch-to-buffer (current-buffer) t)
1460 (if (get-buffer-window (current-buffer))
1461 (select-window (get-buffer-window (current-buffer)))
1462 (if calc-window-hook
1463 (run-hooks 'calc-window-hook)
1464 (let ((w (get-largest-window)))
1465 (if (and pop-up-windows
1466 (> (window-height w)
1467 (+ window-min-height calc-window-height 2)))
1468 (progn
1469 (setq w (split-window w
1470 (- (window-height w)
1471 calc-window-height 2)
1472 nil))
1473 (set-window-buffer w (current-buffer))
1474 (select-window w))
1475 (pop-to-buffer (current-buffer)))))))
1476 (with-current-buffer (calc-trail-buffer)
1477 (and calc-display-trail
1478 (= (window-width) (frame-width))
1479 (calc-trail-display 1 t)))
1480 (message "Welcome to the GNU Emacs Calculator! Press `?' or `h' for help, `q' to quit")
1481 (run-hooks 'calc-start-hook)
1482 (and (windowp full-display)
1483 (window-point full-display)
1484 (select-window full-display))
1485 (calc-check-defines)
1486 (when (and calc-said-hello interactive)
1487 (sit-for 2)
1488 (message ""))
1489 (setq calc-said-hello t)))))
1490
1491 ;;;###autoload
1492 (defun full-calc (&optional interactive)
1493 "Invoke the Calculator and give it a full-sized window."
1494 (interactive "p")
1495 (calc nil t interactive))
1496
1497 (defun calc-same-interface (arg)
1498 "Invoke the Calculator using the most recent interface (calc or calc-keypad)."
1499 (interactive "P")
1500 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1501 (> (recursion-depth) 0))
1502 (exit-recursive-edit)
1503 (if (eq major-mode 'calc-edit-mode)
1504 (calc-edit-finish arg)
1505 (if calc-was-keypad-mode
1506 (calc-keypad)
1507 (calc arg calc-full-mode t)))))
1508
1509 (defun calc-quit (&optional non-fatal interactive)
1510 "Quit the Calculator in an appropriate manner."
1511 (interactive "i\np")
1512 (and calc-standalone-flag (not non-fatal)
1513 (save-buffers-kill-emacs nil))
1514 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1515 (> (recursion-depth) 0))
1516 (exit-recursive-edit))
1517 (if (eq major-mode 'calc-edit-mode)
1518 (calc-edit-cancel)
1519 (if (and interactive
1520 calc-embedded-info
1521 (eq (current-buffer) (aref calc-embedded-info 0)))
1522 (calc-embedded nil)
1523 (unless (eq major-mode 'calc-mode)
1524 (calc-create-buffer))
1525 (run-hooks 'calc-end-hook)
1526 (if (integerp calc-undo-length)
1527 (cond
1528 ((= calc-undo-length 0)
1529 (setq calc-undo-list nil calc-redo-list nil))
1530 ((> calc-undo-length 0)
1531 (let ((tail (nthcdr (1- calc-undo-length) calc-undo-list)))
1532 (if tail (setcdr tail nil)))
1533 (setq calc-redo-list nil))))
1534 (mapc (function (lambda (v) (set-default v (symbol-value v))))
1535 calc-local-var-list)
1536 (let ((buf (current-buffer))
1537 (win (get-buffer-window (current-buffer)))
1538 (kbuf (get-buffer "*Calc Keypad*")))
1539 (delete-windows-on (calc-trail-buffer))
1540 ;; The next few lines will set `calc-window-height' so that the
1541 ;; next time Calc is called, the window will be the same size
1542 ;; as the current window.
1543 (if (and win
1544 (not (window-full-height-p win))
1545 (window-full-width-p win) ; avoid calc-keypad
1546 (not (get-buffer-window "*Calc Keypad*")))
1547 (setq calc-window-height (- (window-height win) 2)))
1548 (progn
1549 (delete-windows-on buf)
1550 (and kbuf (delete-windows-on kbuf)))
1551 (bury-buffer buf)
1552 (bury-buffer calc-trail-buffer)
1553 (and kbuf (bury-buffer kbuf))))))
1554
1555 ;;;###autoload
1556 (defun quick-calc ()
1557 "Do a quick calculation in the minibuffer without invoking full Calculator."
1558 (interactive)
1559 (calc-do-quick-calc))
1560
1561 ;;;###autoload
1562 (defun calc-eval (str &optional separator &rest args)
1563 "Do a quick calculation and return the result as a string.
1564 Return value will either be the formatted result in string form,
1565 or a list containing a character position and an error message in string form."
1566 (calc-do-calc-eval str separator args))
1567
1568 ;;;###autoload
1569 (defun calc-keypad (&optional interactive)
1570 "Invoke the Calculator in \"visual keypad\" mode.
1571 This is most useful in the X window system.
1572 In this mode, click on the Calc \"buttons\" using the left mouse button.
1573 Or, position the cursor manually and do M-x calc-keypad-press."
1574 (interactive "p")
1575 (require 'calc-ext)
1576 (calc-do-keypad calc-full-mode interactive))
1577
1578 ;;;###autoload
1579 (defun full-calc-keypad (&optional interactive)
1580 "Invoke the Calculator in full-screen \"visual keypad\" mode.
1581 See calc-keypad for details."
1582 (interactive "p")
1583 (require 'calc-ext)
1584 (calc-do-keypad t interactive))
1585
1586
1587 (defvar calc-aborted-prefix nil)
1588 (defvar calc-start-time nil)
1589 (defvar calc-command-flags nil)
1590 (defvar calc-final-point-line)
1591 (defvar calc-final-point-column)
1592 ;;; Note that modifications to this function may break calc-pass-errors.
1593 (defun calc-do (do-body &optional do-slow)
1594 (calc-check-defines)
1595 (let* ((calc-command-flags nil)
1596 (calc-start-time (and calc-timing (not calc-start-time)
1597 (require 'calc-ext)
1598 (current-time-string)))
1599 (gc-cons-threshold (max gc-cons-threshold
1600 (if calc-timing 2000000 100000)))
1601 calc-final-point-line calc-final-point-column)
1602 (setq calc-aborted-prefix "")
1603 (unwind-protect
1604 (condition-case err
1605 (save-excursion
1606 (if calc-embedded-info
1607 (calc-embedded-select-buffer)
1608 (calc-select-buffer))
1609 (and (eq calc-algebraic-mode 'total)
1610 (require 'calc-ext)
1611 (use-local-map calc-alg-map))
1612 (when (and do-slow calc-display-working-message)
1613 (message "Working...")
1614 (calc-set-command-flag 'clear-message))
1615 (funcall do-body)
1616 (setq calc-aborted-prefix nil)
1617 (when (memq 'renum-stack calc-command-flags)
1618 (calc-renumber-stack))
1619 (when (memq 'clear-message calc-command-flags)
1620 (message "")))
1621 (error
1622 (if (and (eq (car err) 'error)
1623 (stringp (nth 1 err))
1624 (string-match "max-specpdl-size\\|max-lisp-eval-depth"
1625 (nth 1 err)))
1626 (error "Computation got stuck or ran too long. Type `M' to increase the limit")
1627 (setq calc-aborted-prefix nil)
1628 (signal (car err) (cdr err)))))
1629 (when calc-aborted-prefix
1630 (calc-record "<Aborted>" calc-aborted-prefix))
1631 (and calc-start-time
1632 (let* ((calc-internal-prec 12)
1633 (calc-date-format nil)
1634 (end-time (current-time-string))
1635 (time (if (equal calc-start-time end-time)
1636 0
1637 (math-sub
1638 (calcFunc-unixtime (math-parse-date end-time) 0)
1639 (calcFunc-unixtime (math-parse-date calc-start-time)
1640 0)))))
1641 (if (math-lessp 1 time)
1642 (calc-record time "(t)"))))
1643 (or (memq 'no-align calc-command-flags)
1644 (eq major-mode 'calc-trail-mode)
1645 (calc-align-stack-window))
1646 (and (memq 'position-point calc-command-flags)
1647 (if (eq major-mode 'calc-mode)
1648 (progn
1649 (goto-char (point-min))
1650 (forward-line (1- calc-final-point-line))
1651 (move-to-column calc-final-point-column))
1652 (save-current-buffer
1653 (calc-select-buffer)
1654 (goto-char (point-min))
1655 (forward-line (1- calc-final-point-line))
1656 (move-to-column calc-final-point-column))))
1657 (unless (memq 'keep-flags calc-command-flags)
1658 (save-excursion
1659 (calc-select-buffer)
1660 (setq calc-inverse-flag nil
1661 calc-hyperbolic-flag nil
1662 calc-option-flag nil
1663 calc-keep-args-flag nil)))
1664 (when (memq 'do-edit calc-command-flags)
1665 (switch-to-buffer (get-buffer-create "*Calc Edit*")))
1666 (calc-set-mode-line)
1667 (when calc-embedded-info
1668 (calc-embedded-finish-command))))
1669 (identity nil)) ; allow a GC after timing is done
1670
1671
1672 (defun calc-set-command-flag (f)
1673 (unless (memq f calc-command-flags)
1674 (setq calc-command-flags (cons f calc-command-flags))))
1675
1676 (defun calc-select-buffer ()
1677 (or (eq major-mode 'calc-mode)
1678 (if calc-main-buffer
1679 (set-buffer calc-main-buffer)
1680 (let ((buf (get-buffer "*Calculator*")))
1681 (if buf
1682 (set-buffer buf)
1683 (error "Calculator buffer not available"))))))
1684
1685 (defun calc-cursor-stack-index (&optional index)
1686 (goto-char (point-max))
1687 (forward-line (- (calc-substack-height (or index 1)))))
1688
1689 (defun calc-stack-size ()
1690 (- (length calc-stack) calc-stack-top))
1691
1692 (defun calc-substack-height (n)
1693 (let ((sum 0)
1694 (stack calc-stack))
1695 (setq n (+ n calc-stack-top))
1696 (while (and (> n 0) stack)
1697 (setq sum (+ sum (nth 1 (car stack)))
1698 n (1- n)
1699 stack (cdr stack)))
1700 sum))
1701
1702 (defun calc-set-mode-line ()
1703 (save-excursion
1704 (calc-select-buffer)
1705 (let* ((fmt (car calc-float-format))
1706 (figs (nth 1 calc-float-format))
1707 (new-mode-string
1708 (format "Calc%s%s: %d %s %-14s"
1709 (if (and calc-embedded-info
1710 (eq (aref calc-embedded-info 1) (current-buffer)))
1711 "Embed" "")
1712 (if (and (> (length (buffer-name)) 12)
1713 (equal (substring (buffer-name) 0 12)
1714 "*Calculator*"))
1715 (substring (buffer-name) 12)
1716 "")
1717 calc-internal-prec
1718 (capitalize (symbol-name calc-angle-mode))
1719 (concat
1720
1721 ;; Input-related modes
1722 (if (eq calc-algebraic-mode 'total) "Alg* "
1723 (if calc-algebraic-mode "Alg "
1724 (if calc-incomplete-algebraic-mode "Alg[( " "")))
1725
1726 ;; Computational modes
1727 (if calc-symbolic-mode "Symb " "")
1728 (cond ((eq calc-matrix-mode 'matrix) "Matrix ")
1729 ((integerp calc-matrix-mode)
1730 (format "Matrix%d " calc-matrix-mode))
1731 ((eq calc-matrix-mode 'sqmatrix) "SqMatrix ")
1732 ((eq calc-matrix-mode 'scalar) "Scalar ")
1733 (t ""))
1734 (if (eq calc-complex-mode 'polar) "Polar " "")
1735 (if calc-prefer-frac "Frac " "")
1736 (cond ((null calc-infinite-mode) "")
1737 ((eq calc-infinite-mode 1) "+Inf ")
1738 (t "Inf "))
1739 (cond ((eq calc-simplify-mode 'none) "NoSimp ")
1740 ((eq calc-simplify-mode 'num) "NumSimp ")
1741 ((eq calc-simplify-mode 'binary)
1742 (format "BinSimp%d " calc-word-size))
1743 ((eq calc-simplify-mode 'alg) "AlgSimp ")
1744 ((eq calc-simplify-mode 'ext) "ExtSimp ")
1745 ((eq calc-simplify-mode 'units) "UnitSimp ")
1746 (t ""))
1747
1748 ;; Display modes
1749 (cond ((= calc-number-radix 10) "")
1750 ((= calc-number-radix 2) "Bin ")
1751 ((= calc-number-radix 8) "Oct ")
1752 ((= calc-number-radix 16) "Hex ")
1753 (t (format "Radix%d " calc-number-radix)))
1754 (if calc-twos-complement-mode "TwosComp " "")
1755 (if calc-leading-zeros "Zero " "")
1756 (cond ((null calc-language) "")
1757 ((get calc-language 'math-lang-name)
1758 (concat (get calc-language 'math-lang-name) " "))
1759 (t (concat
1760 (capitalize (symbol-name calc-language))
1761 " ")))
1762 (cond ((eq fmt 'float)
1763 (if (zerop figs) "" (format "Norm%d " figs)))
1764 ((eq fmt 'fix) (format "Fix%d " figs))
1765 ((eq fmt 'sci)
1766 (if (zerop figs) "Sci " (format "Sci%d " figs)))
1767 ((eq fmt 'eng)
1768 (if (zerop figs) "Eng " (format "Eng%d " figs))))
1769 (cond ((not calc-display-just)
1770 (if calc-display-origin
1771 (format "Left%d " calc-display-origin) ""))
1772 ((eq calc-display-just 'right)
1773 (if calc-display-origin
1774 (format "Right%d " calc-display-origin)
1775 "Right "))
1776 (t
1777 (if calc-display-origin
1778 (format "Center%d " calc-display-origin)
1779 "Center ")))
1780 (cond ((integerp calc-line-breaking)
1781 (format "Wid%d " calc-line-breaking))
1782 (calc-line-breaking "")
1783 (t "Wide "))
1784
1785 ;; Miscellaneous other modes/indicators
1786 (if calc-assoc-selections "" "Break ")
1787 (cond ((eq calc-mode-save-mode 'save) "Save ")
1788 ((not calc-embedded-info) "")
1789 ((eq calc-mode-save-mode 'local) "Local ")
1790 ((eq calc-mode-save-mode 'edit) "LocEdit ")
1791 ((eq calc-mode-save-mode 'perm) "LocPerm ")
1792 ((eq calc-mode-save-mode 'global) "Global ")
1793 (t ""))
1794 (if calc-auto-recompute "" "Manual ")
1795 (if (and (fboundp 'calc-gnuplot-alive)
1796 (calc-gnuplot-alive)) "Graph " "")
1797 (if (and calc-embedded-info
1798 (> (calc-stack-size) 0)
1799 (calc-top 1 'sel)) "Sel " "")
1800 (if calc-display-dirty "Dirty " "")
1801 (if calc-option-flag "Opt " "")
1802 (if calc-inverse-flag "Inv " "")
1803 (if calc-hyperbolic-flag "Hyp " "")
1804 (if calc-keep-args-flag "Keep " "")
1805 (if (/= calc-stack-top 1) "Narrow " "")
1806 (apply 'concat calc-other-modes)))))
1807 (if (equal new-mode-string mode-line-buffer-identification)
1808 nil
1809 (setq mode-line-buffer-identification new-mode-string)
1810 (set-buffer-modified-p (buffer-modified-p))
1811 (and calc-embedded-info (calc-embedded-mode-line-change))))))
1812
1813 (defun calc-align-stack-window ()
1814 (if (eq major-mode 'calc-mode)
1815 (progn
1816 (let ((win (get-buffer-window (current-buffer))))
1817 (if win
1818 (progn
1819 (calc-cursor-stack-index 0)
1820 (vertical-motion (- 2 (window-height win)))
1821 (set-window-start win (point)))))
1822 (calc-cursor-stack-index 0)
1823 (if (looking-at " *\\.$")
1824 (goto-char (1- (match-end 0)))))
1825 (save-excursion
1826 (calc-select-buffer)
1827 (calc-align-stack-window))))
1828
1829 (defun calc-check-stack (n)
1830 (if (> n (calc-stack-size))
1831 (error "Too few elements on stack"))
1832 (if (< n 0)
1833 (error "Invalid argument")))
1834
1835 (defun calc-push-list (vals &optional m sels)
1836 (while vals
1837 (if calc-executing-macro
1838 (calc-push-list-in-macro vals m sels)
1839 (save-excursion
1840 (calc-select-buffer)
1841 (let* ((val (car vals))
1842 (entry (list val 1 (car sels)))
1843 (mm (+ (or m 1) calc-stack-top)))
1844 (calc-cursor-stack-index (1- (or m 1)))
1845 (if (> mm 1)
1846 (setcdr (nthcdr (- mm 2) calc-stack)
1847 (cons entry (nthcdr (1- mm) calc-stack)))
1848 (setq calc-stack (cons entry calc-stack)))
1849 (let ((buffer-read-only nil))
1850 (insert (math-format-stack-value entry) "\n"))
1851 (calc-record-undo (list 'push mm))
1852 (calc-set-command-flag 'renum-stack))))
1853 (setq vals (cdr vals)
1854 sels (cdr sels))))
1855
1856 (defun calc-pop-push-list (n vals &optional m sels)
1857 (if (and calc-any-selections (null sels))
1858 (calc-replace-selections n vals m)
1859 (calc-pop-stack n m sels)
1860 (calc-push-list vals m sels)))
1861
1862 (defun calc-pop-push-record-list (n prefix vals &optional m sels)
1863 (or (and (consp vals)
1864 (or (integerp (car vals))
1865 (consp (car vals))))
1866 (and vals (setq vals (list vals)
1867 sels (and sels (list sels)))))
1868 (calc-check-stack (+ n (or m 1) -1))
1869 (if prefix
1870 (if (cdr vals)
1871 (calc-record-list vals prefix)
1872 (calc-record (car vals) prefix)))
1873 (calc-pop-push-list n vals m sels))
1874
1875 (defun calc-enter-result (n prefix vals &optional m)
1876 (setq calc-aborted-prefix prefix)
1877 (if (and (consp vals)
1878 (or (integerp (car vals))
1879 (consp (car vals))))
1880 (setq vals (mapcar 'calc-normalize vals))
1881 (setq vals (calc-normalize vals)))
1882 (or (and (consp vals)
1883 (or (integerp (car vals))
1884 (consp (car vals))))
1885 (setq vals (list vals)))
1886 (if (equal vals '((nil)))
1887 (setq vals nil))
1888 (calc-pop-push-record-list n prefix vals m)
1889 (calc-handle-whys))
1890
1891 (defun calc-normalize (val)
1892 (if (memq calc-simplify-mode '(nil none num))
1893 (math-normalize val)
1894 (require 'calc-ext)
1895 (calc-normalize-fancy val)))
1896
1897 (defun calc-handle-whys ()
1898 (if calc-next-why
1899 (calc-do-handle-whys)))
1900
1901
1902 (defun calc-pop-stack (&optional n m sel-ok) ; pop N objs at level M of stack.
1903 (or n (setq n 1))
1904 (or m (setq m 1))
1905 (or calc-keep-args-flag
1906 (let ((mm (+ m calc-stack-top)))
1907 (if (and calc-any-selections (not sel-ok)
1908 (calc-top-selected n m))
1909 (calc-sel-error))
1910 (if calc-executing-macro
1911 (calc-pop-stack-in-macro n mm)
1912 (calc-record-undo (list 'pop mm (calc-top-list n m 'full)))
1913 (save-excursion
1914 (calc-select-buffer)
1915 (let ((buffer-read-only nil))
1916 (if (> mm 1)
1917 (progn
1918 (calc-cursor-stack-index (1- m))
1919 (let ((bot (point)))
1920 (calc-cursor-stack-index (+ n m -1))
1921 (delete-region (point) bot))
1922 (setcdr (nthcdr (- mm 2) calc-stack)
1923 (nthcdr (+ n mm -1) calc-stack)))
1924 (calc-cursor-stack-index n)
1925 (setq calc-stack (nthcdr n calc-stack))
1926 (delete-region (point) (point-max))))
1927 (calc-set-command-flag 'renum-stack))))))
1928
1929 (defvar sel-mode)
1930 (defun calc-get-stack-element (x)
1931 (cond ((eq sel-mode 'entry)
1932 x)
1933 ((eq sel-mode 'sel)
1934 (nth 2 x))
1935 ((or (null (nth 2 x))
1936 (eq sel-mode 'full)
1937 (not calc-use-selections))
1938 (car x))
1939 (sel-mode
1940 (calc-sel-error))
1941 (t (nth 2 x))))
1942
1943 ;; Get the Nth element of the stack (N=1 is the top element).
1944 (defun calc-top (&optional n sel-mode)
1945 (or n (setq n 1))
1946 (calc-check-stack n)
1947 (calc-get-stack-element (nth (+ n calc-stack-top -1) calc-stack)))
1948
1949 (defun calc-top-n (&optional n sel-mode) ; in case precision has changed
1950 (math-check-complete (calc-normalize (calc-top n sel-mode))))
1951
1952 (defun calc-top-list (&optional n m sel-mode)
1953 (or n (setq n 1))
1954 (or m (setq m 1))
1955 (calc-check-stack (+ n m -1))
1956 (and (> n 0)
1957 (let ((top (copy-sequence (nthcdr (+ m calc-stack-top -1)
1958 calc-stack))))
1959 (setcdr (nthcdr (1- n) top) nil)
1960 (nreverse (mapcar 'calc-get-stack-element top)))))
1961
1962 (defun calc-top-list-n (&optional n m sel-mode)
1963 (mapcar 'math-check-complete
1964 (mapcar 'calc-normalize (calc-top-list n m sel-mode))))
1965
1966
1967 (defun calc-renumber-stack ()
1968 (if calc-line-numbering
1969 (save-excursion
1970 (calc-cursor-stack-index 0)
1971 (let ((lnum 1)
1972 (buffer-read-only nil)
1973 (stack (nthcdr calc-stack-top calc-stack)))
1974 (if (re-search-forward "^[0-9]+[:*]" nil t)
1975 (progn
1976 (beginning-of-line)
1977 (while (re-search-forward "^[0-9]+[:*]" nil t)
1978 (let ((buffer-read-only nil))
1979 (beginning-of-line)
1980 (delete-char 4)
1981 (insert " ")))
1982 (calc-cursor-stack-index 0)))
1983 (while (re-search-backward "^[0-9]+[:*]" nil t)
1984 (delete-char 4)
1985 (if (> lnum 999)
1986 (insert (format "%03d%s" (% lnum 1000)
1987 (if (and (nth 2 (car stack))
1988 calc-use-selections) "*" ":")))
1989 (let ((prefix (int-to-string lnum)))
1990 (insert prefix (if (and (nth 2 (car stack))
1991 calc-use-selections) "*" ":")
1992 (make-string (- 3 (length prefix)) 32))))
1993 (beginning-of-line)
1994 (setq lnum (1+ lnum)
1995 stack (cdr stack))))))
1996 (and calc-embedded-info (calc-embedded-stack-change)))
1997
1998 (defvar calc-any-evaltos nil)
1999 (defun calc-refresh (&optional align)
2000 (interactive)
2001 (and (eq major-mode 'calc-mode)
2002 (not calc-executing-macro)
2003 (let* ((buffer-read-only nil)
2004 (save-point (point))
2005 (save-mark (condition-case err (mark) (error nil)))
2006 (save-aligned (looking-at "\\.$"))
2007 (thing calc-stack)
2008 (calc-any-evaltos nil))
2009 (setq calc-any-selections nil)
2010 (erase-buffer)
2011 (when calc-show-banner
2012 (insert (propertize "--- Emacs Calculator Mode ---\n"
2013 'face 'italic)))
2014 (while thing
2015 (goto-char (point-min))
2016 (when calc-show-banner
2017 (forward-line 1))
2018 (insert (math-format-stack-value (car thing)) "\n")
2019 (setq thing (cdr thing)))
2020 (calc-renumber-stack)
2021 (if calc-display-dirty
2022 (calc-wrapper (setq calc-display-dirty nil)))
2023 (and calc-any-evaltos calc-auto-recompute
2024 (calc-wrapper (calc-refresh-evaltos)))
2025 (if (or align save-aligned)
2026 (calc-align-stack-window)
2027 (goto-char save-point))
2028 (if save-mark (set-mark save-mark))))
2029 (and calc-embedded-info (not (eq major-mode 'calc-mode))
2030 (with-current-buffer (aref calc-embedded-info 1)
2031 (calc-refresh align)))
2032 (setq calc-refresh-count (1+ calc-refresh-count)))
2033
2034 ;;;; The Calc Trail buffer.
2035
2036 (defun calc-check-trail-aligned ()
2037 (save-excursion
2038 (let ((win (get-buffer-window (current-buffer))))
2039 (and win
2040 (pos-visible-in-window-p (1- (point-max)) win)))))
2041
2042 (defun calc-trail-buffer ()
2043 (and (or (null calc-trail-buffer)
2044 (null (buffer-name calc-trail-buffer)))
2045 (save-excursion
2046 (setq calc-trail-buffer (get-buffer-create "*Calc Trail*"))
2047 (let ((buf (or (and (not (eq major-mode 'calc-mode))
2048 (get-buffer "*Calculator*"))
2049 (current-buffer))))
2050 (set-buffer calc-trail-buffer)
2051 (or (eq major-mode 'calc-trail-mode)
2052 (calc-trail-mode buf)))))
2053 (or (and calc-trail-pointer
2054 (eq (marker-buffer calc-trail-pointer) calc-trail-buffer))
2055 (with-current-buffer calc-trail-buffer
2056 (goto-char (point-min))
2057 (forward-line 1)
2058 (setq calc-trail-pointer (point-marker))))
2059 calc-trail-buffer)
2060
2061 (defun calc-record (val &optional prefix)
2062 (setq calc-aborted-prefix nil)
2063 (or calc-executing-macro
2064 (let* ((mainbuf (current-buffer))
2065 (buf (calc-trail-buffer))
2066 (calc-display-raw nil)
2067 (calc-can-abbrev-vectors t)
2068 (fval (if val
2069 (if (stringp val)
2070 val
2071 (math-showing-full-precision
2072 (math-format-flat-expr val 0)))
2073 "")))
2074 (with-current-buffer buf
2075 (let ((aligned (calc-check-trail-aligned))
2076 (buffer-read-only nil))
2077 (goto-char (point-max))
2078 (cond ((null prefix) (insert " "))
2079 ((and (> (length prefix) 4)
2080 (string-match " " prefix 4))
2081 (insert (substring prefix 0 4) " "))
2082 (t (insert (format "%4s " prefix))))
2083 (insert fval "\n")
2084 (let ((win (get-buffer-window buf)))
2085 (if (and aligned win (not (memq 'hold-trail calc-command-flags)))
2086 (calc-trail-here))
2087 (goto-char (1- (point-max))))))))
2088 val)
2089
2090
2091 (defun calc-trail-display (flag &optional no-refresh interactive)
2092 (interactive "P\ni\np")
2093 (let ((win (get-buffer-window (calc-trail-buffer))))
2094 (if (setq calc-display-trail
2095 (not (if flag (memq flag '(nil 0)) win)))
2096 (if (null win)
2097 (progn
2098 (if calc-trail-window-hook
2099 (run-hooks 'calc-trail-window-hook)
2100 (let ((w (split-window nil (/ (* (window-width) 2) 3) t)))
2101 (set-window-buffer w calc-trail-buffer)))
2102 (calc-wrapper
2103 (setq overlay-arrow-string calc-trail-overlay
2104 overlay-arrow-position calc-trail-pointer)
2105 (or no-refresh
2106 (if interactive
2107 (calc-do-refresh)
2108 (calc-refresh))))))
2109 (if win
2110 (progn
2111 (delete-window win)
2112 (calc-wrapper
2113 (or no-refresh
2114 (if interactive
2115 (calc-do-refresh)
2116 (calc-refresh))))))))
2117 calc-trail-buffer)
2118
2119 (defun calc-trail-here ()
2120 (interactive)
2121 (if (eq major-mode 'calc-trail-mode)
2122 (progn
2123 (beginning-of-line)
2124 (if (bobp)
2125 (forward-line 1)
2126 (if (eobp)
2127 (forward-line -1)))
2128 (if (or (bobp) (eobp))
2129 (setq overlay-arrow-position nil) ; trail is empty
2130 (set-marker calc-trail-pointer (point) (current-buffer))
2131 (setq calc-trail-overlay (concat (buffer-substring (point)
2132 (+ (point) 4))
2133 ">")
2134 overlay-arrow-string calc-trail-overlay
2135 overlay-arrow-position calc-trail-pointer)
2136 (forward-char 4)
2137 (let ((win (get-buffer-window (current-buffer))))
2138 (if win
2139 (save-excursion
2140 (forward-line (/ (window-height win) 2))
2141 (forward-line (- 1 (window-height win)))
2142 (set-window-start win (point))
2143 (set-window-point win (+ calc-trail-pointer 4))
2144 (set-buffer calc-main-buffer)
2145 (setq overlay-arrow-string calc-trail-overlay
2146 overlay-arrow-position calc-trail-pointer))))))
2147 (error "Not in Calc Trail buffer")))
2148
2149
2150
2151
2152 ;;;; The Undo list.
2153
2154 (defun calc-record-undo (rec)
2155 (or calc-executing-macro
2156 (if (memq 'undo calc-command-flags)
2157 (setq calc-undo-list (cons (cons rec (car calc-undo-list))
2158 (cdr calc-undo-list)))
2159 (setq calc-undo-list (cons (list rec) calc-undo-list)
2160 calc-redo-list nil)
2161 (calc-set-command-flag 'undo))))
2162
2163
2164
2165
2166 ;;; Arithmetic commands.
2167
2168 (defun calc-binary-op (name func arg &optional ident unary func2)
2169 (setq calc-aborted-prefix name)
2170 (if (null arg)
2171 (calc-enter-result 2 name (cons (or func2 func)
2172 (mapcar 'math-check-complete
2173 (calc-top-list 2))))
2174 (require 'calc-ext)
2175 (calc-binary-op-fancy name func arg ident unary)))
2176
2177 (defun calc-unary-op (name func arg &optional func2)
2178 (setq calc-aborted-prefix name)
2179 (if (null arg)
2180 (calc-enter-result 1 name (list (or func2 func)
2181 (math-check-complete (calc-top 1))))
2182 (require 'calc-ext)
2183 (calc-unary-op-fancy name func arg)))
2184
2185
2186 (defun calc-plus (arg)
2187 (interactive "P")
2188 (calc-slow-wrapper
2189 (calc-binary-op "+" 'calcFunc-add arg 0 nil '+)))
2190
2191 (defun calc-minus (arg)
2192 (interactive "P")
2193 (calc-slow-wrapper
2194 (calc-binary-op "-" 'calcFunc-sub arg 0 'neg '-)))
2195
2196 (defun calc-times (arg)
2197 (interactive "P")
2198 (calc-slow-wrapper
2199 (calc-binary-op "*" 'calcFunc-mul arg 1 nil '*)))
2200
2201 (defun calc-divide (arg)
2202 (interactive "P")
2203 (calc-slow-wrapper
2204 (calc-binary-op "/" 'calcFunc-div arg 0 'calcFunc-inv '/)))
2205
2206 (defun calc-left-divide (arg)
2207 (interactive "P")
2208 (calc-slow-wrapper
2209 (calc-binary-op "ldiv" 'calcFunc-ldiv arg 0 nil nil)))
2210
2211 (defun calc-change-sign (arg)
2212 (interactive "P")
2213 (calc-wrapper
2214 (calc-unary-op "chs" 'neg arg)))
2215
2216
2217
2218 ;;; Stack management commands.
2219
2220 (defun calc-enter (n)
2221 (interactive "p")
2222 (calc-wrapper
2223 (cond ((< n 0)
2224 (calc-push-list (calc-top-list 1 (- n))))
2225 ((= n 0)
2226 (calc-push-list (calc-top-list (calc-stack-size))))
2227 (t
2228 (calc-push-list (calc-top-list n))))))
2229
2230
2231 (defun calc-pop (n)
2232 (interactive "P")
2233 (calc-wrapper
2234 (let* ((nn (prefix-numeric-value n))
2235 (top (and (null n) (calc-top 1))))
2236 (cond ((and (null n)
2237 (eq (car-safe top) 'incomplete)
2238 (> (length top) (if (eq (nth 1 top) 'intv) 3 2)))
2239 (calc-pop-push-list 1 (let ((tt (copy-sequence top)))
2240 (setcdr (nthcdr (- (length tt) 2) tt) nil)
2241 (list tt))))
2242 ((< nn 0)
2243 (if (and calc-any-selections
2244 (calc-top-selected 1 (- nn)))
2245 (calc-delete-selection (- nn))
2246 (calc-pop-stack 1 (- nn) t)))
2247 ((= nn 0)
2248 (calc-pop-stack (calc-stack-size) 1 t))
2249 (t
2250 (if (and calc-any-selections
2251 (= nn 1)
2252 (calc-top-selected 1 1))
2253 (calc-delete-selection 1)
2254 (calc-pop-stack nn)))))))
2255
2256
2257
2258
2259 ;;;; Reading a number using the minibuffer.
2260 (defvar calc-buffer)
2261 (defvar calc-prev-char)
2262 (defvar calc-prev-prev-char)
2263 (defvar calc-digit-value)
2264 (defun calcDigit-start ()
2265 (interactive)
2266 (calc-wrapper
2267 (if (or calc-algebraic-mode
2268 (and (> calc-number-radix 14) (eq last-command-event ?e)))
2269 (calc-alg-digit-entry)
2270 (calc-unread-command)
2271 (setq calc-aborted-prefix nil)
2272 (let* ((calc-digit-value nil)
2273 (calc-prev-char nil)
2274 (calc-prev-prev-char nil)
2275 (calc-buffer (current-buffer))
2276 (buf (if (featurep 'xemacs)
2277 (catch 'calc-foo
2278 (catch 'execute-kbd-macro
2279 (throw 'calc-foo
2280 (read-from-minibuffer
2281 "Calc: " "" calc-digit-map)))
2282 (error "XEmacs requires RET after %s"
2283 "digit entry in kbd macro"))
2284 (let ((old-esc (lookup-key global-map "\e")))
2285 (unwind-protect
2286 (progn
2287 (define-key global-map "\e" nil)
2288 (read-from-minibuffer "Calc: " "" calc-digit-map))
2289 (define-key global-map "\e" old-esc))))))
2290 (or calc-digit-value (setq calc-digit-value (math-read-number buf)))
2291 (if (stringp calc-digit-value)
2292 (calc-alg-entry calc-digit-value)
2293 (if calc-digit-value
2294 (calc-push-list (list (calc-record (calc-normalize
2295 calc-digit-value))))))
2296 (if (eq calc-prev-char 'dots)
2297 (progn
2298 (require 'calc-ext)
2299 (calc-dots)))))))
2300
2301 (defsubst calc-minibuffer-size ()
2302 (- (point-max) (minibuffer-prompt-end)))
2303
2304 (defun calcDigit-nondigit ()
2305 (interactive)
2306 ;; Exercise for the reader: Figure out why this is a good precaution!
2307 (or (boundp 'calc-buffer)
2308 (use-local-map minibuffer-local-map))
2309 (let ((str (minibuffer-contents)))
2310 (setq calc-digit-value (with-current-buffer calc-buffer
2311 (math-read-number str))))
2312 (if (and (null calc-digit-value) (> (calc-minibuffer-size) 0))
2313 (progn
2314 (beep)
2315 (calc-temp-minibuffer-message " [Bad format]"))
2316 (or (memq last-command-event '(32 13))
2317 (progn (setq prefix-arg current-prefix-arg)
2318 (calc-unread-command (if (and (eq last-command-event 27)
2319 (>= last-input-event 128))
2320 last-input-event
2321 nil))))
2322 (exit-minibuffer)))
2323
2324
2325 (defun calc-minibuffer-contains (rex)
2326 (save-excursion
2327 (goto-char (minibuffer-prompt-end))
2328 (looking-at rex)))
2329
2330 (defun calcDigit-key ()
2331 (interactive)
2332 (goto-char (point-max))
2333 (if (or (and (memq last-command-event '(?+ ?-))
2334 (> (buffer-size) 0)
2335 (/= (preceding-char) ?e))
2336 (and (memq last-command-event '(?m ?s))
2337 (not (calc-minibuffer-contains "[-+]?[0-9]+\\.?0*[@oh].*"))
2338 (not (calc-minibuffer-contains "[-+]?\\(1[1-9]\\|[2-9][0-9]\\)#.*"))))
2339 (calcDigit-nondigit)
2340 (if (calc-minibuffer-contains "\\([-+]?\\|.* \\)\\'")
2341 (cond ((memq last-command-event '(?. ?@)) (insert "0"))
2342 ((and (memq last-command-event '(?o ?h ?m))
2343 (not (calc-minibuffer-contains ".*#.*"))) (insert "0"))
2344 ((memq last-command-event '(?: ?e)) (insert "1"))
2345 ((eq last-command-event ?#)
2346 (insert (int-to-string calc-number-radix)))))
2347 (if (and (calc-minibuffer-contains "\\([-+]?[0-9]+#\\|[^:]*:\\)\\'")
2348 (eq last-command-event ?:))
2349 (insert "1"))
2350 (if (and (calc-minibuffer-contains "[-+]?[0-9]+#\\'")
2351 (eq last-command-event ?.))
2352 (insert "0"))
2353 (if (and (calc-minibuffer-contains "[-+]?0*\\([2-9]\\|1[0-4]\\)#\\'")
2354 (eq last-command-event ?e))
2355 (insert "1"))
2356 (if (or (and (memq last-command-event '(?h ?o ?m ?s ?p))
2357 (calc-minibuffer-contains ".*#.*"))
2358 (and (eq last-command-event ?e)
2359 (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2360 (and (eq last-command-event ?n)
2361 (calc-minibuffer-contains "[-+]?\\(2[4-9]\\|[3-9][0-9]\\)#.*")))
2362 (setq last-command-event (upcase last-command-event)))
2363 (cond
2364 ((memq last-command-event '(?_ ?n))
2365 (goto-char (minibuffer-prompt-end))
2366 (if (and (search-forward " +/- " nil t)
2367 (not (search-forward "e" nil t)))
2368 (beep)
2369 (and (not (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2370 (search-forward "e" nil t))
2371 (if (looking-at "+")
2372 (delete-char 1))
2373 (if (looking-at "-")
2374 (delete-char 1)
2375 (insert "-")))
2376 (goto-char (point-max)))
2377 ((eq last-command-event ?p)
2378 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2379 (calc-minibuffer-contains ".*mod.*")
2380 (calc-minibuffer-contains ".*#.*")
2381 (calc-minibuffer-contains ".*[-+e:]\\'"))
2382 (beep)
2383 (if (not (calc-minibuffer-contains ".* \\'"))
2384 (insert " "))
2385 (insert "+/- ")))
2386 ((and (eq last-command-event ?M)
2387 (not (calc-minibuffer-contains
2388 "[-+]?\\(2[3-9]\\|[3-9][0-9]\\)#.*")))
2389 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2390 (calc-minibuffer-contains ".*mod *[^ ]+")
2391 (calc-minibuffer-contains ".*[-+e:]\\'"))
2392 (beep)
2393 (if (calc-minibuffer-contains ".*mod \\'")
2394 (if calc-previous-modulo
2395 (insert (math-format-flat-expr calc-previous-modulo 0))
2396 (beep))
2397 (if (not (calc-minibuffer-contains ".* \\'"))
2398 (insert " "))
2399 (insert "mod "))))
2400 (t
2401 (insert (char-to-string last-command-event))
2402 (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]*\\)?\\)?\\'")
2403 (let ((radix (string-to-number
2404 (buffer-substring
2405 (match-beginning 2) (match-end 2)))))
2406 (and (>= radix 2)
2407 (<= radix 36)
2408 (or (memq last-command-event '(?# ?: ?. ?e ?+ ?-))
2409 (let ((dig (math-read-radix-digit
2410 (upcase last-command-event))))
2411 (and dig
2412 (< dig radix)))))))
2413 (calc-minibuffer-contains
2414 "[-+]?\\(.*\\+/- *\\|.*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]?\\'"))
2415 (if (and (memq last-command-event '(?@ ?o ?h ?\' ?m))
2416 (string-match " " calc-hms-format))
2417 (insert " "))
2418 (if (and (eq this-command last-command)
2419 (eq last-command-event ?.))
2420 (progn
2421 (require 'calc-ext)
2422 (calc-digit-dots))
2423 (delete-char -1)
2424 (beep)
2425 (calc-temp-minibuffer-message " [Bad format]"))))))
2426 (setq calc-prev-prev-char calc-prev-char
2427 calc-prev-char last-command-event))
2428
2429
2430 (defun calcDigit-backspace ()
2431 (interactive)
2432 (goto-char (point-max))
2433 (cond ((calc-minibuffer-contains ".* \\+/- \\'")
2434 (backward-delete-char 5))
2435 ((calc-minibuffer-contains ".* mod \\'")
2436 (backward-delete-char 5))
2437 ((calc-minibuffer-contains ".* \\'")
2438 (backward-delete-char 2))
2439 ((eq last-command 'calcDigit-start)
2440 (erase-buffer))
2441 (t (backward-delete-char 1)))
2442 (if (= (calc-minibuffer-size) 0)
2443 (progn
2444 (setq last-command-event 13)
2445 (calcDigit-nondigit))))
2446
2447
2448
2449
2450 (defconst math-bignum-digit-length
2451 (truncate (/ (log10 (/ most-positive-fixnum 2)) 2))
2452 "The length of a \"digit\" in Calc bignums.
2453 If a big integer is of the form (bigpos N0 N1 ...), this is the
2454 length of the allowable Emacs integers N0, N1,...
2455 The value of 2*10^(2*MATH-BIGNUM-DIGIT-LENGTH) must be less than the
2456 largest Emacs integer.")
2457
2458 (defconst math-bignum-digit-size
2459 (expt 10 math-bignum-digit-length)
2460 "An upper bound for the size of the \"digit\"s in Calc bignums.")
2461
2462 (defconst math-small-integer-size
2463 (expt math-bignum-digit-size 2)
2464 "An upper bound for the size of \"small integer\"s in Calc.")
2465
2466
2467 ;;;; Arithmetic routines.
2468 ;;
2469 ;; An object as manipulated by one of these routines may take any of the
2470 ;; following forms:
2471 ;;
2472 ;; integer An integer. For normalized numbers, this format
2473 ;; is used only for
2474 ;; negative math-small-integer-size + 1 to
2475 ;; math-small-integer-size - 1
2476 ;;
2477 ;; (bigpos N0 N1 N2 ...) A big positive integer,
2478 ;; N0 + N1*math-bignum-digit-size
2479 ;; + N2*(math-bignum-digit-size)^2 ...
2480 ;; (bigneg N0 N1 N2 ...) A big negative integer,
2481 ;; - N0 - N1*math-bignum-digit-size ...
2482 ;; Each digit N is in the range
2483 ;; 0 ... math-bignum-digit-size -1.
2484 ;; Normalized, always at least three N present,
2485 ;; and the most significant N is nonzero.
2486 ;;
2487 ;; (frac NUM DEN) A fraction. NUM and DEN are small or big integers.
2488 ;; Normalized, DEN > 1.
2489 ;;
2490 ;; (float NUM EXP) A floating-point number, NUM * 10^EXP;
2491 ;; NUM is a small or big integer, EXP is a small int.
2492 ;; Normalized, NUM is not a multiple of 10, and
2493 ;; abs(NUM) < 10^calc-internal-prec.
2494 ;; Normalized zero is stored as (float 0 0).
2495 ;;
2496 ;; (cplx REAL IMAG) A complex number; REAL and IMAG are any of above.
2497 ;; Normalized, IMAG is nonzero.
2498 ;;
2499 ;; (polar R THETA) Polar complex number. Normalized, R > 0 and THETA
2500 ;; is neither zero nor 180 degrees (pi radians).
2501 ;;
2502 ;; (vec A B C ...) Vector of objects A, B, C, ... A matrix is a
2503 ;; vector of vectors.
2504 ;;
2505 ;; (hms H M S) Angle in hours-minutes-seconds form. All three
2506 ;; components have the same sign; H and M must be
2507 ;; numerically integers; M and S are expected to
2508 ;; lie in the range [0,60).
2509 ;;
2510 ;; (date N) A date or date/time object. N is an integer to
2511 ;; store a date only, or a fraction or float to
2512 ;; store a date and time.
2513 ;;
2514 ;; (sdev X SIGMA) Error form, X +/- SIGMA. When normalized,
2515 ;; SIGMA > 0. X is any complex number and SIGMA
2516 ;; is real numbers; or these may be symbolic
2517 ;; expressions where SIGMA is assumed real.
2518 ;;
2519 ;; (intv MASK LO HI) Interval form. MASK is 0=(), 1=(], 2=[), or 3=[].
2520 ;; LO and HI are any real numbers, or symbolic
2521 ;; expressions which are assumed real, and LO < HI.
2522 ;; For [LO..HI], if LO = HI normalization produces LO,
2523 ;; and if LO > HI normalization produces [LO..LO).
2524 ;; For other intervals, if LO > HI normalization
2525 ;; sets HI equal to LO.
2526 ;;
2527 ;; (mod N M) Number modulo M. When normalized, 0 <= N < M.
2528 ;; N and M are real numbers.
2529 ;;
2530 ;; (var V S) Symbolic variable. V is a Lisp symbol which
2531 ;; represents the variable's visible name. S is
2532 ;; the symbol which actually stores the variable's
2533 ;; value: (var pi var-pi).
2534 ;;
2535 ;; In general, combining rational numbers in a calculation always produces
2536 ;; a rational result, but if either argument is a float, result is a float.
2537
2538 ;; In the following comments, [x y z] means result is x, args must be y, z,
2539 ;; respectively, where the code letters are:
2540 ;;
2541 ;; O Normalized object (vector or number)
2542 ;; V Normalized vector
2543 ;; N Normalized number of any type
2544 ;; N Normalized complex number
2545 ;; R Normalized real number (float or rational)
2546 ;; F Normalized floating-point number
2547 ;; T Normalized rational number
2548 ;; I Normalized integer
2549 ;; B Normalized big integer
2550 ;; S Normalized small integer
2551 ;; D Digit (small integer, 0..999)
2552 ;; L Normalized bignum digit list (without "bigpos" or "bigneg" symbol)
2553 ;; or normalized vector element list (without "vec")
2554 ;; P Predicate (truth value)
2555 ;; X Any Lisp object
2556 ;; Z "nil"
2557 ;;
2558 ;; Lower-case letters signify possibly un-normalized values.
2559 ;; "L.D" means a cons of an L and a D.
2560 ;; [N N; n n] means result will be normalized if argument is.
2561 ;; Also, [Public] marks routines intended to be called from outside.
2562 ;; [This notation has been neglected in many recent routines.]
2563
2564 (defvar math-eval-rules-cache)
2565 (defvar math-eval-rules-cache-other)
2566 ;;; Reduce an object to canonical (normalized) form. [O o; Z Z] [Public]
2567
2568 (defvar math-normalize-a)
2569 (defun math-normalize (math-normalize-a)
2570 (cond
2571 ((not (consp math-normalize-a))
2572 (if (integerp math-normalize-a)
2573 (if (or (>= math-normalize-a math-small-integer-size)
2574 (<= math-normalize-a (- math-small-integer-size)))
2575 (math-bignum math-normalize-a)
2576 math-normalize-a)
2577 math-normalize-a))
2578 ((eq (car math-normalize-a) 'bigpos)
2579 (if (eq (nth (1- (length math-normalize-a)) math-normalize-a) 0)
2580 (let* ((last (setq math-normalize-a
2581 (copy-sequence math-normalize-a))) (digs math-normalize-a))
2582 (while (setq digs (cdr digs))
2583 (or (eq (car digs) 0) (setq last digs)))
2584 (setcdr last nil)))
2585 (if (cdr (cdr (cdr math-normalize-a)))
2586 math-normalize-a
2587 (cond
2588 ((cdr (cdr math-normalize-a)) (+ (nth 1 math-normalize-a)
2589 (* (nth 2 math-normalize-a)
2590 math-bignum-digit-size)))
2591 ((cdr math-normalize-a) (nth 1 math-normalize-a))
2592 (t 0))))
2593 ((eq (car math-normalize-a) 'bigneg)
2594 (if (eq (nth (1- (length math-normalize-a)) math-normalize-a) 0)
2595 (let* ((last (setq math-normalize-a (copy-sequence math-normalize-a)))
2596 (digs math-normalize-a))
2597 (while (setq digs (cdr digs))
2598 (or (eq (car digs) 0) (setq last digs)))
2599 (setcdr last nil)))
2600 (if (cdr (cdr (cdr math-normalize-a)))
2601 math-normalize-a
2602 (cond
2603 ((cdr (cdr math-normalize-a)) (- (+ (nth 1 math-normalize-a)
2604 (* (nth 2 math-normalize-a)
2605 math-bignum-digit-size))))
2606 ((cdr math-normalize-a) (- (nth 1 math-normalize-a)))
2607 (t 0))))
2608 ((eq (car math-normalize-a) 'float)
2609 (math-make-float (math-normalize (nth 1 math-normalize-a))
2610 (nth 2 math-normalize-a)))
2611 ((or (memq (car math-normalize-a)
2612 '(frac cplx polar hms date mod sdev intv vec var quote
2613 special-const calcFunc-if calcFunc-lambda
2614 calcFunc-quote calcFunc-condition
2615 calcFunc-evalto))
2616 (integerp (car math-normalize-a))
2617 (and (consp (car math-normalize-a))
2618 (not (eq (car (car math-normalize-a)) 'lambda))))
2619 (require 'calc-ext)
2620 (math-normalize-fancy math-normalize-a))
2621 (t
2622 (or (and calc-simplify-mode
2623 (require 'calc-ext)
2624 (math-normalize-nonstandard))
2625 (let ((args (mapcar 'math-normalize (cdr math-normalize-a))))
2626 (or (condition-case err
2627 (let ((func
2628 (assq (car math-normalize-a) '( ( + . math-add )
2629 ( - . math-sub )
2630 ( * . math-mul )
2631 ( / . math-div )
2632 ( % . math-mod )
2633 ( ^ . math-pow )
2634 ( neg . math-neg )
2635 ( | . math-concat ) ))))
2636 (or (and var-EvalRules
2637 (progn
2638 (or (eq var-EvalRules math-eval-rules-cache-tag)
2639 (progn
2640 (require 'calc-ext)
2641 (math-recompile-eval-rules)))
2642 (and (or math-eval-rules-cache-other
2643 (assq (car math-normalize-a)
2644 math-eval-rules-cache))
2645 (math-apply-rewrites
2646 (cons (car math-normalize-a) args)
2647 (cdr math-eval-rules-cache)
2648 nil math-eval-rules-cache))))
2649 (if func
2650 (apply (cdr func) args)
2651 (and (or (consp (car math-normalize-a))
2652 (fboundp (car math-normalize-a))
2653 (and (not (featurep 'calc-ext))
2654 (require 'calc-ext)
2655 (fboundp (car math-normalize-a))))
2656 (apply (car math-normalize-a) args)))))
2657 (wrong-number-of-arguments
2658 (calc-record-why "*Wrong number of arguments"
2659 (cons (car math-normalize-a) args))
2660 nil)
2661 (wrong-type-argument
2662 (or calc-next-why
2663 (calc-record-why "Wrong type of argument"
2664 (cons (car math-normalize-a) args)))
2665 nil)
2666 (args-out-of-range
2667 (calc-record-why "*Argument out of range"
2668 (cons (car math-normalize-a) args))
2669 nil)
2670 (inexact-result
2671 (calc-record-why "No exact representation for result"
2672 (cons (car math-normalize-a) args))
2673 nil)
2674 (math-overflow
2675 (calc-record-why "*Floating-point overflow occurred"
2676 (cons (car math-normalize-a) args))
2677 nil)
2678 (math-underflow
2679 (calc-record-why "*Floating-point underflow occurred"
2680 (cons (car math-normalize-a) args))
2681 nil)
2682 (void-variable
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