Merge from emacs--rel--22
[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 "Non-nil if Calc was last invoked in keypad mode.")
743
744 (defcalcmodevar calc-full-mode nil
745 "Non-nil if Calc was last invoked in full-screen mode.")
746
747 (defcalcmodevar calc-user-parse-tables nil
748 "Alist of languages with user-defined parse rules.")
749
750 (defcalcmodevar calc-gnuplot-default-device "default"
751 "The default device name for GNUPLOT plotting.")
752
753 (defcalcmodevar calc-gnuplot-default-output "STDOUT"
754 "The default output file for GNUPLOT plotting.")
755
756 (defcalcmodevar calc-gnuplot-print-device "postscript"
757 "The default device name for GNUPLOT printing.")
758
759 (defcalcmodevar calc-gnuplot-print-output "auto"
760 "The default output for GNUPLOT printing.")
761
762 (defcalcmodevar calc-gnuplot-geometry nil
763 "The default geometry for the GNUPLOT window.")
764
765 (defcalcmodevar calc-graph-default-resolution 15
766 "The default number of data points when plotting curves.")
767
768 (defcalcmodevar calc-graph-default-resolution-3d 5
769 "The default number of x- and y- data points when plotting surfaces.")
770
771 (defcalcmodevar calc-invocation-macro nil
772 "A user defined macro for starting Calc.
773 Used by `calc-user-invocation'.")
774
775 (defcalcmodevar calc-show-banner t
776 "*If non-nil, show a friendly greeting above the stack.")
777
778 (defconst calc-local-var-list '(calc-stack
779 calc-stack-top
780 calc-undo-list
781 calc-redo-list
782 calc-always-load-extensions
783 calc-mode-save-mode
784 calc-display-raw
785 calc-line-numbering
786 calc-line-breaking
787 calc-display-just
788 calc-display-origin
789 calc-left-label
790 calc-right-label
791 calc-auto-why
792 calc-algebraic-mode
793 calc-incomplete-algebraic-mode
794 calc-symbolic-mode
795 calc-matrix-mode
796 calc-inverse-flag
797 calc-hyperbolic-flag
798 calc-keep-args-flag
799 calc-angle-mode
800 calc-number-radix
801 calc-leading-zeros
802 calc-group-digits
803 calc-group-char
804 calc-point-char
805 calc-frac-format
806 calc-prefer-frac
807 calc-hms-format
808 calc-date-format
809 calc-standard-date-formats
810 calc-float-format
811 calc-full-float-format
812 calc-complex-format
813 calc-matrix-just
814 calc-full-vectors
815 calc-full-trail-vectors
816 calc-break-vectors
817 calc-vector-commas
818 calc-vector-brackets
819 calc-matrix-brackets
820 calc-complex-mode
821 calc-infinite-mode
822 calc-display-strings
823 calc-simplify-mode
824 calc-auto-recompute
825 calc-autorange-units
826 calc-show-plain
827 calc-show-selections
828 calc-use-selections
829 calc-assoc-selections
830 calc-word-size
831 calc-internal-prec))
832
833 (defvar calc-mode-hook nil
834 "Hook run when entering calc-mode.")
835
836 (defvar calc-trail-mode-hook nil
837 "Hook run when entering calc-trail-mode.")
838
839 (defvar calc-start-hook nil
840 "Hook run when calc is started.")
841
842 (defvar calc-end-hook nil
843 "Hook run when calc is quit.")
844
845 (defvar calc-load-hook nil
846 "Hook run when calc.el is loaded.")
847
848 (defvar calc-window-hook nil
849 "Hook called to create the Calc window.")
850
851 (defvar calc-trail-window-hook nil
852 "Hook called to create the Calc trail window.")
853
854 (defvar calc-embedded-new-buffer-hook nil
855 "Hook run when starting embedded mode in a new buffer.")
856
857 (defvar calc-embedded-new-formula-hook nil
858 "Hook run when starting embedded mode in a new formula.")
859
860 (defvar calc-embedded-mode-hook nil
861 "Hook run when starting embedded mode.")
862
863 ;; Set up the autoloading linkage.
864 (let ((name (and (fboundp 'calc-dispatch)
865 (eq (car-safe (symbol-function 'calc-dispatch)) 'autoload)
866 (nth 1 (symbol-function 'calc-dispatch))))
867 (p load-path))
868
869 ;; If Calc files exist on the load-path, we're all set.
870 (while (and p (not (file-exists-p
871 (expand-file-name "calc-misc.elc" (car p)))))
872 (setq p (cdr p)))
873 (or p
874
875 ;; If Calc is autoloaded using a path name, look there for Calc files.
876 ;; This works for both relative ("calc/calc.elc") and absolute paths.
877 (and name (file-name-directory name)
878 (let ((p2 load-path)
879 (name2 (concat (file-name-directory name)
880 "calc-misc.elc")))
881 (while (and p2 (not (file-exists-p
882 (expand-file-name name2 (car p2)))))
883 (setq p2 (cdr p2)))
884 (when p2
885 (setq load-path (nconc load-path
886 (list
887 (directory-file-name
888 (file-name-directory
889 (expand-file-name
890 name (car p2))))))))))))
891
892 ;; The following modes use specially-formatted data.
893 (put 'calc-mode 'mode-class 'special)
894 (put 'calc-trail-mode 'mode-class 'special)
895
896 ;; Define "inexact-result" as an e-lisp error symbol.
897 (put 'inexact-result 'error-conditions '(error inexact-result calc-error))
898 (put 'inexact-result 'error-message "Calc internal error (inexact-result)")
899
900 ;; Define "math-overflow" and "math-underflow" as e-lisp error symbols.
901 (put 'math-overflow 'error-conditions '(error math-overflow calc-error))
902 (put 'math-overflow 'error-message "Floating-point overflow occurred")
903 (put 'math-underflow 'error-conditions '(error math-underflow calc-error))
904 (put 'math-underflow 'error-message "Floating-point underflow occurred")
905
906 (defconst calc-version "2.1")
907 (defvar calc-trail-pointer nil
908 "The \"current\" entry in trail buffer.")
909 (defvar calc-trail-overlay nil
910 "The value of overlay-arrow-string.")
911 (defvar calc-undo-list nil
912 "The list of previous operations for undo.")
913 (defvar calc-redo-list nil
914 "The list of recent undo operations.")
915 (defvar calc-main-buffer nil
916 "A pointer to Calculator buffer.")
917 (defvar calc-trail-buffer nil
918 "A pointer to Calc Trail buffer.")
919 (defvar calc-why nil
920 "Explanations of most recent errors.")
921 (defvar calc-next-why nil)
922 (defvar calc-inverse-flag nil
923 "If non-nil, next operation is Inverse.")
924 (defvar calc-hyperbolic-flag nil
925 "If non-nil, next operation is Hyperbolic.")
926 (defvar calc-keep-args-flag nil
927 "If non-nil, next operation should not remove its arguments from stack.")
928 (defvar calc-function-open "("
929 "Open-parenthesis string for function call notation.")
930 (defvar calc-function-close ")"
931 "Close-parenthesis string for function call notation.")
932 (defvar calc-language-output-filter nil
933 "Function through which to pass strings after formatting.")
934 (defvar calc-language-input-filter nil
935 "Function through which to pass strings before parsing.")
936 (defvar calc-radix-formatter nil
937 "Formatting function used for non-decimal numbers.")
938 (defvar calc-lang-slash-idiv nil
939 "A list of languages in which / might represent integer division.")
940 (defvar calc-lang-allow-underscores nil
941 "A list of languages which allow underscores in variable names.")
942 (defvar calc-lang-allow-percentsigns nil
943 "A list of languages which allow percent signs in variable names.")
944 (defvar calc-lang-c-type-hex nil
945 "Languages in which octal and hex numbers are written with leading 0 and 0x,")
946 (defvar calc-lang-brackets-are-subscripts nil
947 "Languages in which subscripts are indicated by brackets.")
948 (defvar calc-lang-parens-are-subscripts nil
949 "Languages in which subscripts are indicated by parentheses.")
950
951 (defvar calc-last-kill nil
952 "The last number killed in calc-mode.")
953 (defvar calc-dollar-values nil
954 "Values to be used for '$'.")
955 (defvar calc-dollar-used nil
956 "The highest order of '$' that occurred.")
957 (defvar calc-hashes-used nil
958 "The highest order of '#' that occurred.")
959 (defvar calc-quick-prev-results nil
960 "Previous results from Quick Calc.")
961 (defvar calc-said-hello nil
962 "Non-nil if the welcomd message has been displayed.")
963 (defvar calc-executing-macro nil
964 "Non-nil if a keyboard macro is executing from the \"K\" key.")
965 (defvar calc-any-selections nil
966 "Non-nil if there are selections present.")
967 (defvar calc-help-phase 0
968 "The number of consecutive \"?\" keystrokes.")
969 (defvar calc-full-help-flag nil
970 "Non-nil if `calc-full-help' is being executed.")
971 (defvar calc-refresh-count 0
972 "The number of `calc-refresh' calls.")
973 (defvar calc-display-dirty nil
974 "Non-nil if the stack display might not reflect the latest mode settings.")
975 (defvar calc-prepared-composition nil)
976 (defvar calc-selection-cache-default-entry nil)
977 (defvar calc-embedded-info nil
978 "If non-nil, a vector consisting of information for embedded mode.")
979 (defvar calc-embedded-active nil
980 "Alist of buffers with sorted lists of calc-embedded-infos.")
981 (defvar calc-standalone-flag nil
982 "Non-nil if Emacs started with standalone Calc.")
983 (defvar var-EvalRules nil
984 "User defined rules that Calc will apply automatically.")
985 (defvar math-eval-rules-cache-tag t)
986 (defvar math-radix-explicit-format t)
987 (defvar math-expr-function-mapping nil
988 "Alist of language specific functions with Calc functions.")
989 (defvar math-expr-variable-mapping nil
990 "Alist of language specific variables with Calc variables.")
991 (defvar math-read-expr-quotes nil)
992 (defvar math-working-step nil)
993 (defvar math-working-step-2 nil)
994 (defvar var-i '(special-const (math-imaginary 1)))
995 (defvar var-pi '(special-const (math-pi)))
996 (defvar var-e '(special-const (math-e)))
997 (defvar var-phi '(special-const (math-phi)))
998 (defvar var-gamma '(special-const (math-gamma-const)))
999 (defvar var-Modes '(special-const (math-get-modes-vec)))
1000
1001 (mapc (lambda (v) (or (boundp v) (set v nil)))
1002 calc-local-var-list)
1003
1004 (defvar calc-mode-map
1005 (let ((map (make-keymap)))
1006 (suppress-keymap map t)
1007 (define-key map "+" 'calc-plus)
1008 (define-key map "-" 'calc-minus)
1009 (define-key map "*" 'calc-times)
1010 (define-key map "/" 'calc-divide)
1011 (define-key map "%" 'calc-mod)
1012 (define-key map "&" 'calc-inv)
1013 (define-key map "^" 'calc-power)
1014 (define-key map "\M-%" 'calc-percent)
1015 (define-key map "e" 'calcDigit-start)
1016 (define-key map "i" 'calc-info)
1017 (define-key map "n" 'calc-change-sign)
1018 (define-key map "q" 'calc-quit)
1019 (define-key map "Y" 'nil)
1020 (define-key map "Y?" 'calc-shift-Y-prefix-help)
1021 (define-key map "?" 'calc-help)
1022 (define-key map " " 'calc-enter)
1023 (define-key map "'" 'calc-algebraic-entry)
1024 (define-key map "$" 'calc-auto-algebraic-entry)
1025 (define-key map "\"" 'calc-auto-algebraic-entry)
1026 (define-key map "\t" 'calc-roll-down)
1027 (define-key map "\M-\t" 'calc-roll-up)
1028 (define-key map "\C-m" 'calc-enter)
1029 (define-key map "\M-\C-m" 'calc-last-args-stub)
1030 (define-key map "\C-j" 'calc-over)
1031 (define-key map "\C-y" 'calc-yank)
1032 (define-key map [mouse-2] 'calc-yank)
1033
1034 (mapc (lambda (x) (define-key map (char-to-string x) 'undefined))
1035 "lOW")
1036 (mapc (lambda (x) (define-key map (char-to-string x) 'calc-missing-key))
1037 (concat "ABCDEFGHIJKLMNPQRSTUVXZabcdfghjkmoprstuvwxyz"
1038 ":\\|!()[]<>{},;=~`\C-k\M-k\C-w\M-w\C-y\C-_"))
1039 (mapc (lambda (x) (define-key map (char-to-string x) 'calcDigit-start))
1040 "_0123456789.#@")
1041 map)
1042 "The key map for Calc.")
1043
1044
1045
1046 (defvar calc-digit-map
1047 (let ((map (make-keymap)))
1048 (if (featurep 'xemacs)
1049 (map-keymap (function
1050 (lambda (keys bind)
1051 (define-key map keys
1052 (if (eq bind 'undefined)
1053 'undefined 'calcDigit-nondigit))))
1054 calc-mode-map)
1055 (let ((cmap (nth 1 calc-mode-map))
1056 (dmap (nth 1 map))
1057 (i 0))
1058 (while (< i 128)
1059 (aset dmap i
1060 (if (eq (aref cmap i) 'undefined)
1061 'undefined 'calcDigit-nondigit))
1062 (setq i (1+ i)))))
1063 (mapc (lambda (x) (define-key map (char-to-string x) 'calcDigit-key))
1064 "_0123456789.e+-:n#@oh'\"mspM")
1065 (mapc (lambda (x) (define-key map (char-to-string x) 'calcDigit-letter))
1066 "abcdfgijklqrtuvwxyzABCDEFGHIJKLNOPQRSTUVWXYZ")
1067 (define-key map "'" 'calcDigit-algebraic)
1068 (define-key map "`" 'calcDigit-edit)
1069 (define-key map "\C-g" 'abort-recursive-edit)
1070 map)
1071 "The key map for entering Calc digits.")
1072
1073 (mapc (lambda (x)
1074 (condition-case err
1075 (progn
1076 (define-key calc-digit-map x 'calcDigit-backspace)
1077 (define-key calc-mode-map x 'calc-pop)
1078 (define-key calc-mode-map
1079 (if (vectorp x)
1080 (if (featurep 'xemacs)
1081 (if (= (length x) 1)
1082 (vector (if (consp (aref x 0))
1083 (cons 'meta (aref x 0))
1084 (list 'meta (aref x 0))))
1085 "\e\C-d")
1086 (vconcat "\e" x))
1087 (concat "\e" x))
1088 'calc-pop-above))
1089 (error nil)))
1090 (if calc-scan-for-dels
1091 (append (where-is-internal 'delete-backward-char global-map)
1092 (where-is-internal 'backward-delete-char global-map)
1093 (where-is-internal 'backward-delete-char-untabify global-map)
1094 '("\C-d"))
1095 '("\177" "\C-d")))
1096
1097 (defvar calc-dispatch-map
1098 (let ((map (make-keymap)))
1099 (mapc (lambda (x)
1100 (define-key map (char-to-string (car x)) (cdr x))
1101 (when (string-match "abcdefhijklnopqrstuwxyz"
1102 (char-to-string (car x)))
1103 (define-key map (char-to-string (- (car x) ?a -1)) (cdr x)))
1104 (define-key map (format "\e%c" (car x)) (cdr x)))
1105 '( ( ?a . calc-embedded-activate )
1106 ( ?b . calc-big-or-small )
1107 ( ?c . calc )
1108 ( ?d . calc-embedded-duplicate )
1109 ( ?e . calc-embedded )
1110 ( ?f . calc-embedded-new-formula )
1111 ( ?g . calc-grab-region )
1112 ( ?h . calc-dispatch-help )
1113 ( ?i . calc-info )
1114 ( ?j . calc-embedded-select )
1115 ( ?k . calc-keypad )
1116 ( ?l . calc-load-everything )
1117 ( ?m . read-kbd-macro )
1118 ( ?n . calc-embedded-next )
1119 ( ?o . calc-other-window )
1120 ( ?p . calc-embedded-previous )
1121 ( ?q . quick-calc )
1122 ( ?r . calc-grab-rectangle )
1123 ( ?s . calc-info-summary )
1124 ( ?t . calc-tutorial )
1125 ( ?u . calc-embedded-update-formula )
1126 ( ?w . calc-embedded-word )
1127 ( ?x . calc-quit )
1128 ( ?y . calc-copy-to-buffer )
1129 ( ?z . calc-user-invocation )
1130 ( ?\' . calc-embedded-new-formula )
1131 ( ?\` . calc-embedded-edit )
1132 ( ?: . calc-grab-sum-down )
1133 ( ?_ . calc-grab-sum-across )
1134 ( ?0 . calc-reset )
1135 ( ?? . calc-dispatch-help )
1136 ( ?# . calc-same-interface )
1137 ( ?& . calc-same-interface )
1138 ( ?\\ . calc-same-interface )
1139 ( ?= . calc-same-interface )
1140 ( ?* . calc-same-interface )
1141 ( ?/ . calc-same-interface )
1142 ( ?+ . calc-same-interface )
1143 ( ?- . calc-same-interface ) ))
1144 map)
1145 "The key map for starting Calc.")
1146
1147
1148 ;;;; (Autoloads here)
1149 (load "calc-loaddefs.el" nil t)
1150
1151 ;;;###autoload (define-key ctl-x-map "*" 'calc-dispatch)
1152
1153 ;;;###autoload
1154 (defun calc-dispatch (&optional arg)
1155 "Invoke the GNU Emacs Calculator. See `calc-dispatch-help' for details."
1156 (interactive "P")
1157 ; (sit-for echo-keystrokes)
1158 (condition-case err ; look for other keys bound to calc-dispatch
1159 (let ((keys (this-command-keys)))
1160 (unless (or (not (stringp keys))
1161 (string-match "\\`\C-u\\|\\`\e[-0-9#]\\|`[\M--\M-0-\M-9]" keys)
1162 (eq (lookup-key calc-dispatch-map keys) 'calc-same-interface))
1163 (when (and (string-match "\\`[\C-@-\C-_]" keys)
1164 (symbolp
1165 (lookup-key calc-dispatch-map (substring keys 0 1))))
1166 (define-key calc-dispatch-map (substring keys 0 1) nil))
1167 (define-key calc-dispatch-map keys 'calc-same-interface)))
1168 (error nil))
1169 (calc-do-dispatch arg))
1170
1171 (defvar calc-dispatch-help nil)
1172 (defun calc-do-dispatch (arg)
1173 "Start the Calculator."
1174 (let ((key (calc-read-key-sequence
1175 (if calc-dispatch-help
1176 "Calc options: Calc, Keypad, Quick, Embed; eXit; Info, Tutorial; Grab; ?=more"
1177 (format "%s (Type ? for a list of Calc options)"
1178 (key-description (this-command-keys))))
1179 calc-dispatch-map)))
1180 (setq key (lookup-key calc-dispatch-map key))
1181 (message "")
1182 (if key
1183 (progn
1184 (or (commandp key) (require 'calc-ext))
1185 (call-interactively key))
1186 (beep))))
1187
1188 (defun calc-read-key-sequence (prompt map)
1189 "Read keys, with prompt PROMPT and keymap MAP."
1190 (let ((prompt2 (format "%s " (key-description (this-command-keys))))
1191 (glob (current-global-map))
1192 (loc (current-local-map)))
1193 (or (input-pending-p) (message "%s" prompt))
1194 (let ((key (calc-read-key t)))
1195 (calc-unread-command (cdr key))
1196 (unwind-protect
1197 (progn
1198 (use-global-map map)
1199 (use-local-map nil)
1200 (read-key-sequence nil))
1201 (use-global-map glob)
1202 (use-local-map loc)))))
1203
1204 (defvar calc-alg-map) ; Defined in calc-ext.el
1205
1206 (defun calc-version ()
1207 "Return version of this version of Calc."
1208 (interactive)
1209 (message "Calc version %s" calc-version))
1210
1211 (defun calc-mode ()
1212 "Calculator major mode.
1213
1214 This is an RPN calculator featuring arbitrary-precision integer, rational,
1215 floating-point, complex, matrix, and symbolic arithmetic.
1216
1217 RPN calculation: 2 RET 3 + produces 5.
1218 Algebraic style: ' 2+3 RET produces 5.
1219
1220 Basic operators are +, -, *, /, ^, & (reciprocal), % (modulo), n (change-sign).
1221
1222 Press ? repeatedly for more complete help. Press `h i' to read the
1223 Calc manual on-line, `h s' to read the summary, or `h t' for the tutorial.
1224
1225 Notations: 3.14e6 3.14 * 10^6
1226 _23 negative number -23 (or type `23 n')
1227 17:3 the fraction 17/3
1228 5:2:3 the fraction 5 and 2/3
1229 16#12C the integer 12C base 16 = 300 base 10
1230 8#177:100 the fraction 177:100 base 8 = 127:64 base 10
1231 (2, 4) complex number 2 + 4i
1232 (2; 4) polar complex number (r; theta)
1233 [1, 2, 3] vector ([[1, 2], [3, 4]] is a matrix)
1234 [1 .. 4) semi-open interval, 1 <= x < 4
1235 2 +/- 3 (p key) number with mean 2, standard deviation 3
1236 2 mod 3 (M key) number 2 computed modulo 3
1237 <1 jan 91> Date form (enter using ' key)
1238
1239
1240 \\{calc-mode-map}
1241 "
1242 (interactive)
1243 (mapc (function
1244 (lambda (v) (set-default v (symbol-value v)))) calc-local-var-list)
1245 (kill-all-local-variables)
1246 (use-local-map (if (eq calc-algebraic-mode 'total)
1247 (progn (require 'calc-ext) calc-alg-map) calc-mode-map))
1248 (mapc (function (lambda (v) (make-local-variable v))) calc-local-var-list)
1249 (make-local-variable 'overlay-arrow-position)
1250 (make-local-variable 'overlay-arrow-string)
1251 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
1252 (setq truncate-lines t)
1253 (setq buffer-read-only t)
1254 (setq major-mode 'calc-mode)
1255 (setq mode-name "Calculator")
1256 (setq calc-stack-top (length (or (memq (assq 'top-of-stack calc-stack)
1257 calc-stack)
1258 (setq calc-stack (list (list 'top-of-stack
1259 1 nil))))))
1260 (setq calc-stack-top (- (length calc-stack) calc-stack-top -1))
1261 (or calc-loaded-settings-file
1262 (null calc-settings-file)
1263 (equal calc-settings-file user-init-file)
1264 (progn
1265 (setq calc-loaded-settings-file t)
1266 (load (file-name-sans-extension calc-settings-file) t))) ; t = missing-ok
1267 (let ((p command-line-args))
1268 (while p
1269 (and (equal (car p) "-f")
1270 (string-match "calc" (nth 1 p))
1271 (string-match "full" (nth 1 p))
1272 (setq calc-standalone-flag t))
1273 (setq p (cdr p))))
1274 (require 'calc-menu)
1275 (run-mode-hooks 'calc-mode-hook)
1276 (calc-refresh t)
1277 (calc-set-mode-line)
1278 (calc-check-defines))
1279
1280 (defvar calc-check-defines 'calc-check-defines) ; suitable for run-hooks
1281 (defun calc-check-defines ()
1282 (if (symbol-plist 'calc-define)
1283 (let ((plist (copy-sequence (symbol-plist 'calc-define))))
1284 (while (and plist (null (nth 1 plist)))
1285 (setq plist (cdr (cdr plist))))
1286 (if plist
1287 (save-excursion
1288 (require 'calc-ext)
1289 (require 'calc-macs)
1290 (set-buffer "*Calculator*")
1291 (while plist
1292 (put 'calc-define (car plist) nil)
1293 (eval (nth 1 plist))
1294 (setq plist (cdr (cdr plist))))
1295 ;; See if this has added any more calc-define properties.
1296 (calc-check-defines))
1297 (setplist 'calc-define nil)))))
1298
1299 (defun calc-trail-mode (&optional buf)
1300 "Calc Trail mode.
1301 This mode is used by the *Calc Trail* buffer, which records all results
1302 obtained by the GNU Emacs Calculator.
1303
1304 Calculator commands beginning with the `t' key are used to manipulate
1305 the Trail.
1306
1307 This buffer uses the same key map as the *Calculator* buffer; calculator
1308 commands given here will actually operate on the *Calculator* stack."
1309 (interactive)
1310 (fundamental-mode)
1311 (use-local-map calc-mode-map)
1312 (setq major-mode 'calc-trail-mode)
1313 (setq mode-name "Calc Trail")
1314 (setq truncate-lines t)
1315 (setq buffer-read-only t)
1316 (make-local-variable 'overlay-arrow-position)
1317 (make-local-variable 'overlay-arrow-string)
1318 (when buf
1319 (set (make-local-variable 'calc-main-buffer) buf))
1320 (when (= (buffer-size) 0)
1321 (let ((buffer-read-only nil))
1322 (insert (propertize (concat "Emacs Calculator Trail\n")
1323 'font-lock-face 'italic))))
1324 (run-mode-hooks 'calc-trail-mode-hook))
1325
1326 (defun calc-create-buffer ()
1327 "Create and initialize a buffer for the Calculator."
1328 (set-buffer (get-buffer-create "*Calculator*"))
1329 (or (eq major-mode 'calc-mode)
1330 (calc-mode))
1331 (setq max-lisp-eval-depth (max max-lisp-eval-depth 1000))
1332 (when calc-always-load-extensions
1333 (require 'calc-ext))
1334 (when calc-language
1335 (require 'calc-ext)
1336 (calc-set-language calc-language calc-language-option t)))
1337
1338 ;;;###autoload
1339 (defun calc (&optional arg full-display interactive)
1340 "The Emacs Calculator. Full documentation is listed under \"calc-mode\"."
1341 (interactive "P\ni\np")
1342 (if arg
1343 (unless (eq arg 0)
1344 (require 'calc-ext)
1345 (if (= (prefix-numeric-value arg) -1)
1346 (calc-grab-region (region-beginning) (region-end) nil)
1347 (when (= (prefix-numeric-value arg) -2)
1348 (calc-keypad))))
1349 (when (get-buffer-window "*Calc Keypad*")
1350 (calc-keypad)
1351 (set-buffer (window-buffer (selected-window))))
1352 (if (eq major-mode 'calc-mode)
1353 (calc-quit)
1354 (let ((oldbuf (current-buffer)))
1355 (calc-create-buffer)
1356 (setq calc-was-keypad-mode nil)
1357 (if (or (eq full-display t)
1358 (and (null full-display) calc-full-mode))
1359 (switch-to-buffer (current-buffer) t)
1360 (if (get-buffer-window (current-buffer))
1361 (select-window (get-buffer-window (current-buffer)))
1362 (if calc-window-hook
1363 (run-hooks 'calc-window-hook)
1364 (let ((w (get-largest-window)))
1365 (if (and pop-up-windows
1366 (> (window-height w)
1367 (+ window-min-height calc-window-height 2)))
1368 (progn
1369 (setq w (split-window w
1370 (- (window-height w)
1371 calc-window-height 2)
1372 nil))
1373 (set-window-buffer w (current-buffer))
1374 (select-window w))
1375 (pop-to-buffer (current-buffer)))))))
1376 (save-excursion
1377 (set-buffer (calc-trail-buffer))
1378 (and calc-display-trail
1379 (= (window-width) (frame-width))
1380 (calc-trail-display 1 t)))
1381 (message "Welcome to the GNU Emacs Calculator! Press `?' or `h' for help, `q' to quit")
1382 (run-hooks 'calc-start-hook)
1383 (and (windowp full-display)
1384 (window-point full-display)
1385 (select-window full-display))
1386 (calc-check-defines)
1387 (when (and calc-said-hello interactive)
1388 (sit-for 2)
1389 (message ""))
1390 (setq calc-said-hello t)))))
1391
1392 ;;;###autoload
1393 (defun full-calc (&optional interactive)
1394 "Invoke the Calculator and give it a full-sized window."
1395 (interactive "p")
1396 (calc nil t interactive))
1397
1398 (defun calc-same-interface (arg)
1399 "Invoke the Calculator using the most recent interface (calc or calc-keypad)."
1400 (interactive "P")
1401 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1402 (> (recursion-depth) 0))
1403 (exit-recursive-edit)
1404 (if (eq major-mode 'calc-edit-mode)
1405 (calc-edit-finish arg)
1406 (if calc-was-keypad-mode
1407 (calc-keypad)
1408 (calc arg calc-full-mode t)))))
1409
1410 (defun calc-quit (&optional non-fatal interactive)
1411 "Quit the Calculator in an appropriate manner."
1412 (interactive "i\np")
1413 (and calc-standalone-flag (not non-fatal)
1414 (save-buffers-kill-emacs nil))
1415 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1416 (> (recursion-depth) 0))
1417 (exit-recursive-edit))
1418 (if (eq major-mode 'calc-edit-mode)
1419 (calc-edit-cancel)
1420 (if (and interactive
1421 calc-embedded-info
1422 (eq (current-buffer) (aref calc-embedded-info 0)))
1423 (calc-embedded nil)
1424 (unless (eq major-mode 'calc-mode)
1425 (calc-create-buffer))
1426 (run-hooks 'calc-end-hook)
1427 (setq calc-undo-list nil calc-redo-list nil)
1428 (mapc (function (lambda (v) (set-default v (symbol-value v))))
1429 calc-local-var-list)
1430 (let ((buf (current-buffer))
1431 (win (get-buffer-window (current-buffer)))
1432 (kbuf (get-buffer "*Calc Keypad*")))
1433 (delete-windows-on (calc-trail-buffer))
1434 (if (and win
1435 (< (window-height win) (1- (frame-height)))
1436 (= (window-width win) (frame-width)) ; avoid calc-keypad
1437 (not (get-buffer-window "*Calc Keypad*")))
1438 (setq calc-window-height (- (window-height win) 2)))
1439 (progn
1440 (delete-windows-on buf)
1441 (delete-windows-on kbuf))
1442 (bury-buffer buf)
1443 (bury-buffer calc-trail-buffer)
1444 (and kbuf (bury-buffer kbuf))))))
1445
1446 ;;;###autoload
1447 (defun quick-calc ()
1448 "Do a quick calculation in the minibuffer without invoking full Calculator."
1449 (interactive)
1450 (calc-do-quick-calc))
1451
1452 ;;;###autoload
1453 (defun calc-eval (str &optional separator &rest args)
1454 "Do a quick calculation and return the result as a string.
1455 Return value will either be the formatted result in string form,
1456 or a list containing a character position and an error message in string form."
1457 (calc-do-calc-eval str separator args))
1458
1459 ;;;###autoload
1460 (defun calc-keypad (&optional interactive)
1461 "Invoke the Calculator in \"visual keypad\" mode.
1462 This is most useful in the X window system.
1463 In this mode, click on the Calc \"buttons\" using the left mouse button.
1464 Or, position the cursor manually and do M-x calc-keypad-press."
1465 (interactive "p")
1466 (require 'calc-ext)
1467 (calc-do-keypad calc-full-mode interactive))
1468
1469 ;;;###autoload
1470 (defun full-calc-keypad (&optional interactive)
1471 "Invoke the Calculator in full-screen \"visual keypad\" mode.
1472 See calc-keypad for details."
1473 (interactive "p")
1474 (require 'calc-ext)
1475 (calc-do-keypad t interactive))
1476
1477
1478 (defvar calc-aborted-prefix nil)
1479 (defvar calc-start-time nil)
1480 (defvar calc-command-flags)
1481 (defvar calc-final-point-line)
1482 (defvar calc-final-point-column)
1483 ;;; Note that modifications to this function may break calc-pass-errors.
1484 (defun calc-do (do-body &optional do-slow)
1485 (calc-check-defines)
1486 (let* ((calc-command-flags nil)
1487 (calc-start-time (and calc-timing (not calc-start-time)
1488 (require 'calc-ext)
1489 (current-time-string)))
1490 (gc-cons-threshold (max gc-cons-threshold
1491 (if calc-timing 2000000 100000)))
1492 calc-final-point-line calc-final-point-column)
1493 (setq calc-aborted-prefix "")
1494 (unwind-protect
1495 (condition-case err
1496 (save-excursion
1497 (if calc-embedded-info
1498 (calc-embedded-select-buffer)
1499 (calc-select-buffer))
1500 (and (eq calc-algebraic-mode 'total)
1501 (require 'calc-ext)
1502 (use-local-map calc-alg-map))
1503 (when (and do-slow calc-display-working-message)
1504 (message "Working...")
1505 (calc-set-command-flag 'clear-message))
1506 (funcall do-body)
1507 (setq calc-aborted-prefix nil)
1508 (when (memq 'renum-stack calc-command-flags)
1509 (calc-renumber-stack))
1510 (when (memq 'clear-message calc-command-flags)
1511 (message "")))
1512 (error
1513 (if (and (eq (car err) 'error)
1514 (stringp (nth 1 err))
1515 (string-match "max-specpdl-size\\|max-lisp-eval-depth"
1516 (nth 1 err)))
1517 (error "Computation got stuck or ran too long. Type `M' to increase the limit")
1518 (setq calc-aborted-prefix nil)
1519 (signal (car err) (cdr err)))))
1520 (when calc-aborted-prefix
1521 (calc-record "<Aborted>" calc-aborted-prefix))
1522 (and calc-start-time
1523 (let* ((calc-internal-prec 12)
1524 (calc-date-format nil)
1525 (end-time (current-time-string))
1526 (time (if (equal calc-start-time end-time)
1527 0
1528 (math-sub
1529 (calcFunc-unixtime (math-parse-date end-time) 0)
1530 (calcFunc-unixtime (math-parse-date calc-start-time)
1531 0)))))
1532 (if (math-lessp 1 time)
1533 (calc-record time "(t)"))))
1534 (or (memq 'no-align calc-command-flags)
1535 (eq major-mode 'calc-trail-mode)
1536 (calc-align-stack-window))
1537 (and (memq 'position-point calc-command-flags)
1538 (if (eq major-mode 'calc-mode)
1539 (progn
1540 (goto-line calc-final-point-line)
1541 (move-to-column calc-final-point-column))
1542 (save-current-buffer
1543 (calc-select-buffer)
1544 (goto-line calc-final-point-line)
1545 (move-to-column calc-final-point-column))))
1546 (unless (memq 'keep-flags calc-command-flags)
1547 (save-excursion
1548 (calc-select-buffer)
1549 (setq calc-inverse-flag nil
1550 calc-hyperbolic-flag nil
1551 calc-keep-args-flag nil)))
1552 (when (memq 'do-edit calc-command-flags)
1553 (switch-to-buffer (get-buffer-create "*Calc Edit*")))
1554 (calc-set-mode-line)
1555 (when calc-embedded-info
1556 (calc-embedded-finish-command))))
1557 (identity nil)) ; allow a GC after timing is done
1558
1559
1560 (defun calc-set-command-flag (f)
1561 (unless (memq f calc-command-flags)
1562 (setq calc-command-flags (cons f calc-command-flags))))
1563
1564 (defun calc-select-buffer ()
1565 (or (eq major-mode 'calc-mode)
1566 (if calc-main-buffer
1567 (set-buffer calc-main-buffer)
1568 (let ((buf (get-buffer "*Calculator*")))
1569 (if buf
1570 (set-buffer buf)
1571 (error "Calculator buffer not available"))))))
1572
1573 (defun calc-cursor-stack-index (&optional index)
1574 (goto-char (point-max))
1575 (forward-line (- (calc-substack-height (or index 1)))))
1576
1577 (defun calc-stack-size ()
1578 (- (length calc-stack) calc-stack-top))
1579
1580 (defun calc-substack-height (n)
1581 (let ((sum 0)
1582 (stack calc-stack))
1583 (setq n (+ n calc-stack-top))
1584 (while (and (> n 0) stack)
1585 (setq sum (+ sum (nth 1 (car stack)))
1586 n (1- n)
1587 stack (cdr stack)))
1588 sum))
1589
1590 (defun calc-set-mode-line ()
1591 (save-excursion
1592 (calc-select-buffer)
1593 (let* ((fmt (car calc-float-format))
1594 (figs (nth 1 calc-float-format))
1595 (new-mode-string
1596 (format "Calc%s%s: %d %s %-14s"
1597 (if calc-embedded-info "Embed" "")
1598 (if (and (> (length (buffer-name)) 12)
1599 (equal (substring (buffer-name) 0 12)
1600 "*Calculator*"))
1601 (substring (buffer-name) 12)
1602 "")
1603 calc-internal-prec
1604 (capitalize (symbol-name calc-angle-mode))
1605 (concat
1606
1607 ;; Input-related modes
1608 (if (eq calc-algebraic-mode 'total) "Alg* "
1609 (if calc-algebraic-mode "Alg "
1610 (if calc-incomplete-algebraic-mode "Alg[( " "")))
1611
1612 ;; Computational modes
1613 (if calc-symbolic-mode "Symb " "")
1614 (cond ((eq calc-matrix-mode 'matrix) "Matrix ")
1615 ((integerp calc-matrix-mode)
1616 (format "Matrix%d " calc-matrix-mode))
1617 ((eq calc-matrix-mode 'sqmatrix) "SqMatrix ")
1618 ((eq calc-matrix-mode 'scalar) "Scalar ")
1619 (t ""))
1620 (if (eq calc-complex-mode 'polar) "Polar " "")
1621 (if calc-prefer-frac "Frac " "")
1622 (cond ((null calc-infinite-mode) "")
1623 ((eq calc-infinite-mode 1) "+Inf ")
1624 (t "Inf "))
1625 (cond ((eq calc-simplify-mode 'none) "NoSimp ")
1626 ((eq calc-simplify-mode 'num) "NumSimp ")
1627 ((eq calc-simplify-mode 'binary)
1628 (format "BinSimp%d " calc-word-size))
1629 ((eq calc-simplify-mode 'alg) "AlgSimp ")
1630 ((eq calc-simplify-mode 'ext) "ExtSimp ")
1631 ((eq calc-simplify-mode 'units) "UnitSimp ")
1632 (t ""))
1633
1634 ;; Display modes
1635 (cond ((= calc-number-radix 10) "")
1636 ((= calc-number-radix 2) "Bin ")
1637 ((= calc-number-radix 8) "Oct ")
1638 ((= calc-number-radix 16) "Hex ")
1639 (t (format "Radix%d " calc-number-radix)))
1640 (if calc-leading-zeros "Zero " "")
1641 (cond ((null calc-language) "")
1642 ((get calc-language 'math-lang-name)
1643 (concat (get calc-language 'math-lang-name) " "))
1644 (t (concat
1645 (capitalize (symbol-name calc-language))
1646 " ")))
1647 (cond ((eq fmt 'float)
1648 (if (zerop figs) "" (format "Norm%d " figs)))
1649 ((eq fmt 'fix) (format "Fix%d " figs))
1650 ((eq fmt 'sci)
1651 (if (zerop figs) "Sci " (format "Sci%d " figs)))
1652 ((eq fmt 'eng)
1653 (if (zerop figs) "Eng " (format "Eng%d " figs))))
1654 (cond ((not calc-display-just)
1655 (if calc-display-origin
1656 (format "Left%d " calc-display-origin) ""))
1657 ((eq calc-display-just 'right)
1658 (if calc-display-origin
1659 (format "Right%d " calc-display-origin)
1660 "Right "))
1661 (t
1662 (if calc-display-origin
1663 (format "Center%d " calc-display-origin)
1664 "Center ")))
1665 (cond ((integerp calc-line-breaking)
1666 (format "Wid%d " calc-line-breaking))
1667 (calc-line-breaking "")
1668 (t "Wide "))
1669
1670 ;; Miscellaneous other modes/indicators
1671 (if calc-assoc-selections "" "Break ")
1672 (cond ((eq calc-mode-save-mode 'save) "Save ")
1673 ((not calc-embedded-info) "")
1674 ((eq calc-mode-save-mode 'local) "Local ")
1675 ((eq calc-mode-save-mode 'edit) "LocEdit ")
1676 ((eq calc-mode-save-mode 'perm) "LocPerm ")
1677 ((eq calc-mode-save-mode 'global) "Global ")
1678 (t ""))
1679 (if calc-auto-recompute "" "Manual ")
1680 (if (and (fboundp 'calc-gnuplot-alive)
1681 (calc-gnuplot-alive)) "Graph " "")
1682 (if (and calc-embedded-info
1683 (> (calc-stack-size) 0)
1684 (calc-top 1 'sel)) "Sel " "")
1685 (if calc-display-dirty "Dirty " "")
1686 (if calc-inverse-flag "Inv " "")
1687 (if calc-hyperbolic-flag "Hyp " "")
1688 (if calc-keep-args-flag "Keep " "")
1689 (if (/= calc-stack-top 1) "Narrow " "")
1690 (apply 'concat calc-other-modes)))))
1691 (if (equal new-mode-string mode-line-buffer-identification)
1692 nil
1693 (setq mode-line-buffer-identification new-mode-string)
1694 (set-buffer-modified-p (buffer-modified-p))
1695 (and calc-embedded-info (calc-embedded-mode-line-change))))))
1696
1697 (defun calc-align-stack-window ()
1698 (if (eq major-mode 'calc-mode)
1699 (progn
1700 (let ((win (get-buffer-window (current-buffer))))
1701 (if win
1702 (progn
1703 (calc-cursor-stack-index 0)
1704 (vertical-motion (- 2 (window-height win)))
1705 (set-window-start win (point)))))
1706 (calc-cursor-stack-index 0)
1707 (if (looking-at " *\\.$")
1708 (goto-char (1- (match-end 0)))))
1709 (save-excursion
1710 (calc-select-buffer)
1711 (calc-align-stack-window))))
1712
1713 (defun calc-check-stack (n)
1714 (if (> n (calc-stack-size))
1715 (error "Too few elements on stack"))
1716 (if (< n 0)
1717 (error "Invalid argument")))
1718
1719 (defun calc-push-list (vals &optional m sels)
1720 (while vals
1721 (if calc-executing-macro
1722 (calc-push-list-in-macro vals m sels)
1723 (save-excursion
1724 (calc-select-buffer)
1725 (let* ((val (car vals))
1726 (entry (list val 1 (car sels)))
1727 (mm (+ (or m 1) calc-stack-top)))
1728 (calc-cursor-stack-index (1- (or m 1)))
1729 (if (> mm 1)
1730 (setcdr (nthcdr (- mm 2) calc-stack)
1731 (cons entry (nthcdr (1- mm) calc-stack)))
1732 (setq calc-stack (cons entry calc-stack)))
1733 (let ((buffer-read-only nil))
1734 (insert (math-format-stack-value entry) "\n"))
1735 (calc-record-undo (list 'push mm))
1736 (calc-set-command-flag 'renum-stack))))
1737 (setq vals (cdr vals)
1738 sels (cdr sels))))
1739
1740 (defun calc-pop-push-list (n vals &optional m sels)
1741 (if (and calc-any-selections (null sels))
1742 (calc-replace-selections n vals m)
1743 (calc-pop-stack n m sels)
1744 (calc-push-list vals m sels)))
1745
1746 (defun calc-pop-push-record-list (n prefix vals &optional m sels)
1747 (or (and (consp vals)
1748 (or (integerp (car vals))
1749 (consp (car vals))))
1750 (and vals (setq vals (list vals)
1751 sels (and sels (list sels)))))
1752 (calc-check-stack (+ n (or m 1) -1))
1753 (if prefix
1754 (if (cdr vals)
1755 (calc-record-list vals prefix)
1756 (calc-record (car vals) prefix)))
1757 (calc-pop-push-list n vals m sels))
1758
1759 (defun calc-enter-result (n prefix vals &optional m)
1760 (setq calc-aborted-prefix prefix)
1761 (if (and (consp vals)
1762 (or (integerp (car vals))
1763 (consp (car vals))))
1764 (setq vals (mapcar 'calc-normalize vals))
1765 (setq vals (calc-normalize vals)))
1766 (or (and (consp vals)
1767 (or (integerp (car vals))
1768 (consp (car vals))))
1769 (setq vals (list vals)))
1770 (if (equal vals '((nil)))
1771 (setq vals nil))
1772 (calc-pop-push-record-list n prefix vals m)
1773 (calc-handle-whys))
1774
1775 (defun calc-normalize (val)
1776 (if (memq calc-simplify-mode '(nil none num))
1777 (math-normalize val)
1778 (require 'calc-ext)
1779 (calc-normalize-fancy val)))
1780
1781 (defun calc-handle-whys ()
1782 (if calc-next-why
1783 (calc-do-handle-whys)))
1784
1785
1786 (defun calc-pop-stack (&optional n m sel-ok) ; pop N objs at level M of stack.
1787 (or n (setq n 1))
1788 (or m (setq m 1))
1789 (or calc-keep-args-flag
1790 (let ((mm (+ m calc-stack-top)))
1791 (if (and calc-any-selections (not sel-ok)
1792 (calc-top-selected n m))
1793 (calc-sel-error))
1794 (if calc-executing-macro
1795 (calc-pop-stack-in-macro n mm)
1796 (calc-record-undo (list 'pop mm (calc-top-list n m 'full)))
1797 (save-excursion
1798 (calc-select-buffer)
1799 (let ((buffer-read-only nil))
1800 (if (> mm 1)
1801 (progn
1802 (calc-cursor-stack-index (1- m))
1803 (let ((bot (point)))
1804 (calc-cursor-stack-index (+ n m -1))
1805 (delete-region (point) bot))
1806 (setcdr (nthcdr (- mm 2) calc-stack)
1807 (nthcdr (+ n mm -1) calc-stack)))
1808 (calc-cursor-stack-index n)
1809 (setq calc-stack (nthcdr n calc-stack))
1810 (delete-region (point) (point-max))))
1811 (calc-set-command-flag 'renum-stack))))))
1812
1813 (defvar sel-mode)
1814 (defun calc-get-stack-element (x)
1815 (cond ((eq sel-mode 'entry)
1816 x)
1817 ((eq sel-mode 'sel)
1818 (nth 2 x))
1819 ((or (null (nth 2 x))
1820 (eq sel-mode 'full)
1821 (not calc-use-selections))
1822 (car x))
1823 (sel-mode
1824 (calc-sel-error))
1825 (t (nth 2 x))))
1826
1827 ;; Get the Nth element of the stack (N=1 is the top element).
1828 (defun calc-top (&optional n sel-mode)
1829 (or n (setq n 1))
1830 (calc-check-stack n)
1831 (calc-get-stack-element (nth (+ n calc-stack-top -1) calc-stack)))
1832
1833 (defun calc-top-n (&optional n sel-mode) ; in case precision has changed
1834 (math-check-complete (calc-normalize (calc-top n sel-mode))))
1835
1836 (defun calc-top-list (&optional n m sel-mode)
1837 (or n (setq n 1))
1838 (or m (setq m 1))
1839 (calc-check-stack (+ n m -1))
1840 (and (> n 0)
1841 (let ((top (copy-sequence (nthcdr (+ m calc-stack-top -1)
1842 calc-stack))))
1843 (setcdr (nthcdr (1- n) top) nil)
1844 (nreverse (mapcar 'calc-get-stack-element top)))))
1845
1846 (defun calc-top-list-n (&optional n m sel-mode)
1847 (mapcar 'math-check-complete
1848 (mapcar 'calc-normalize (calc-top-list n m sel-mode))))
1849
1850
1851 (defun calc-renumber-stack ()
1852 (if calc-line-numbering
1853 (save-excursion
1854 (calc-cursor-stack-index 0)
1855 (let ((lnum 1)
1856 (buffer-read-only nil)
1857 (stack (nthcdr calc-stack-top calc-stack)))
1858 (if (re-search-forward "^[0-9]+[:*]" nil t)
1859 (progn
1860 (beginning-of-line)
1861 (while (re-search-forward "^[0-9]+[:*]" nil t)
1862 (let ((buffer-read-only nil))
1863 (beginning-of-line)
1864 (delete-char 4)
1865 (insert " ")))
1866 (calc-cursor-stack-index 0)))
1867 (while (re-search-backward "^[0-9]+[:*]" nil t)
1868 (delete-char 4)
1869 (if (> lnum 999)
1870 (insert (format "%03d%s" (% lnum 1000)
1871 (if (and (nth 2 (car stack))
1872 calc-use-selections) "*" ":")))
1873 (let ((prefix (int-to-string lnum)))
1874 (insert prefix (if (and (nth 2 (car stack))
1875 calc-use-selections) "*" ":")
1876 (make-string (- 3 (length prefix)) 32))))
1877 (beginning-of-line)
1878 (setq lnum (1+ lnum)
1879 stack (cdr stack))))))
1880 (and calc-embedded-info (calc-embedded-stack-change)))
1881
1882 (defvar calc-any-evaltos nil)
1883 (defun calc-refresh (&optional align)
1884 (interactive)
1885 (and (eq major-mode 'calc-mode)
1886 (not calc-executing-macro)
1887 (let* ((buffer-read-only nil)
1888 (save-point (point))
1889 (save-mark (condition-case err (mark) (error nil)))
1890 (save-aligned (looking-at "\\.$"))
1891 (thing calc-stack)
1892 (calc-any-evaltos nil))
1893 (setq calc-any-selections nil)
1894 (erase-buffer)
1895 (when calc-show-banner
1896 (insert (propertize "--- Emacs Calculator Mode ---\n"
1897 'font-lock-face 'italic)))
1898 (while thing
1899 (goto-char (point-min))
1900 (when calc-show-banner
1901 (forward-line 1))
1902 (insert (math-format-stack-value (car thing)) "\n")
1903 (setq thing (cdr thing)))
1904 (calc-renumber-stack)
1905 (if calc-display-dirty
1906 (calc-wrapper (setq calc-display-dirty nil)))
1907 (and calc-any-evaltos calc-auto-recompute
1908 (calc-wrapper (calc-refresh-evaltos)))
1909 (if (or align save-aligned)
1910 (calc-align-stack-window)
1911 (goto-char save-point))
1912 (if save-mark (set-mark save-mark))))
1913 (and calc-embedded-info (not (eq major-mode 'calc-mode))
1914 (save-excursion
1915 (set-buffer (aref calc-embedded-info 1))
1916 (calc-refresh align)))
1917 (setq calc-refresh-count (1+ calc-refresh-count)))
1918
1919 ;;;; The Calc Trail buffer.
1920
1921 (defun calc-check-trail-aligned ()
1922 (save-excursion
1923 (let ((win (get-buffer-window (current-buffer))))
1924 (and win
1925 (pos-visible-in-window-p (1- (point-max)) win)))))
1926
1927 (defun calc-trail-buffer ()
1928 (and (or (null calc-trail-buffer)
1929 (null (buffer-name calc-trail-buffer)))
1930 (save-excursion
1931 (setq calc-trail-buffer (get-buffer-create "*Calc Trail*"))
1932 (let ((buf (or (and (not (eq major-mode 'calc-mode))
1933 (get-buffer "*Calculator*"))
1934 (current-buffer))))
1935 (set-buffer calc-trail-buffer)
1936 (or (eq major-mode 'calc-trail-mode)
1937 (calc-trail-mode buf)))))
1938 (or (and calc-trail-pointer
1939 (eq (marker-buffer calc-trail-pointer) calc-trail-buffer))
1940 (save-excursion
1941 (set-buffer calc-trail-buffer)
1942 (goto-line 2)
1943 (setq calc-trail-pointer (point-marker))))
1944 calc-trail-buffer)
1945
1946 (defun calc-record (val &optional prefix)
1947 (setq calc-aborted-prefix nil)
1948 (or calc-executing-macro
1949 (let* ((mainbuf (current-buffer))
1950 (buf (calc-trail-buffer))
1951 (calc-display-raw nil)
1952 (calc-can-abbrev-vectors t)
1953 (fval (if val
1954 (if (stringp val)
1955 val
1956 (math-showing-full-precision
1957 (math-format-flat-expr val 0)))
1958 "")))
1959 (save-excursion
1960 (set-buffer buf)
1961 (let ((aligned (calc-check-trail-aligned))
1962 (buffer-read-only nil))
1963 (goto-char (point-max))
1964 (cond ((null prefix) (insert " "))
1965 ((and (> (length prefix) 4)
1966 (string-match " " prefix 4))
1967 (insert (substring prefix 0 4) " "))
1968 (t (insert (format "%4s " prefix))))
1969 (insert fval "\n")
1970 (let ((win (get-buffer-window buf)))
1971 (if (and aligned win (not (memq 'hold-trail calc-command-flags)))
1972 (calc-trail-here))
1973 (goto-char (1- (point-max))))))))
1974 val)
1975
1976
1977 (defun calc-trail-display (flag &optional no-refresh interactive)
1978 (interactive "P\ni\np")
1979 (let ((win (get-buffer-window (calc-trail-buffer))))
1980 (if (setq calc-display-trail
1981 (not (if flag (memq flag '(nil 0)) win)))
1982 (if (null win)
1983 (progn
1984 (if calc-trail-window-hook
1985 (run-hooks 'calc-trail-window-hook)
1986 (let ((w (split-window nil (/ (* (window-width) 2) 3) t)))
1987 (set-window-buffer w calc-trail-buffer)))
1988 (calc-wrapper
1989 (setq overlay-arrow-string calc-trail-overlay
1990 overlay-arrow-position calc-trail-pointer)
1991 (or no-refresh
1992 (if interactive
1993 (calc-do-refresh)
1994 (calc-refresh))))))
1995 (if win
1996 (progn
1997 (delete-window win)
1998 (calc-wrapper
1999 (or no-refresh
2000 (if interactive
2001 (calc-do-refresh)
2002 (calc-refresh))))))))
2003 calc-trail-buffer)
2004
2005 (defun calc-trail-here ()
2006 (interactive)
2007 (if (eq major-mode 'calc-trail-mode)
2008 (progn
2009 (beginning-of-line)
2010 (if (bobp)
2011 (forward-line 1)
2012 (if (eobp)
2013 (forward-line -1)))
2014 (if (or (bobp) (eobp))
2015 (setq overlay-arrow-position nil) ; trail is empty
2016 (set-marker calc-trail-pointer (point) (current-buffer))
2017 (setq calc-trail-overlay (concat (buffer-substring (point)
2018 (+ (point) 4))
2019 ">")
2020 overlay-arrow-string calc-trail-overlay
2021 overlay-arrow-position calc-trail-pointer)
2022 (forward-char 4)
2023 (let ((win (get-buffer-window (current-buffer))))
2024 (if win
2025 (save-excursion
2026 (forward-line (/ (window-height win) 2))
2027 (forward-line (- 1 (window-height win)))
2028 (set-window-start win (point))
2029 (set-window-point win (+ calc-trail-pointer 4))
2030 (set-buffer calc-main-buffer)
2031 (setq overlay-arrow-string calc-trail-overlay
2032 overlay-arrow-position calc-trail-pointer))))))
2033 (error "Not in Calc Trail buffer")))
2034
2035
2036
2037
2038 ;;;; The Undo list.
2039
2040 (defun calc-record-undo (rec)
2041 (or calc-executing-macro
2042 (if (memq 'undo calc-command-flags)
2043 (setq calc-undo-list (cons (cons rec (car calc-undo-list))
2044 (cdr calc-undo-list)))
2045 (setq calc-undo-list (cons (list rec) calc-undo-list)
2046 calc-redo-list nil)
2047 (calc-set-command-flag 'undo))))
2048
2049
2050
2051
2052 ;;; Arithmetic commands.
2053
2054 (defun calc-binary-op (name func arg &optional ident unary func2)
2055 (setq calc-aborted-prefix name)
2056 (if (null arg)
2057 (calc-enter-result 2 name (cons (or func2 func)
2058 (mapcar 'math-check-complete
2059 (calc-top-list 2))))
2060 (require 'calc-ext)
2061 (calc-binary-op-fancy name func arg ident unary)))
2062
2063 (defun calc-unary-op (name func arg &optional func2)
2064 (setq calc-aborted-prefix name)
2065 (if (null arg)
2066 (calc-enter-result 1 name (list (or func2 func)
2067 (math-check-complete (calc-top 1))))
2068 (require 'calc-ext)
2069 (calc-unary-op-fancy name func arg)))
2070
2071
2072 (defun calc-plus (arg)
2073 (interactive "P")
2074 (calc-slow-wrapper
2075 (calc-binary-op "+" 'calcFunc-add arg 0 nil '+)))
2076
2077 (defun calc-minus (arg)
2078 (interactive "P")
2079 (calc-slow-wrapper
2080 (calc-binary-op "-" 'calcFunc-sub arg 0 'neg '-)))
2081
2082 (defun calc-times (arg)
2083 (interactive "P")
2084 (calc-slow-wrapper
2085 (calc-binary-op "*" 'calcFunc-mul arg 1 nil '*)))
2086
2087 (defun calc-divide (arg)
2088 (interactive "P")
2089 (calc-slow-wrapper
2090 (calc-binary-op "/" 'calcFunc-div arg 0 'calcFunc-inv '/)))
2091
2092 (defun calc-left-divide (arg)
2093 (interactive "P")
2094 (calc-slow-wrapper
2095 (calc-binary-op "ldiv" 'calcFunc-ldiv arg 0 nil nil)))
2096
2097 (defun calc-change-sign (arg)
2098 (interactive "P")
2099 (calc-wrapper
2100 (calc-unary-op "chs" 'neg arg)))
2101
2102
2103
2104 ;;; Stack management commands.
2105
2106 (defun calc-enter (n)
2107 (interactive "p")
2108 (calc-wrapper
2109 (cond ((< n 0)
2110 (calc-push-list (calc-top-list 1 (- n))))
2111 ((= n 0)
2112 (calc-push-list (calc-top-list (calc-stack-size))))
2113 (t
2114 (calc-push-list (calc-top-list n))))))
2115
2116
2117 (defun calc-pop (n)
2118 (interactive "P")
2119 (calc-wrapper
2120 (let* ((nn (prefix-numeric-value n))
2121 (top (and (null n) (calc-top 1))))
2122 (cond ((and (null n)
2123 (eq (car-safe top) 'incomplete)
2124 (> (length top) (if (eq (nth 1 top) 'intv) 3 2)))
2125 (calc-pop-push-list 1 (let ((tt (copy-sequence top)))
2126 (setcdr (nthcdr (- (length tt) 2) tt) nil)
2127 (list tt))))
2128 ((< nn 0)
2129 (if (and calc-any-selections
2130 (calc-top-selected 1 (- nn)))
2131 (calc-delete-selection (- nn))
2132 (calc-pop-stack 1 (- nn) t)))
2133 ((= nn 0)
2134 (calc-pop-stack (calc-stack-size) 1 t))
2135 (t
2136 (if (and calc-any-selections
2137 (= nn 1)
2138 (calc-top-selected 1 1))
2139 (calc-delete-selection 1)
2140 (calc-pop-stack nn)))))))
2141
2142
2143
2144
2145 ;;;; Reading a number using the minibuffer.
2146 (defvar calc-buffer)
2147 (defvar calc-prev-char)
2148 (defvar calc-prev-prev-char)
2149 (defvar calc-digit-value)
2150 (defun calcDigit-start ()
2151 (interactive)
2152 (calc-wrapper
2153 (if (or calc-algebraic-mode
2154 (and (> calc-number-radix 14) (eq last-command-char ?e)))
2155 (calc-alg-digit-entry)
2156 (calc-unread-command)
2157 (setq calc-aborted-prefix nil)
2158 (let* ((calc-digit-value nil)
2159 (calc-prev-char nil)
2160 (calc-prev-prev-char nil)
2161 (calc-buffer (current-buffer))
2162 (buf (if (featurep 'xemacs)
2163 (catch 'calc-foo
2164 (catch 'execute-kbd-macro
2165 (throw 'calc-foo
2166 (read-from-minibuffer
2167 "Calc: " "" calc-digit-map)))
2168 (error "XEmacs requires RET after %s"
2169 "digit entry in kbd macro"))
2170 (let ((old-esc (lookup-key global-map "\e")))
2171 (unwind-protect
2172 (progn
2173 (define-key global-map "\e" nil)
2174 (read-from-minibuffer "Calc: " "" calc-digit-map))
2175 (define-key global-map "\e" old-esc))))))
2176 (or calc-digit-value (setq calc-digit-value (math-read-number buf)))
2177 (if (stringp calc-digit-value)
2178 (calc-alg-entry calc-digit-value)
2179 (if calc-digit-value
2180 (calc-push-list (list (calc-record (calc-normalize
2181 calc-digit-value))))))
2182 (if (eq calc-prev-char 'dots)
2183 (progn
2184 (require 'calc-ext)
2185 (calc-dots)))))))
2186
2187 (defsubst calc-minibuffer-size ()
2188 (- (point-max) (minibuffer-prompt-end)))
2189
2190 (defun calcDigit-nondigit ()
2191 (interactive)
2192 ;; Exercise for the reader: Figure out why this is a good precaution!
2193 (or (boundp 'calc-buffer)
2194 (use-local-map minibuffer-local-map))
2195 (let ((str (minibuffer-contents)))
2196 (setq calc-digit-value (save-excursion
2197 (set-buffer calc-buffer)
2198 (math-read-number str))))
2199 (if (and (null calc-digit-value) (> (calc-minibuffer-size) 0))
2200 (progn
2201 (beep)
2202 (calc-temp-minibuffer-message " [Bad format]"))
2203 (or (memq last-command-char '(32 13))
2204 (progn (setq prefix-arg current-prefix-arg)
2205 (calc-unread-command (if (and (eq last-command-char 27)
2206 (>= last-input-char 128))
2207 last-input-char
2208 nil))))
2209 (exit-minibuffer)))
2210
2211
2212 (defun calc-minibuffer-contains (rex)
2213 (save-excursion
2214 (goto-char (minibuffer-prompt-end))
2215 (looking-at rex)))
2216
2217 (defun calcDigit-key ()
2218 (interactive)
2219 (goto-char (point-max))
2220 (if (or (and (memq last-command-char '(?+ ?-))
2221 (> (buffer-size) 0)
2222 (/= (preceding-char) ?e))
2223 (and (memq last-command-char '(?m ?s))
2224 (not (calc-minibuffer-contains "[-+]?[0-9]+\\.?0*[@oh].*"))
2225 (not (calc-minibuffer-contains "[-+]?\\(1[1-9]\\|[2-9][0-9]\\)#.*"))))
2226 (calcDigit-nondigit)
2227 (if (calc-minibuffer-contains "\\([-+]?\\|.* \\)\\'")
2228 (cond ((memq last-command-char '(?. ?@)) (insert "0"))
2229 ((and (memq last-command-char '(?o ?h ?m))
2230 (not (calc-minibuffer-contains ".*#.*"))) (insert "0"))
2231 ((memq last-command-char '(?: ?e)) (insert "1"))
2232 ((eq last-command-char ?#)
2233 (insert (int-to-string calc-number-radix)))))
2234 (if (and (calc-minibuffer-contains "\\([-+]?[0-9]+#\\|[^:]*:\\)\\'")
2235 (eq last-command-char ?:))
2236 (insert "1"))
2237 (if (and (calc-minibuffer-contains "[-+]?[0-9]+#\\'")
2238 (eq last-command-char ?.))
2239 (insert "0"))
2240 (if (and (calc-minibuffer-contains "[-+]?0*\\([2-9]\\|1[0-4]\\)#\\'")
2241 (eq last-command-char ?e))
2242 (insert "1"))
2243 (if (or (and (memq last-command-char '(?h ?o ?m ?s ?p))
2244 (calc-minibuffer-contains ".*#.*"))
2245 (and (eq last-command-char ?e)
2246 (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2247 (and (eq last-command-char ?n)
2248 (calc-minibuffer-contains "[-+]?\\(2[4-9]\\|[3-9][0-9]\\)#.*")))
2249 (setq last-command-char (upcase last-command-char)))
2250 (cond
2251 ((memq last-command-char '(?_ ?n))
2252 (goto-char (minibuffer-prompt-end))
2253 (if (and (search-forward " +/- " nil t)
2254 (not (search-forward "e" nil t)))
2255 (beep)
2256 (and (not (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2257 (search-forward "e" nil t))
2258 (if (looking-at "+")
2259 (delete-char 1))
2260 (if (looking-at "-")
2261 (delete-char 1)
2262 (insert "-")))
2263 (goto-char (point-max)))
2264 ((eq last-command-char ?p)
2265 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2266 (calc-minibuffer-contains ".*mod.*")
2267 (calc-minibuffer-contains ".*#.*")
2268 (calc-minibuffer-contains ".*[-+e:]\\'"))
2269 (beep)
2270 (if (not (calc-minibuffer-contains ".* \\'"))
2271 (insert " "))
2272 (insert "+/- ")))
2273 ((and (eq last-command-char ?M)
2274 (not (calc-minibuffer-contains
2275 "[-+]?\\(2[3-9]\\|[3-9][0-9]\\)#.*")))
2276 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2277 (calc-minibuffer-contains ".*mod *[^ ]+")
2278 (calc-minibuffer-contains ".*[-+e:]\\'"))
2279 (beep)
2280 (if (calc-minibuffer-contains ".*mod \\'")
2281 (if calc-previous-modulo
2282 (insert (math-format-flat-expr calc-previous-modulo 0))
2283 (beep))
2284 (if (not (calc-minibuffer-contains ".* \\'"))
2285 (insert " "))
2286 (insert "mod "))))
2287 (t
2288 (insert (char-to-string last-command-char))
2289 (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]*\\)?\\)?\\'")
2290 (let ((radix (string-to-number
2291 (buffer-substring
2292 (match-beginning 2) (match-end 2)))))
2293 (and (>= radix 2)
2294 (<= radix 36)
2295 (or (memq last-command-char '(?# ?: ?. ?e ?+ ?-))
2296 (let ((dig (math-read-radix-digit
2297 (upcase last-command-char))))
2298 (and dig
2299 (< dig radix)))))))
2300 (calc-minibuffer-contains
2301 "[-+]?\\(.*\\+/- *\\|.*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]?\\'"))
2302 (if (and (memq last-command-char '(?@ ?o ?h ?\' ?m))
2303 (string-match " " calc-hms-format))
2304 (insert " "))
2305 (if (and (eq this-command last-command)
2306 (eq last-command-char ?.))
2307 (progn
2308 (require 'calc-ext)
2309 (calc-digit-dots))
2310 (delete-backward-char 1)
2311 (beep)
2312 (calc-temp-minibuffer-message " [Bad format]"))))))
2313 (setq calc-prev-prev-char calc-prev-char
2314 calc-prev-char last-command-char))
2315
2316
2317 (defun calcDigit-backspace ()
2318 (interactive)
2319 (goto-char (point-max))
2320 (cond ((calc-minibuffer-contains ".* \\+/- \\'")
2321 (backward-delete-char 5))
2322 ((calc-minibuffer-contains ".* mod \\'")
2323 (backward-delete-char 5))
2324 ((calc-minibuffer-contains ".* \\'")
2325 (backward-delete-char 2))
2326 ((eq last-command 'calcDigit-start)
2327 (erase-buffer))
2328 (t (backward-delete-char 1)))
2329 (if (= (calc-minibuffer-size) 0)
2330 (progn
2331 (setq last-command-char 13)
2332 (calcDigit-nondigit))))
2333
2334
2335
2336
2337 (defconst math-bignum-digit-length
2338 (truncate (/ (log10 (/ most-positive-fixnum 2)) 2))
2339 "The length of a \"digit\" in Calc bignums.
2340 If a big integer is of the form (bigpos N0 N1 ...), this is the
2341 length of the allowable Emacs integers N0, N1,...
2342 The value of 2*10^(2*MATH-BIGNUM-DIGIT-LENGTH) must be less than the
2343 largest Emacs integer.")
2344
2345 (defconst math-bignum-digit-size
2346 (expt 10 math-bignum-digit-length)
2347 "An upper bound for the size of the \"digit\"s in Calc bignums.")
2348
2349 (defconst math-small-integer-size
2350 (expt math-bignum-digit-size 2)
2351 "An upper bound for the size of \"small integer\"s in Calc.")
2352
2353
2354 ;;;; Arithmetic routines.
2355 ;;;
2356 ;;; An object as manipulated by one of these routines may take any of the
2357 ;;; following forms:
2358 ;;;
2359 ;;; integer An integer. For normalized numbers, this format
2360 ;;; is used only for
2361 ;;; negative math-small-integer-size + 1 to
2362 ;;; math-small-integer-size - 1
2363 ;;;
2364 ;;; (bigpos N0 N1 N2 ...) A big positive integer,
2365 ;;; N0 + N1*math-bignum-digit-size
2366 ;;; + N2*(math-bignum-digit-size)^2 ...
2367 ;;; (bigneg N0 N1 N2 ...) A big negative integer,
2368 ;;; - N0 - N1*math-bignum-digit-size ...
2369 ;;; Each digit N is in the range
2370 ;;; 0 ... math-bignum-digit-size -1.
2371 ;;; Normalized, always at least three N present,
2372 ;;; and the most significant N is nonzero.
2373 ;;;
2374 ;;; (frac NUM DEN) A fraction. NUM and DEN are small or big integers.
2375 ;;; Normalized, DEN > 1.
2376 ;;;
2377 ;;; (float NUM EXP) A floating-point number, NUM * 10^EXP;
2378 ;;; NUM is a small or big integer, EXP is a small int.
2379 ;;; Normalized, NUM is not a multiple of 10, and
2380 ;;; abs(NUM) < 10^calc-internal-prec.
2381 ;;; Normalized zero is stored as (float 0 0).
2382 ;;;
2383 ;;; (cplx REAL IMAG) A complex number; REAL and IMAG are any of above.
2384 ;;; Normalized, IMAG is nonzero.
2385 ;;;
2386 ;;; (polar R THETA) Polar complex number. Normalized, R > 0 and THETA
2387 ;;; is neither zero nor 180 degrees (pi radians).
2388 ;;;
2389 ;;; (vec A B C ...) Vector of objects A, B, C, ... A matrix is a
2390 ;;; vector of vectors.
2391 ;;;
2392 ;;; (hms H M S) Angle in hours-minutes-seconds form. All three
2393 ;;; components have the same sign; H and M must be
2394 ;;; numerically integers; M and S are expected to
2395 ;;; lie in the range [0,60).
2396 ;;;
2397 ;;; (date N) A date or date/time object. N is an integer to
2398 ;;; store a date only, or a fraction or float to
2399 ;;; store a date and time.
2400 ;;;
2401 ;;; (sdev X SIGMA) Error form, X +/- SIGMA. When normalized,
2402 ;;; SIGMA > 0. X is any complex number and SIGMA
2403 ;;; is real numbers; or these may be symbolic
2404 ;;; expressions where SIGMA is assumed real.
2405 ;;;
2406 ;;; (intv MASK LO HI) Interval form. MASK is 0=(), 1=(], 2=[), or 3=[].
2407 ;;; LO and HI are any real numbers, or symbolic
2408 ;;; expressions which are assumed real, and LO < HI.
2409 ;;; For [LO..HI], if LO = HI normalization produces LO,
2410 ;;; and if LO > HI normalization produces [LO..LO).
2411 ;;; For other intervals, if LO > HI normalization
2412 ;;; sets HI equal to LO.
2413 ;;;
2414 ;;; (mod N M) Number modulo M. When normalized, 0 <= N < M.
2415 ;;; N and M are real numbers.
2416 ;;;
2417 ;;; (var V S) Symbolic variable. V is a Lisp symbol which
2418 ;;; represents the variable's visible name. S is
2419 ;;; the symbol which actually stores the variable's
2420 ;;; value: (var pi var-pi).
2421 ;;;
2422 ;;; In general, combining rational numbers in a calculation always produces
2423 ;;; a rational result, but if either argument is a float, result is a float.
2424
2425 ;;; In the following comments, [x y z] means result is x, args must be y, z,
2426 ;;; respectively, where the code letters are:
2427 ;;;
2428 ;;; O Normalized object (vector or number)
2429 ;;; V Normalized vector
2430 ;;; N Normalized number of any type
2431 ;;; N Normalized complex number
2432 ;;; R Normalized real number (float or rational)
2433 ;;; F Normalized floating-point number
2434 ;;; T Normalized rational number
2435 ;;; I Normalized integer
2436 ;;; B Normalized big integer
2437 ;;; S Normalized small integer
2438 ;;; D Digit (small integer, 0..999)
2439 ;;; L Normalized bignum digit list (without "bigpos" or "bigneg" symbol)
2440 ;;; or normalized vector element list (without "vec")
2441 ;;; P Predicate (truth value)
2442 ;;; X Any Lisp object
2443 ;;; Z "nil"
2444 ;;;
2445 ;;; Lower-case letters signify possibly un-normalized values.
2446 ;;; "L.D" means a cons of an L and a D.
2447 ;;; [N N; n n] means result will be normalized if argument is.
2448 ;;; Also, [Public] marks routines intended to be called from outside.
2449 ;;; [This notation has been neglected in many recent routines.]
2450
2451 (defvar math-eval-rules-cache)
2452 (defvar math-eval-rules-cache-other)
2453 ;;; Reduce an object to canonical (normalized) form. [O o; Z Z] [Public]
2454
2455 (defvar math-normalize-a)
2456 (defun math-normalize (math-normalize-a)
2457 (cond
2458 ((not (consp math-normalize-a))
2459 (if (integerp math-normalize-a)
2460 (if (or (>= math-normalize-a math-small-integer-size)
2461 (<= math-normalize-a (- math-small-integer-size)))
2462 (math-bignum math-normalize-a)
2463 math-normalize-a)
2464 math-normalize-a))
2465 ((eq (car math-normalize-a) 'bigpos)
2466 (if (eq (nth (1- (length math-normalize-a)) math-normalize-a) 0)
2467 (let* ((last (setq math-normalize-a
2468 (copy-sequence math-normalize-a))) (digs math-normalize-a))
2469 (while (setq digs (cdr digs))
2470 (or (eq (car digs) 0) (setq last digs)))
2471 (setcdr last nil)))
2472 (if (cdr (cdr (cdr math-normalize-a)))
2473 math-normalize-a
2474 (cond
2475 ((cdr (cdr math-normalize-a)) (+ (nth 1 math-normalize-a)
2476 (* (nth 2 math-normalize-a)
2477 math-bignum-digit-size)))
2478 ((cdr math-normalize-a) (nth 1 math-normalize-a))
2479 (t 0))))
2480 ((eq (car math-normalize-a) 'bigneg)
2481 (if (eq (nth (1- (length math-normalize-a)) math-normalize-a) 0)
2482 (let* ((last (setq math-normalize-a (copy-sequence math-normalize-a)))
2483 (digs math-normalize-a))
2484 (while (setq digs (cdr digs))
2485 (or (eq (car digs) 0) (setq last digs)))
2486 (setcdr last nil)))
2487 (if (cdr (cdr (cdr math-normalize-a)))
2488 math-normalize-a
2489 (cond
2490 ((cdr (cdr math-normalize-a)) (- (+ (nth 1 math-normalize-a)
2491 (* (nth 2 math-normalize-a)
2492 math-bignum-digit-size))))
2493 ((cdr math-normalize-a) (- (nth 1 math-normalize-a)))
2494 (t 0))))
2495 ((eq (car math-normalize-a) 'float)
2496 (math-make-float (math-normalize (nth 1 math-normalize-a))
2497 (nth 2 math-normalize-a)))
2498 ((or (memq (car math-normalize-a)
2499 '(frac cplx polar hms date mod sdev intv vec var quote
2500 special-const calcFunc-if calcFunc-lambda
2501 calcFunc-quote calcFunc-condition
2502 calcFunc-evalto))
2503 (integerp (car math-normalize-a))
2504 (and (consp (car math-normalize-a))
2505 (not (eq (car (car math-normalize-a)) 'lambda))))
2506 (require 'calc-ext)
2507 (math-normalize-fancy math-normalize-a))
2508 (t
2509 (or (and calc-simplify-mode
2510 (require 'calc-ext)
2511 (math-normalize-nonstandard))
2512 (let ((args (mapcar 'math-normalize (cdr math-normalize-a))))
2513 (or (condition-case err
2514 (let ((func
2515 (assq (car math-normalize-a) '( ( + . math-add )
2516 ( - . math-sub )
2517 ( * . math-mul )
2518 ( / . math-div )
2519 ( % . math-mod )
2520 ( ^ . math-pow )
2521 ( neg . math-neg )
2522 ( | . math-concat ) ))))
2523 (or (and var-EvalRules
2524 (progn
2525 (or (eq var-EvalRules math-eval-rules-cache-tag)
2526 (progn
2527 (require 'calc-ext)
2528 (math-recompile-eval-rules)))
2529 (and (or math-eval-rules-cache-other
2530 (assq (car math-normalize-a)
2531 math-eval-rules-cache))
2532 (math-apply-rewrites
2533 (cons (car math-normalize-a) args)
2534 (cdr math-eval-rules-cache)
2535 nil math-eval-rules-cache))))
2536 (if func
2537 (apply (cdr func) args)
2538 (and (or (consp (car math-normalize-a))
2539 (fboundp (car math-normalize-a))
2540 (and (not (featurep 'calc-ext))
2541 (require 'calc-ext)
2542 (fboundp (car math-normalize-a))))
2543 (apply (car math-normalize-a) args)))))
2544 (wrong-number-of-arguments
2545 (calc-record-why "*Wrong number of arguments"
2546 (cons (car math-normalize-a) args))
2547 nil)
2548 (wrong-type-argument
2549 (or calc-next-why
2550 (calc-record-why "Wrong type of argument"
2551 (cons (car math-normalize-a) args)))
2552 nil)
2553 (args-out-of-range
2554 (calc-record-why "*Argument out of range"
2555 (cons (car math-normalize-a) args))
2556 nil)
2557 (inexact-result
2558 (calc-record-why "No exact representation for result"
2559 (cons (car math-normalize-a) args))
2560 nil)
2561 (math-overflow
2562 (calc-record-why "*Floating-point overflow occurred"
2563 (cons (car math-normalize-a) args))
2564 nil)
2565 (math-underflow
2566 (calc-record-why "*Floating-point underflow occurred"
2567 (cons (car math-normalize-a) args))
2568 nil)
2569 (void-variable
2570 (if (eq (nth 1 err) 'var-EvalRules)
2571 (progn
2572 (setq var-EvalRules nil)
2573 (math-normalize (cons (car math-normalize-a) args)))
2574 (calc-record-why "*Variable is void" (nth 1 err)))))
2575 (if (consp (car math-normalize-a))
2576 (math-dimension-error)
2577 (cons (car math-normalize-a) args))))))))
2578
2579
2580
2581 ;;; True if A is a floating-point real or complex number. [P x] [Public]
2582 (defun math-floatp (a)
2583 (cond ((eq (car-safe a) 'float) t)
2584 ((memq (car-safe a) '(cplx polar mod sdev intv))
2585 (or (math-floatp (nth 1 a))
2586 (math-floatp (nth 2 a))
2587 (and (eq (car a) 'intv) (math-floatp (nth 3 a)))))
2588 ((eq (car-safe a) 'date)
2589 (math-floatp (nth 1 a)))))
2590
2591
2592
2593 ;;; Verify that A is a complete object and return A. [x x] [Public]
2594 (defun math-check-complete (a)
2595 (cond ((integerp a) a)
2596 ((eq (car-safe a) 'incomplete)
2597 (calc-incomplete-error a))
2598 ((consp a) a)
2599 (t (error "Invalid data object encountered"))))
2600
2601
2602
2603 ;;; Coerce integer A to be a bignum. [B S]
2604 (defun math-bignum (a)
2605 (if (>= a 0)
2606 (cons 'bigpos (math-bignum-big a))
2607 (cons 'bigneg (math-bignum-big (- a)))))
2608
2609 (defun math-bignum-big (a) ; [L s]
2610 (if (= a 0)
2611 nil
2612 (cons (% a math-bignum-digit-size)
2613 (math-bignum-big (/ a math-bignum-digit-size)))))
2614
2615
2616 ;;; Build a normalized floating-point number. [F I S]
2617 (defun math-make-float (mant exp)
2618 (if (eq mant 0)
2619 '(float 0 0)
2620 (let* ((ldiff (- calc-internal-prec (math-numdigs mant))))
2621 (if (< ldiff 0)
2622 (setq mant (math-scale-rounding mant ldiff)
2623 exp (- exp ldiff))))
2624 (if (consp mant)
2625 (let ((digs (cdr mant)))
2626 (if (= (% (car digs) 10) 0)
2627 (progn
2628 (while (= (car digs) 0)
2629 (setq digs (cdr digs)
2630 exp (+ exp math-bignum-digit-length)))
2631 (while (= (% (car digs) 10) 0)
2632 (setq digs (math-div10-bignum digs)
2633 exp (1+ exp)))
2634 (setq mant (math-normalize (cons (car mant) digs))))))
2635 (while (= (% mant 10) 0)
2636 (setq mant (/ mant 10)
2637 exp (1+ exp))))
2638 (if (and (<= exp -4000000)
2639 (<= (+ exp (math-numdigs mant) -1) -4000000))
2640 (signal 'math-underflow nil)
2641 (if (and (>= exp 3000000)
2642 (>= (+ exp (math-numdigs mant) -1) 4000000))
2643 (signal 'math-overflow nil)
2644 (list 'float mant exp)))))
2645
2646 (defun math-div10-bignum (a) ; [l l]
2647 (if (cdr a)
2648 (cons (+ (/ (car a) 10) (* (% (nth 1 a) 10)
2649 (expt 10 (1- math-bignum-digit-length))))
2650 (math-div10-bignum (cdr a)))
2651 (list (/ (car a) 10))))
2652
2653 ;;; Coerce A to be a float. [F N; V V] [Public]
2654 (defun math-float (a)
2655 (cond ((Math-integerp a) (math-make-float a 0))
2656 ((eq (car a) 'frac) (math-div (math-float (nth 1 a)) (nth 2 a)))
2657 ((eq (car a) 'float) a)
2658 ((memq (car a) '(cplx polar vec hms date sdev mod))
2659 (cons (car a) (mapcar 'math-float (cdr a))))
2660 (t (math-float-fancy a))))
2661
2662
2663 (defun math-neg (a)
2664 (cond ((not (consp a)) (- a))
2665 ((eq (car a) 'bigpos) (cons 'bigneg (cdr a)))
2666 ((eq (car a) 'bigneg) (cons 'bigpos (cdr a)))
2667 ((memq (car a) '(frac float))
2668 (list (car a) (Math-integer-neg (nth 1 a)) (nth 2 a)))
2669 ((memq (car a) '(cplx vec hms date calcFunc-idn))
2670 (cons (car a) (mapcar 'math-neg (cdr a))))
2671 (t (math-neg-fancy a))))
2672
2673
2674 ;;; Compute the number of decimal digits in integer A. [S I]
2675 (defun math-numdigs (a)
2676 (if (consp a)
2677 (if (cdr a)
2678 (let* ((len (1- (length a)))
2679 (top (nth len a)))
2680 (+ (* (1- len) math-bignum-digit-length) (math-numdigs top)))
2681 0)
2682 (cond ((>= a 100) (+ (math-numdigs (/ a 1000)) 3))
2683 ((>= a 10) 2)
2684 ((>= a 1) 1)
2685 ((= a 0) 0)
2686 ((> a -10) 1)
2687 ((> a -100) 2)
2688 (t (math-numdigs (- a))))))
2689
2690 ;;; Multiply (with truncation toward 0) the integer A by 10^N. [I i S]
2691 (defun math-scale-int (a n)
2692 (cond ((= n 0) a)
2693 ((> n 0) (math-scale-left a n))
2694 (t (math-normalize (math-scale-right a (- n))))))
2695
2696 (defun math-scale-left (a n) ; [I I S]
2697 (if (= n 0)
2698 a
2699 (if (consp a)
2700 (cons (car a) (math-scale-left-bignum (cdr a) n))
2701 (if (>= n math-bignum-digit-length)
2702 (if (or (>= a math-bignum-digit-size)
2703 (<= a (- math-bignum-digit-size)))
2704 (math-scale-left (math-bignum a) n)
2705 (math-scale-left (* a math-bignum-digit-size)
2706 (- n math-bignum-digit-length)))
2707 (let ((sz (expt 10 (- (* 2 math-bignum-digit-length) n))))
2708 (if (or (>= a sz) (<= a (- sz)))
2709 (math-scale-left (math-bignum a) n)
2710 (* a (expt 10 n))))))))
2711
2712 (defun math-scale-left-bignum (a n)
2713 (if (>= n math-bignum-digit-length)
2714 (while (>= (setq a (cons 0 a)
2715 n (- n math-bignum-digit-length))
2716 math-bignum-digit-length)))
2717 (if (> n 0)
2718 (math-mul-bignum-digit a (expt 10 n) 0)
2719 a))
2720
2721 (defun math-scale-right (a n) ; [i i S]
2722 (if (= n 0)
2723 a
2724 (if (consp a)
2725 (cons (car a) (math-scale-right-bignum (cdr a) n))
2726 (if (<= a 0)
2727 (if (= a 0)
2728 0
2729 (- (math-scale-right (- a) n)))
2730 (if (>= n math-bignum-digit-length)
2731 (while (and (> (setq a (/ a math-bignum-digit-size)) 0)
2732 (>= (setq n (- n math-bignum-digit-length))
2733 math-bignum-digit-length))))
2734 (if (> n 0)
2735 (/ a (expt 10 n))
2736 a)))))
2737
2738 (defun math-scale-right-bignum (a n) ; [L L S; l l S]
2739 (if (>= n math-bignum-digit-length)
2740 (setq a (nthcdr (/ n math-bignum-digit-length) a)
2741 n (% n math-bignum-digit-length)))
2742 (if (> n 0)
2743 (cdr (math-mul-bignum-digit a (expt 10 (- math-bignum-digit-length n)) 0))
2744 a))
2745
2746 ;;; Multiply (with rounding) the integer A by 10^N. [I i S]
2747 (defun math-scale-rounding (a n)
2748 (cond ((>= n 0)
2749 (math-scale-left a n))
2750 ((consp a)
2751 (math-normalize
2752 (cons (car a)
2753 (let ((val (if (< n (- math-bignum-digit-length))
2754 (math-scale-right-bignum
2755 (cdr a)
2756 (- (- math-bignum-digit-length) n))
2757 (if (< n 0)
2758 (math-mul-bignum-digit
2759 (cdr a)
2760 (expt 10 (+ math-bignum-digit-length n)) 0)
2761 (cdr a))))) ; n = -math-bignum-digit-length
2762 (if (and val (>= (car val) (/ math-bignum-digit-size 2)))
2763 (if (cdr val)
2764 (if (eq (car (cdr val)) (1- math-bignum-digit-size))
2765 (math-add-bignum (cdr val) '(1))
2766 (cons (1+ (car (cdr val))) (cdr (cdr val))))
2767 '(1))
2768 (cdr val))))))
2769 (t
2770 (if (< a 0)
2771 (- (math-scale-rounding (- a) n))
2772 (if (= n -1)
2773 (/ (+ a 5) 10)
2774 (/ (+ (math-scale-right a (- -1 n)) 5) 10))))))
2775
2776
2777 ;;; Compute the sum of A and B. [O O O] [Public]
2778 (defun math-add (a b)
2779 (or
2780 (and (not (or (consp a) (consp b)))
2781 (progn
2782 (setq a (+ a b))
2783 (if (or (<= a (- math-small-integer-size)) (>= a math-small-integer-size))
2784 (math-bignum a)
2785 a)))
2786 (and (Math-zerop a) (not (eq (car-safe a) 'mod))
2787 (if (and (math-floatp a) (Math-ratp b)) (math-float b) b))
2788 (and (Math-zerop b) (not (eq (car-safe b) 'mod))
2789 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a))
2790 (and (Math-objvecp a) (Math-objvecp b)
2791 (or
2792 (and (Math-integerp a) (Math-integerp b)
2793 (progn
2794 (or (consp a) (setq a (math-bignum a)))
2795 (or (consp b) (setq b (math-bignum b)))
2796 (if (eq (car a) 'bigneg)
2797 (if (eq (car b) 'bigneg)
2798 (cons 'bigneg (math-add-bignum (cdr a) (cdr b)))
2799 (math-normalize
2800 (let ((diff (math-sub-bignum (cdr b) (cdr a))))
2801 (if (eq diff 'neg)
2802 (cons 'bigneg (math-sub-bignum (cdr a) (cdr b)))
2803 (cons 'bigpos diff)))))
2804 (if (eq (car b) 'bigneg)
2805 (math-normalize
2806 (let ((diff (math-sub-bignum (cdr a) (cdr b))))
2807 (if (eq diff 'neg)
2808 (cons 'bigneg (math-sub-bignum (cdr b) (cdr a)))
2809 (cons 'bigpos diff))))
2810 (cons 'bigpos (math-add-bignum (cdr a) (cdr b)))))))
2811 (and (Math-ratp a) (Math-ratp b)
2812 (require 'calc-ext)
2813 (calc-add-fractions a b))
2814 (and (Math-realp a) (Math-realp b)
2815 (progn
2816 (or (and (consp a) (eq (car a) 'float))
2817 (setq a (math-float a)))
2818 (or (and (consp b) (eq (car b) 'float))
2819 (setq b (math-float b)))
2820 (math-add-float a b)))
2821 (and (require 'calc-ext)
2822 (math-add-objects-fancy a b))))
2823 (and (require 'calc-ext)
2824 (math-add-symb-fancy a b))))
2825
2826 (defun math-add-bignum (a b) ; [L L L; l l l]
2827 (if a
2828 (if b
2829 (let* ((a (copy-sequence a)) (aa a) (carry nil) sum)
2830 (while (and aa b)
2831 (if carry
2832 (if (< (setq sum (+ (car aa) (car b)))
2833 (1- math-bignum-digit-size))
2834 (progn
2835 (setcar aa (1+ sum))
2836 (setq carry nil))
2837 (setcar aa (- sum (1- math-bignum-digit-size))))
2838 (if (< (setq sum (+ (car aa) (car b))) math-bignum-digit-size)
2839 (setcar aa sum)
2840 (setcar aa (- sum math-bignum-digit-size))
2841 (setq carry t)))
2842 (setq aa (cdr aa)
2843 b (cdr b)))
2844 (if carry
2845 (if b
2846 (nconc a (math-add-bignum b '(1)))
2847 (while (eq (car aa) (1- math-bignum-digit-size))
2848 (setcar aa 0)
2849 (setq aa (cdr aa)))
2850 (if aa
2851 (progn
2852 (setcar aa (1+ (car aa)))
2853 a)
2854 (nconc a '(1))))
2855 (if b
2856 (nconc a b)
2857 a)))
2858 a)
2859 b))
2860
2861 (defun math-sub-bignum (a b) ; [l l l]
2862 (if b
2863 (if a
2864 (let* ((a (copy-sequence a)) (aa a) (borrow nil) sum diff)
2865 (while (and aa b)
2866 (if borrow
2867 (if (>= (setq diff (- (car aa) (car b))) 1)
2868 (progn
2869 (setcar aa (1- diff))
2870 (setq borrow nil))
2871 (setcar aa (+ diff (1- math-bignum-digit-size))))
2872 (if (>= (setq diff (- (car aa) (car b))) 0)
2873 (setcar aa diff)
2874 (setcar aa (+ diff math-bignum-digit-size))
2875 (setq borrow t)))
2876 (setq aa (cdr aa)
2877 b (cdr b)))
2878 (if borrow
2879 (progn
2880 (while (eq (car aa) 0)
2881 (setcar aa (1- math-bignum-digit-size))
2882 (setq aa (cdr aa)))
2883 (if aa
2884 (progn
2885 (setcar aa (1- (car aa)))
2886 a)
2887 'neg))
2888 (while (eq (car b) 0)
2889 (setq b (cdr b)))
2890 (if b
2891 'neg
2892 a)))
2893 (while (eq (car b) 0)
2894 (setq b (cdr b)))
2895 (and b
2896 'neg))
2897 a))
2898
2899 (defun math-add-float (a b) ; [F F F]
2900 (let ((ediff (- (nth 2 a) (nth 2 b))))
2901 (if (>= ediff 0)
2902 (if (>= ediff (+ calc-internal-prec calc-internal-prec))
2903 a
2904 (math-make-float (math-add (nth 1 b)
2905 (if (eq ediff 0)
2906 (nth 1 a)
2907 (math-scale-left (nth 1 a) ediff)))
2908 (nth 2 b)))
2909 (if (>= (setq ediff (- ediff))
2910 (+ calc-internal-prec calc-internal-prec))
2911 b
2912 (math-make-float (math-add (nth 1 a)
2913 (math-scale-left (nth 1 b) ediff))
2914 (nth 2 a))))))
2915
2916 ;;; Compute the difference of A and B. [O O O] [Public]
2917 (defun math-sub (a b)
2918 (if (or (consp a) (consp b))
2919 (math-add a (math-neg b))
2920 (setq a (- a b))
2921 (if (or (<= a (- math-small-integer-size)) (>= a math-small-integer-size))
2922 (math-bignum a)
2923 a)))
2924
2925 (defun math-sub-float (a b) ; [F F F]
2926 (let ((ediff (- (nth 2 a) (nth 2 b))))
2927 (if (>= ediff 0)
2928 (if (>= ediff (+ calc-internal-prec calc-internal-prec))
2929 a
2930 (math-make-float (math-add (Math-integer-neg (nth 1 b))
2931 (if (eq ediff 0)
2932 (nth 1 a)
2933 (math-scale-left (nth 1 a) ediff)))
2934 (nth 2 b)))
2935 (if (>= (setq ediff (- ediff))
2936 (+ calc-internal-prec calc-internal-prec))
2937 b
2938 (math-make-float (math-add (nth 1 a)
2939 (Math-integer-neg
2940 (math-scale-left (nth 1 b) ediff)))
2941 (nth 2 a))))))
2942
2943
2944 ;;; Compute the product of A and B. [O O O] [Public]
2945 (defun math-mul (a b)
2946 (or
2947 (and (not (consp a)) (not (consp b))
2948 (< a math-bignum-digit-size) (> a (- math-bignum-digit-size))
2949 (< b math-bignum-digit-size) (> b (- math-bignum-digit-size))
2950 (* a b))
2951 (and (Math-zerop a) (not (eq (car-safe b) 'mod))
2952 (if (Math-scalarp b)
2953 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
2954 (require 'calc-ext)
2955 (math-mul-zero a b)))
2956 (and (Math-zerop b) (not (eq (car-safe a) 'mod))
2957 (if (Math-scalarp a)
2958 (if (and (math-floatp a) (Math-ratp b)) (math-float b) b)
2959 (require 'calc-ext)
2960 (math-mul-zero b a)))
2961 (and (Math-objvecp a) (Math-objvecp b)
2962 (or
2963 (and (Math-integerp a) (Math-integerp b)
2964 (progn
2965 (or (consp a) (setq a (math-bignum a)))
2966 (or (consp b) (setq b (math-bignum b)))
2967 (math-normalize
2968 (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
2969 (if (cdr (cdr a))
2970 (if (cdr (cdr b))
2971 (math-mul-bignum (cdr a) (cdr b))
2972 (math-mul-bignum-digit (cdr a) (nth 1 b) 0))
2973 (math-mul-bignum-digit (cdr b) (nth 1 a) 0))))))
2974 (and (Math-ratp a) (Math-ratp b)
2975 (require 'calc-ext)
2976 (calc-mul-fractions a b))
2977 (and (Math-realp a) (Math-realp b)
2978 (progn
2979 (or (and (consp a) (eq (car a) 'float))
2980 (setq a (math-float a)))
2981 (or (and (consp b) (eq (car b) 'float))
2982 (setq b (math-float b)))
2983 (math-make-float (math-mul (nth 1 a) (nth 1 b))
2984 (+ (nth 2 a) (nth 2 b)))))
2985 (and (require 'calc-ext)
2986 (math-mul-objects-fancy a b))))
2987 (and (require 'calc-ext)
2988 (math-mul-symb-fancy a b))))
2989
2990 (defun math-infinitep (a &optional undir)
2991 (while (and (consp a) (memq (car a) '(* / neg)))
2992 (if (or (not (eq (car a) '*)) (math-infinitep (nth 1 a)))
2993 (setq a (nth 1 a))
2994 (setq a (nth 2 a))))
2995 (and (consp a)
2996 (eq (car a) 'var)
2997 (memq (nth 2 a) '(var-inf var-uinf var-nan))
2998 (if (and undir (eq (nth 2 a) 'var-inf))
2999 '(var uinf var-uinf)
3000 a)))
3001
3002 ;;; Multiply digit lists A and B. [L L L; l l l]
3003 (defun math-mul-bignum (a b)
3004 (and a b
3005 (let* ((sum (if (<= (car b) 1)
3006 (if (= (car b) 0)
3007 (list 0)
3008 (copy-sequence a))
3009 (math-mul-bignum-digit a (car b) 0)))
3010 (sump sum) c d aa ss prod)
3011 (while (setq b (cdr b))
3012 (setq ss (setq sump (or (cdr sump) (setcdr sump (list 0))))
3013 d (car b)
3014 c 0
3015 aa a)
3016 (while (progn
3017 (setcar ss (% (setq prod (+ (+ (car ss) (* (car aa) d))
3018 c)) math-bignum-digit-size))
3019 (setq aa (cdr aa)))
3020 (setq c (/ prod math-bignum-digit-size)
3021 ss (or (cdr ss) (setcdr ss (list 0)))))
3022 (if (>= prod math-bignum-digit-size)
3023 (if (cdr ss)
3024 (setcar (cdr ss) (+ (/ prod math-bignum-digit-size) (car (cdr ss))))
3025 (setcdr ss (list (/ prod math-bignum-digit-size))))))
3026 sum)))
3027
3028 ;;; Multiply digit list A by digit D. [L L D D; l l D D]
3029 (defun math-mul-bignum-digit (a d c)
3030 (if a
3031 (if (<= d 1)
3032 (and (= d 1) a)
3033 (let* ((a (copy-sequence a)) (aa a) prod)
3034 (while (progn
3035 (setcar aa
3036 (% (setq prod (+ (* (car aa) d) c))
3037 math-bignum-digit-size))
3038 (cdr aa))
3039 (setq aa (cdr aa)
3040 c (/ prod math-bignum-digit-size)))
3041 (if (>= prod math-bignum-digit-size)
3042 (setcdr aa (list (/ prod math-bignum-digit-size))))
3043 a))
3044 (and (> c 0)
3045 (list c))))
3046
3047
3048 ;;; Compute the integer (quotient . remainder) of A and B, which may be
3049 ;;; small or big integers. Type and consistency of truncation is undefined
3050 ;;; if A or B is negative. B must be nonzero. [I.I I I] [Public]
3051 (defun math-idivmod (a b)
3052 (if (eq b 0)
3053 (math-reject-arg a "*Division by zero"))
3054 (if (or (consp a) (consp b))
3055 (if (and (natnump b) (< b math-bignum-digit-size))
3056 (let ((res (math-div-bignum-digit (cdr a) b)))
3057 (cons
3058 (math-normalize (cons (car a) (car res)))
3059 (cdr res)))
3060 (or (consp a) (setq a (math-bignum a)))
3061 (or (consp b) (setq b (math-bignum b)))
3062 (let ((res (math-div-bignum (cdr a) (cdr b))))
3063 (cons
3064 (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
3065 (car res)))
3066 (math-normalize (cons (car a) (cdr res))))))
3067 (cons (/ a b) (% a b))))
3068
3069 (defun math-quotient (a b) ; [I I I] [Public]
3070 (if (and (not (consp a)) (not (consp b)))
3071 (if (= b 0)
3072 (math-reject-arg a "*Division by zero")
3073 (/ a b))
3074 (if (and (natnump b) (< b math-bignum-digit-size))
3075 (if (= b 0)
3076 (math-reject-arg a "*Division by zero")
3077 (math-normalize (cons (car a)
3078 (car (math-div-bignum-digit (cdr a) b)))))
3079 (or (consp a) (setq a (math-bignum a)))
3080 (or (consp b) (setq b (math-bignum b)))
3081 (let* ((alen (1- (length a)))
3082 (blen (1- (length b)))
3083 (d (/ math-bignum-digit-size (1+ (nth (1- blen) (cdr b)))))
3084 (res (math-div-bignum-big (math-mul-bignum-digit (cdr a) d 0)
3085 (math-mul-bignum-digit (cdr b) d 0)
3086 alen blen)))
3087 (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
3088 (car res)))))))
3089
3090
3091 ;;; Divide a bignum digit list by another. [l.l l L]
3092 ;;; The following division algorithm is borrowed from Knuth vol. II, sec. 4.3.1
3093 (defun math-div-bignum (a b)
3094 (if (cdr b)
3095 (let* ((alen (length a))
3096 (blen (length b))
3097 (d (/ math-bignum-digit-size (1+ (nth (1- blen) b))))
3098 (res (math-div-bignum-big (math-mul-bignum-digit a d 0)
3099 (math-mul-bignum-digit b d 0)
3100 alen blen)))
3101 (if (= d 1)
3102 res
3103 (cons (car res)
3104 (car (math-div-bignum-digit (cdr res) d)))))
3105 (let ((res (math-div-bignum-digit a (car b))))
3106 (cons (car res) (list (cdr res))))))
3107
3108 ;;; Divide a bignum digit list by a digit. [l.D l D]
3109 (defun math-div-bignum-digit (a b)
3110 (if a
3111 (let* ((res (math-div-bignum-digit (cdr a) b))
3112 (num (+ (* (cdr res) math-bignum-digit-size) (car a))))
3113 (cons
3114 (cons (/ num b) (car res))
3115 (% num b)))
3116 '(nil . 0)))
3117
3118 (defun math-div-bignum-big (a b alen blen) ; [l.l l L]
3119 (if (< alen blen)
3120 (cons nil a)
3121 (let* ((res (math-div-bignum-big (cdr a) b (1- alen) blen))
3122 (num (cons (car a) (cdr res)))
3123 (res2 (math-div-bignum-part num b blen)))
3124 (cons
3125 (cons (car res2) (car res))
3126 (cdr res2)))))
3127
3128 (defun math-div-bignum-part (a b blen) ; a < b*math-bignum-digit-size [D.l l L]
3129 (let* ((num (+ (* (or (nth blen a) 0) math-bignum-digit-size)
3130 (or (nth (1- blen) a) 0)))
3131 (den (nth (1- blen) b))
3132 (guess (min (/ num den) (1- math-bignum-digit-size))))
3133 (math-div-bignum-try a b (math-mul-bignum-digit b guess 0) guess)))
3134
3135 (defun math-div-bignum-try (a b c guess) ; [D.l l l D]
3136 (let ((rem (math-sub-bignum a c)))
3137 (if (eq rem 'neg)
3138 (math-div-bignum-try a b (math-sub-bignum c b) (1- guess))
3139 (cons guess rem))))
3140
3141
3142 ;;; Compute the quotient of A and B. [O O N] [Public]
3143 (defun math-div (a b)
3144 (or
3145 (and (Math-zerop b)
3146 (require 'calc-ext)
3147 (math-div-by-zero a b))
3148 (and (Math-zerop a) (not (eq (car-safe b) 'mod))
3149 (if (Math-scalarp b)
3150 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
3151 (require 'calc-ext)
3152 (math-div-zero a b)))
3153 (and (Math-objvecp a) (Math-objvecp b)
3154 (or
3155 (and (Math-integerp a) (Math-integerp b)
3156 (let ((q (math-idivmod a b)))
3157 (if (eq (cdr q) 0)
3158 (car q)
3159 (if calc-prefer-frac
3160 (progn
3161 (require 'calc-ext)
3162 (math-make-frac a b))
3163 (math-div-float (math-make-float a 0)
3164 (math-make-float b 0))))))
3165 (and (Math-ratp a) (Math-ratp b)
3166 (require 'calc-ext)
3167 (calc-div-fractions a b))
3168 (and (Math-realp a) (Math-realp b)
3169 (progn
3170 (or (and (consp a) (eq (car a) 'float))
3171 (setq a (math-float a)))
3172 (or (and (consp b) (eq (car b) 'float))
3173 (setq b (math-float b)))
3174 (math-div-float a b)))
3175 (and (require 'calc-ext)
3176 (math-div-objects-fancy a b))))
3177 (and (require 'calc-ext)
3178 (math-div-symb-fancy a b))))
3179
3180 (defun math-div-float (a b) ; [F F F]
3181 (let ((ldiff (max (- (1+ calc-internal-prec)
3182 (- (math-numdigs (nth 1 a)) (math-numdigs (nth 1 b))))
3183 0)))
3184 (math-make-float (math-quotient (math-scale-int (nth 1 a) ldiff) (nth 1 b))
3185 (- (- (nth 2 a) (nth 2 b)) ldiff))))
3186
3187
3188
3189
3190 (defvar calc-selection-cache-entry)
3191 ;;; Format the number A as a string. [X N; X Z] [Public]
3192 (defun math-format-stack-value (entry)
3193 (setq calc-selection-cache-entry calc-selection-cache-default-entry)
3194 (let* ((a (car entry))
3195 (math-comp-selected (nth 2 entry))
3196 (c (cond ((null a) "<nil>")
3197 ((eq calc-display-raw t) (format "%s" a))
3198 ((stringp a) a)
3199 ((eq a 'top-of-stack) (propertize "." 'font-lock-face 'bold))
3200 (calc-prepared-composition
3201 calc-prepared-composition)
3202 ((and (Math-scalarp a)
3203 (memq calc-language '(nil flat unform))
3204 (null math-comp-selected))
3205 (math-format-number a))
3206 (t (require 'calc-ext)
3207 (math-compose-expr a 0))))
3208 (off (math-stack-value-offset c))
3209 s w)
3210 (and math-comp-selected (setq calc-any-selections t))
3211 (setq w (cdr off)
3212 off (car off))
3213 (when (> off 0)
3214 (setq c (math-comp-concat (make-string off ?\s) c)))
3215 (or (equal calc-left-label "")
3216 (setq c (math-comp-concat (if (eq a 'top-of-stack)
3217 (make-string (length calc-left-label) ?\s)
3218 calc-left-label)
3219 c)))
3220 (when calc-line-numbering
3221 (setq c (math-comp-concat (if (eq calc-language 'big)
3222 (if math-comp-selected
3223 '(tag t "1: ")
3224 "1: ")
3225 " ")
3226 c)))
3227 (unless (or (equal calc-right-label "")
3228 (eq a 'top-of-stack))
3229 (require 'calc-ext)
3230 (setq c (list 'horiz c
3231 (make-string (max (- w (math-comp-width c)
3232 (length calc-right-label)) 0) ?\s)
3233 '(break -1)
3234 calc-right-label)))
3235 (setq s (if (stringp c)
3236 (if calc-display-raw
3237 (prin1-to-string c)
3238 c)
3239 (math-composition-to-string c w)))
3240 (when calc-language-output-filter
3241 (setq s (funcall calc-language-output-filter s)))
3242 (if (eq calc-language 'big)
3243 (setq s (concat s "\n"))
3244 (when calc-line-numbering
3245 (setq s (concat "1:" (substring s 2)))))
3246 (setcar (cdr entry) (calc-count-lines s))
3247 s))
3248
3249 ;; The variables math-svo-c, math-svo-wid and math-svo-off are local
3250 ;; to math-stack-value-offset, but are used by math-stack-value-offset-fancy
3251 ;; in calccomp.el.
3252
3253 (defun math-stack-value-offset (math-svo-c)
3254 (let* ((num (if calc-line-numbering 4 0))
3255 (math-svo-wid (calc-window-width))
3256 math-svo-off)
3257 (if calc-display-just
3258 (progn
3259 (require 'calc-ext)
3260 (math-stack-value-offset-fancy))
3261 (setq math-svo-off (or calc-display-origin 0))
3262 (when (integerp calc-line-breaking)
3263 (setq math-svo-wid calc-line-breaking)))
3264 (cons (max (- math-svo-off (length calc-left-label)) 0)
3265 (+ math-svo-wid num))))
3266
3267 (defun calc-count-lines (s)
3268 (let ((pos 0)
3269 (num 1))
3270 (while (setq pos (string-match "\n" s pos))
3271 (setq pos (1+ pos)
3272 num (1+ num)))
3273 num))
3274
3275 (defun math-format-value (a &optional w)
3276 (if (and (Math-scalarp a)
3277 (memq calc-language '(nil flat unform)))
3278 (math-format-number a)
3279 (require 'calc-ext)
3280 (let ((calc-line-breaking nil))
3281 (math-composition-to-string (math-compose-expr a 0) w))))
3282
3283 (defun calc-window-width ()
3284 (if calc-embedded-info
3285 (let ((win (get-buffer-window (aref calc-embedded-info 0))))
3286 (1- (if win (window-width win) (frame-width))))
3287 (- (window-width (get-buffer-window (current-buffer)))
3288 (if calc-line-numbering 5 1))))
3289
3290 (defun math-comp-concat (c1 c2)
3291 (if (and (stringp c1) (stringp c2))
3292 (concat c1 c2)
3293 (list 'horiz c1 c2)))
3294
3295
3296
3297 ;;; Format an expression as a one-line string suitable for re-reading.
3298
3299 (defun math-format-flat-expr (a prec)
3300 (cond
3301 ((or (not (or (consp a) (integerp a)))
3302 (eq calc-display-raw t))
3303 (let ((print-escape-newlines t))
3304 (concat "'" (prin1-to-string a))))
3305 ((Math-scalarp a)
3306 (let ((calc-group-digits nil)
3307 (calc-point-char ".")
3308 (calc-frac-format (if (> (length (car calc-frac-format)) 1)
3309 '("::" nil) '(":" nil)))
3310 (calc-complex-format nil)
3311 (calc-hms-format "%s@ %s' %s\"")
3312 (calc-language nil))
3313 (math-format-number a)))
3314 (t
3315 (require 'calc-ext)
3316 (math-format-flat-expr-fancy a prec))))
3317
3318
3319
3320 ;;; Format a number as a string.
3321 (defun math-format-number (a &optional prec) ; [X N] [Public]
3322 (cond
3323 ((eq calc-display-raw t) (format "%s" a))
3324 ((and (nth 1 calc-frac-format) (Math-integerp a))
3325 (require 'calc-ext)
3326 (math-format-number (math-adjust-fraction a)))
3327 ((integerp a)
3328 (if (not (or calc-group-digits calc-leading-zeros))
3329 (if (= calc-number-radix 10)
3330 (int-to-string a)
3331 (if (< a 0)
3332 (concat "-" (math-format-number (- a)))
3333 (require 'calc-ext)
3334 (if math-radix-explicit-format
3335 (if calc-radix-formatter
3336 (funcall calc-radix-formatter
3337 calc-number-radix
3338 (if (= calc-number-radix 2)
3339 (math-format-binary a)
3340 (math-format-radix a)))
3341 (format "%d#%s" calc-number-radix
3342 (if (= calc-number-radix 2)
3343 (math-format-binary a)
3344 (math-format-radix a))))
3345 (math-format-radix a))))
3346 (math-format-number (math-bignum a))))
3347 ((stringp a) a)
3348 ((not (consp a)) (prin1-to-string a))
3349 ((eq (car a) 'bigpos) (math-format-bignum (cdr a)))
3350 ((eq (car a) 'bigneg) (concat "-" (math-format-bignum (cdr a))))
3351 ((and (eq (car a) 'float) (= calc-number-radix 10))
3352 (if (Math-integer-negp (nth 1 a))
3353 (concat "-" (math-format-number (math-neg a)))
3354 (let ((mant (nth 1 a))
3355 (exp (nth 2 a))
3356 (fmt (car calc-float-format))
3357 (figs (nth 1 calc-float-format))
3358 (point calc-point-char)
3359 str)
3360 (if (and (eq fmt 'fix)
3361 (or (and (< figs 0) (setq figs (- figs)))
3362 (> (+ exp (math-numdigs mant)) (- figs))))
3363 (progn
3364 (setq mant (math-scale-rounding mant (+ exp figs))
3365 str (if (integerp mant)
3366 (int-to-string mant)
3367 (math-format-bignum-decimal (cdr mant))))
3368 (if (<= (length str) figs)
3369 (setq str (concat (make-string (1+ (- figs (length str))) ?0)
3370 str)))
3371 (if (> figs 0)
3372 (setq str (concat (substring str 0 (- figs)) point
3373 (substring str (- figs))))
3374 (setq str (concat str point)))
3375 (when calc-group-digits
3376 (require 'calc-ext)
3377 (setq str (math-group-float str))))
3378 (when (< figs 0)
3379 (setq figs (+ calc-internal-prec figs)))
3380 (when (> figs 0)
3381 (let ((adj (- figs (math-numdigs mant))))
3382 (when (< adj 0)
3383 (setq mant (math-scale-rounding mant adj)
3384 exp (- exp adj)))))
3385 (setq str (if (integerp mant)
3386 (int-to-string mant)
3387 (math-format-bignum-decimal (cdr mant))))
3388 (let* ((len (length str))
3389 (dpos (+ exp len)))
3390 (if (and (eq fmt 'float)
3391 (<= dpos (+ calc-internal-prec calc-display-sci-high))
3392 (>= dpos (+ calc-display-sci-low 2)))
3393 (progn
3394 (cond
3395 ((= dpos 0)
3396 (setq str (concat "0" point str)))
3397 ((and (<= exp 0) (> dpos 0))
3398 (setq str (concat (substring str 0 dpos) point
3399 (substring str dpos))))
3400 ((> exp 0)
3401 (setq str (concat str (make-string exp ?0) point)))
3402 (t ; (< dpos 0)
3403 (setq str (concat "0" point
3404 (make-string (- dpos) ?0) str))))
3405 (when calc-group-digits
3406 (require 'calc-ext)
3407 (setq str (math-group-float str))))
3408 (let* ((eadj (+ exp len))
3409 (scale (if (eq fmt 'eng)
3410 (1+ (math-mod (+ eadj 300002) 3))
3411 1)))
3412 (if (> scale (length str))
3413 (setq str (concat str (make-string (- scale (length str))
3414 ?0))))
3415 (if (< scale (length str))
3416 (setq str (concat (substring str 0 scale) point
3417 (substring str scale))))
3418 (when calc-group-digits
3419 (require 'calc-ext)
3420 (setq str (math-group-float str)))
3421 (setq str (format (if (memq calc-language '(math maple))
3422 (if (and prec (> prec 191))
3423 "(%s*10.^%d)" "%s*10.^%d")
3424 "%se%d")
3425 str (- eadj scale)))))))
3426 str)))
3427 (t
3428 (require 'calc-ext)
3429 (math-format-number-fancy a prec))))
3430
3431 (defun math-format-bignum (a) ; [X L]
3432 (if (and (= calc-number-radix 10)
3433 (not calc-leading-zeros)
3434 (not calc-group-digits))
3435 (math-format-bignum-decimal a)
3436 (require 'calc-ext)
3437 (math-format-bignum-fancy a)))
3438
3439 (defun math-format-bignum-decimal (a) ; [X L]
3440 (if a
3441 (let ((s ""))
3442 (while (cdr (cdr a))
3443 (setq s (concat
3444 (format
3445 (concat "%0"
3446 (number-to-string (* 2 math-bignum-digit-length))
3447 "d")
3448 (+ (* (nth 1 a) math-bignum-digit-size) (car a))) s)
3449 a (cdr (cdr a))))
3450 (concat (int-to-string
3451 (+ (* (or (nth 1 a) 0) math-bignum-digit-size) (car a))) s))
3452 "0"))
3453
3454
3455
3456 ;;; Parse a simple number in string form. [N X] [Public]
3457 (defun math-read-number (s)
3458 "Convert the string S into a Calc number."
3459 (math-normalize
3460 (cond
3461
3462 ;; Integers (most common case)
3463 ((string-match "\\` *\\([0-9]+\\) *\\'" s)
3464 (let ((digs (math-match-substring s 1)))
3465 (if (and (eq calc-language 'c)
3466 (> (length digs) 1)
3467 (eq (aref digs 0) ?0))
3468 (math-read-number (concat "8#" digs))
3469 (if (<= (length digs) (* 2 math-bignum-digit-length))
3470 (string-to-number digs)
3471 (cons 'bigpos (math-read-bignum digs))))))
3472
3473 ;; Clean up the string if necessary
3474 ((string-match "\\`\\(.*\\)[ \t\n]+\\([^\001]*\\)\\'" s)
3475 (math-read-number (concat (math-match-substring s 1)
3476 (math-match-substring s 2))))
3477
3478 ;; Plus and minus signs
3479 ((string-match "^[-_+]\\(.*\\)$" s)
3480 (let ((val (math-read-number (math-match-substring s 1))))
3481 (and val (if (eq (aref s 0) ?+) val (math-neg val)))))
3482
3483 ;; Forms that require extensions module
3484 ((string-match "[^-+0-9eE.]" s)
3485 (require 'calc-ext)
3486 (math-read-number-fancy s))
3487
3488 ;; Decimal point
3489 ((string-match "^\\([0-9]*\\)\\.\\([0-9]*\\)$" s)
3490 (let ((int (math-match-substring s 1))
3491 (frac (math-match-substring s 2)))
3492 (let ((ilen (length int))
3493 (flen (length frac)))
3494 (let ((int (if (> ilen 0) (math-read-number int) 0))
3495 (frac (if (> flen 0) (math-read-number frac) 0)))
3496 (and int frac (or (> ilen 0) (> flen 0))
3497 (list 'float
3498 (math-add (math-scale-int int flen) frac)
3499 (- flen)))))))
3500
3501 ;; "e" notation
3502 ((string-match "^\\(.*\\)[eE]\\([-+]?[0-9]+\\)$" s)
3503 (let ((mant (math-match-substring s 1))
3504 (exp (math-match-substring s 2)))
3505 (let ((mant (if (> (length mant) 0) (math-read-number mant) 1))
3506 (exp (if (<= (length exp) (if (memq (aref exp 0) '(?+ ?-)) 8 7))
3507 (string-to-number exp))))
3508 (and mant exp (Math-realp mant) (> exp -4000000) (< exp 4000000)
3509 (let ((mant (math-float mant)))
3510 (list 'float (nth 1 mant) (+ (nth 2 mant) exp)))))))
3511
3512 ;; Syntax error!
3513 (t nil))))
3514
3515 ;;; Parse a very simple number, keeping all digits.
3516 (defun math-read-number-simple (s)
3517 "Convert the string S into a Calc number.
3518 S is assumed to be a simple number (integer or float without an exponent)
3519 and all digits are kept, regardless of Calc's current precision."
3520 (cond
3521 ;; Integer
3522 ((string-match "^[0-9]+$" s)
3523 (if (string-match "^\\(0+\\)" s)
3524 (setq s (substring s (match-end 0))))
3525 (if (<= (length s) (* 2 math-bignum-digit-length))
3526 (string-to-number s)
3527 (cons 'bigpos (math-read-bignum s))))
3528 ;; Minus sign
3529 ((string-match "^-[0-9]+$" s)
3530 (if (<= (length s) (1+ (* 2 math-bignum-digit-length)))
3531 (string-to-number s)
3532 (cons 'bigneg (math-read-bignum (substring s 1)))))
3533 ;; Decimal point
3534 ((string-match "^\\(-?[0-9]*\\)\\.\\([0-9]*\\)$" s)
3535 (let ((int (math-match-substring s 1))
3536 (frac (math-match-substring s 2)))
3537 (list 'float (math-read-number-simple (concat int frac))
3538 (- (length frac)))))
3539 ;; Syntax error!
3540 (t nil)))
3541
3542 (defun math-match-substring (s n)
3543 (if (match-beginning n)
3544 (substring s (match-beginning n) (match-end n))
3545 ""))
3546
3547 (defun math-read-bignum (s) ; [l X]
3548 (if (> (length s) math-bignum-digit-length)
3549 (cons (string-to-number (substring s (- math-bignum-digit-length)))
3550 (math-read-bignum (substring s 0 (- math-bignum-digit-length))))
3551 (list (string-to-number s))))
3552
3553 (defconst math-standard-opers
3554 '( ( "_" calcFunc-subscr 1200 1201 )
3555 ( "%" calcFunc-percent 1100 -1 )
3556 ( "u!" calcFunc-lnot -1 1000 )
3557 ( "mod" mod 400 400 185 )
3558 ( "+/-" sdev 300 300 185 )
3559 ( "!!" calcFunc-dfact 210 -1 )
3560 ( "!" calcFunc-fact 210 -1 )
3561 ( "^" ^ 201 200 )
3562 ( "**" ^ 201 200 )
3563 ( "u+" ident -1 197 )
3564 ( "u-" neg -1 197 )
3565 ( "/" / 190 191 )
3566 ( "%" % 190 191 )
3567 ( "\\" calcFunc-idiv 190 191 )
3568 ( "+" + 180 181 )
3569 ( "-" - 180 181 )
3570 ( "|" | 170 171 )
3571 ( "<" calcFunc-lt 160 161 )
3572 ( ">" calcFunc-gt 160 161 )
3573 ( "<=" calcFunc-leq 160 161 )
3574 ( ">=" calcFunc-geq 160 161 )
3575 ( "=" calcFunc-eq 160 161 )
3576 ( "==" calcFunc-eq 160 161 )
3577 ( "!=" calcFunc-neq 160 161 )
3578 ( "&&" calcFunc-land 110 111 )
3579 ( "||" calcFunc-lor 100 101 )
3580 ( "?" (math-read-if) 91 90 )
3581 ( "!!!" calcFunc-pnot -1 85 )
3582 ( "&&&" calcFunc-pand 80 81 )
3583 ( "|||" calcFunc-por 75 76 )
3584 ( ":=" calcFunc-assign 51 50 )
3585 ( "::" calcFunc-condition 45 46 )
3586 ( "=>" calcFunc-evalto 40 41 )
3587 ( "=>" calcFunc-evalto 40 -1 )))
3588
3589 (defun math-standard-ops ()
3590 (if calc-multiplication-has-precedence
3591 (cons
3592 '( "*" * 196 195 )
3593 (cons
3594 '( "2x" * 196 195 )
3595 math-standard-opers))
3596 (cons
3597 '( "*" * 190 191 )
3598 (cons
3599 '( "2x" * 190 191 )
3600 math-standard-opers))))
3601
3602 (defvar math-expr-opers (math-standard-ops))
3603
3604 (defun math-standard-ops-p ()
3605 (let ((meo (caar math-expr-opers)))
3606 (and (stringp meo)
3607 (string= meo "*"))))
3608
3609 (defun math-expr-ops ()
3610 (if (math-standard-ops-p)
3611 (math-standard-ops)
3612 math-expr-opers))
3613
3614 ;;;###autoload
3615 (defun calc-grab-region (top bot arg)
3616 "Parse the region as a vector of numbers and push it on the Calculator stack."
3617 (interactive "r\nP")
3618 (require 'calc-ext)
3619 (calc-do-grab-region top bot arg))
3620
3621 ;;;###autoload
3622 (defun calc-grab-rectangle (top bot arg)
3623 "Parse a rectangle as a matrix of numbers and push it on the Calculator stack."
3624 (interactive "r\nP")
3625 (require 'calc-ext)
3626 (calc-do-grab-rectangle top bot arg))
3627
3628 (defun calc-grab-sum-down (top bot arg)
3629 "Parse a rectangle as a matrix of numbers and sum its columns."
3630 (interactive "r\nP")
3631 (require 'calc-ext)
3632 (calc-do-grab-rectangle top bot arg 'calcFunc-reduced))
3633
3634 (defun calc-grab-sum-across (top bot arg)
3635 "Parse a rectangle as a matrix of numbers and sum its rows."
3636 (interactive "r\nP")
3637 (require 'calc-ext)
3638 (calc-do-grab-rectangle top bot arg 'calcFunc-reducea))
3639
3640
3641 ;;;###autoload
3642 (defun calc-embedded (arg &optional end obeg oend)
3643 "Start Calc Embedded mode on the formula surrounding point."
3644 (interactive "P")
3645 (require 'calc-ext)
3646 (calc-do-embedded arg end obeg oend))
3647
3648 ;;;###autoload
3649 (defun calc-embedded-activate (&optional arg cbuf)
3650 "Scan the current editing buffer for all embedded := and => formulas.
3651 Also looks for the equivalent TeX words, \\gets and \\evalto."
3652 (interactive "P")
3653 (calc-do-embedded-activate arg cbuf))
3654
3655 (defun calc-user-invocation ()
3656 (interactive)
3657 (unless calc-invocation-macro
3658 (error "Use `Z I' inside Calc to define a `C-x * Z' keyboard macro"))
3659 (execute-kbd-macro calc-invocation-macro nil))
3660
3661 ;;; User-programmability.
3662
3663 ;;;###autoload
3664 (defmacro defmath (func args &rest body) ; [Public]
3665 (require 'calc-ext)
3666 (math-do-defmath func args body))
3667
3668 ;;; Functions needed for Lucid Emacs support.
3669
3670 (defun calc-read-key (&optional optkey)
3671 (cond ((featurep 'xemacs)
3672 (let ((event (next-command-event)))
3673 (let ((key (event-to-character event t t)))
3674 (or key optkey (error "Expected a plain keystroke"))
3675 (cons key event))))
3676 (t
3677 (let ((key (read-event)))
3678 (cons key key)))))
3679
3680 (defun calc-unread-command (&optional input)
3681 (if (featurep 'xemacs)
3682 (setq unread-command-event
3683 (if (integerp input) (character-to-event input)
3684 (or input last-command-event)))
3685 (push (or input last-command-event) unread-command-events)))
3686
3687 (defun calc-clear-unread-commands ()
3688 (if (featurep 'xemacs)
3689 (setq unread-command-event nil)
3690 (setq unread-command-events nil)))
3691
3692 (when calc-always-load-extensions
3693 (require 'calc-ext)
3694 (calc-load-everything))
3695
3696
3697 (run-hooks 'calc-load-hook)
3698
3699 (provide 'calc)
3700
3701 ;; arch-tag: 0c3b170c-4ce6-4eaf-8d9b-5834d1fe938f
3702 ;;; calc.el ends here