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