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