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