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