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