calc.el 113 KB
Newer Older
1
;;; calc.el --- the GNU Emacs calculator
2

3
;; Copyright (C) 1990, 1991, 1992, 1993, 2001, 2002 Free Software Foundation, Inc.
4 5 6 7

;; Author: David Gillespie <daveg@synaptics.com>
;; Maintainer: Colin Walters <walters@debian.org>
;; Keywords: convenience, extensions
8
;; Version: 2.02g
Eli Zaretskii's avatar
Eli Zaretskii committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

;; This file is part of GNU Emacs.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY.  No author or distributor
;; accepts responsibility to anyone for the consequences of using it
;; or for whether it serves any particular purpose or works at all,
;; unless he says so in writing.  Refer to the GNU Emacs General Public
;; License for full details.

;; Everyone is granted permission to copy, modify and redistribute
;; GNU Emacs, but only under the conditions described in the
;; GNU Emacs General Public License.   A copy of this license is
;; supposed to have been given to you along with GNU Emacs so you
;; can know your rights and responsibilities.  It should be in a
;; file named COPYING.  Among other things, the copyright notice
;; and this notice must be preserved on all copies.

27
;;; Commentary:
Eli Zaretskii's avatar
Eli Zaretskii committed
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
;; Calc is split into many files.  This file is the main entry point.
;; This file includes autoload commands for various other basic Calc
;; facilities.  The more advanced features are based in calc-ext, which
;; in turn contains autoloads for the rest of the Calc files.  This
;; odd set of interactions is designed to make Calc's loading time
;; be as short as possible when only simple calculations are needed.

;; Original author's address:
;;  Dave Gillespie, daveg@synaptics.com, uunet!synaptx!daveg.
;;  Synaptics, Inc., 2698 Orchard Parkway, San Jose, CA 95134.
;;
;; The old address daveg@csvax.cs.caltech.edu will continue to
;; work for the foreseeable future.
;;
;; Bug reports and suggestions are always welcome!  (Type M-x
;; report-calc-bug to send them).

;; All functions, macros, and Lisp variables defined here begin with one
;; of the prefixes "math", "Math", or "calc", with the exceptions of
;; "full-calc", "full-calc-keypad", "another-calc", "quick-calc",
;; "report-calc-bug", and "defmath".  User-accessible variables begin
;; with "var-".

;;; TODO:

;;   Fix rewrite mechanism to do less gratuitous rearrangement of terms.
;;   Implement a pattern-based "refers" predicate.
;;
;;   Make it possible to Undo a selection command.
;;   Figure out how to allow selecting rows of matrices.
;;   If cursor was in selection before, move it after j n, j p, j L, etc.
;;   Consider reimplementing calc-delete-selection using rewrites.
;;
;;   Implement line-breaking in non-flat compositions (is this desirable?).
;;   Implement matrix formatting with multi-line components.
;;
;;   Have "Z R" define a user command based on a set of rewrite rules.
;;   Support "incf" and "decf" in defmath definitions.
;;   Have defmath generate calls to calc-binary-op or calc-unary-op.
;;   Make some way to define algebraic functions using keyboard macros.
;;
;;   Allow calc-word-size=0 => Common Lisp-style signed bitwise arithmetic.
;;   Consider digamma function (and thus arb. prec. Euler's gamma constant).
;;   May as well make continued-fractions stuff available to the user.
;;
;;   How about matrix eigenvalues, SVD, pseudo-inverse, etc.?
;;   Should cache matrix inverses as well as decompositions.
;;   If dividing by a non-square matrix, use least-squares automatically.
;;   Consider supporting matrix exponentials.
;;
;;   Have ninteg detect and work around singularities at the endpoints.
;;   Use an adaptive subdivision algorithm for ninteg.
;;   Provide nsum and nprod to go along with ninteg.
;;
;;   Handle TeX-mode parsing of \matrix{ ... } where ... contains braces.
;;   Support AmS-TeX's \{d,t,}frac, \{d,t,}binom notations.
;;   Format and parse sums and products in Eqn and Math modes.
;;
;;   Get math-read-big-expr to read sums, products, etc.
;;   Change calc-grab-region to use math-read-big-expr.
;;   Have a way to define functions using := in Embedded Mode.
;;
;;   Support polar plotting with GNUPLOT.
;;   Make a calc-graph-histogram function.
;;
;;   Replace hokey formulas for complex functions with formulas designed
;;      to minimize roundoff while maintaining the proper branch cuts.
;;   Test accuracy of advanced math functions over whole complex plane.
;;   Extend Bessel functions to provide arbitrary precision.
;;   Extend advanced math functions to handle error forms and intervals.
;;   Provide a better implementation for math-sin-cos-raw.
;;   Provide a better implementation for math-hypot.
;;   Provide a better implementation for math-make-frac.
;;   Provide a better implementation for calcFunc-prfac.
;;   Provide a better implementation for calcFunc-factor.
;;
;;   Provide more examples in the tutorial section of the manual.
;;   Cover in the tutorial:  simplification modes, declarations,
;;       bitwise stuff, selections, matrix mapping, financial functions.
;;   Provide more Lisp programming examples in the manual.
;;   Finish the Internals section of the manual (and bring it up to date).
;;
;;   Tim suggests adding spreadsheet-like features.
;;   Implement language modes for Gnuplot, Lisp, Ada, APL, ...?
;;
;; For atan series, if x > tan(pi/12) (about 0.268) reduce using the identity
;;   atan(x) = atan((x * sqrt(3) - 1) / (sqrt(3) + x)) + pi/6.
;;
;; A better integration algorithm:
;;   Use breadth-first instead of depth-first search, as follows:
;;	The integral cache allows unfinished integrals in symbolic notation
;;	on the righthand side.  An entry with no unfinished integrals on the
;;	RHS is "complete"; references to it elsewhere are replaced by the
;;	integrated value.  More than one cache entry for the same integral
;;	may exist, though if one becomes complete, the others may be deleted.
;;	The integrator works by using every applicable rule (such as
;;	substitution, parts, linearity, etc.) to generate possible righthand
;;	sides, all of which are entered into the cache.  Now, as long as the
;;	target integral is not complete (and the time limit has not run out)
;;	choose an incomplete integral from the cache and, for every integral
;;	appearing in its RHS's, add those integrals to the cache using the
;;	same substitition, parts, etc. rules.  The cache should be organized
;;	as a priority queue, choosing the "simplest" incomplete integral at
;;	each step, or choosing randomly among equally simple integrals.
;;	Simplicity equals small size, and few steps removed from the original
;;	target integral.  Note that when the integrator finishes, incomplete
;;	integrals can be left in the cache, so the algorithm can start where
;;	it left off if another similar integral is later requested.
;;   Breadth-first search would avoid the nagging problem of, e.g., whether
;;   to use parts or substitution first, and which decomposition is best.
;;   All are tried, and any path that diverges will quickly be put on the
;;   back burner by the priority queue.
;;   Note: Probably a good idea to call math-simplify-extended before
;;   measuring a formula's simplicity.

;; From: "Robert J. Chassell" <bob@rattlesnake.com>
;; Subject: Re: fix for `Cannot open load file: calc-alg-3'
;; To: walters@debian.org
;; Date: Sat, 24 Nov 2001 21:44:21 +0000 (UTC)
;; 
;; Could you add logistic curve fitting to the current list?
;; 
;; (I guess the key binding for a logistic curve would have to be `s'
;; since a logistic curve is an `s' curve; both `l' and `L' are already
;; taken for logarithms.)
;; 
;; Here is the current list for curve fitting;
;; 
;;     `1'
;;          Linear or multilinear.  a + b x + c y + d z.
;; 
;;     `2-9'
;;          Polynomials.  a + b x + c x^2 + d x^3.
;; 
;;     `e'
;;          Exponential.  a exp(b x) exp(c y).
;; 
;;     `E'
;;          Base-10 exponential.  a 10^(b x) 10^(c y).
;; 
;;     `x'
;;          Exponential (alternate notation).  exp(a + b x + c y).
;; 
;;     `X'
;;          Base-10 exponential (alternate).  10^(a + b x + c y).
;; 
;;     `l'
;;          Logarithmic.  a + b ln(x) + c ln(y).
;; 
;;     `L'
;;          Base-10 logarithmic.  a + b log10(x) + c log10(y).
;; 
;;     `^'
;;          General exponential.  a b^x c^y.
;; 
;;     `p'
;;          Power law.  a x^b y^c.
;; 
;;     `q'
;;          Quadratic.  a + b (x-c)^2 + d (x-e)^2.
;; 
;;     `g'
;;          Gaussian.  (a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2).
;; 
;; 
;; Logistic curves are used a great deal in ecology, and in predicting
;; human actions, such as use of different kinds of energy in a country
;; (wood, coal, oil, natural gas, etc.) or the number of scientific
;; papers a person publishes, or the number of movies made.
;; 
;; (The less information on which to base the curve, the higher the error
;; rate.  Theodore Modis ran some Monte Carlo simulations and produced
;; what may be useful set of confidence levels for different amounts of
;; initial information.)
Eli Zaretskii's avatar
Eli Zaretskii committed
203

204
;;; Code:
Eli Zaretskii's avatar
Eli Zaretskii committed
205 206

(provide 'calc)
Eli Zaretskii's avatar
Eli Zaretskii committed
207
(require 'calc-macs)
Eli Zaretskii's avatar
Eli Zaretskii committed
208 209 210 211 212 213 214 215 216

;;; The "###autoload" comment will be used by Emacs version 19 for
;;; maintaining the loaddefs.el file automatically.

;;;###autoload
(defvar calc-info-filename "calc.info"
  "*File name in which to look for the Calculator's Info documentation.")

;;;###autoload
217 218
(defvar calc-settings-file user-init-file
  "*File in which to record permanent settings; default is `user-init-file'.")
Eli Zaretskii's avatar
Eli Zaretskii committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

;;;###autoload
(defvar calc-autoload-directory nil
  "Name of directory from which additional \".elc\" files for Calc should be
loaded.  Should include a trailing \"/\".
If nil, use original installation directory.
This can safely be nil as long as the Calc files are on the load-path.")

;;;###autoload
(defvar calc-gnuplot-name "gnuplot"
  "*Name of GNUPLOT program, for calc-graph features.")

;;;###autoload
(defvar calc-gnuplot-plot-command nil
  "*Name of command for displaying GNUPLOT output; %s = file name to print.")

;;;###autoload
(defvar calc-gnuplot-print-command "lp %s"
  "*Name of command for printing GNUPLOT output; %s = file name to print.")

;; Address of the author of Calc, for use by report-calc-bug.
240
(defvar calc-bug-address "walters@debian.org")
Eli Zaretskii's avatar
Eli Zaretskii committed
241

Pavel Janík's avatar
Pavel Janík committed
242 243
;; If t, scan keymaps to find all DEL-like keys.
;; if nil, only DEL itself is mapped to calc-pop.
Eli Zaretskii's avatar
Eli Zaretskii committed
244 245 246 247 248 249 250 251 252 253 254 255
(defvar calc-scan-for-dels t)

(defvar calc-extensions-loaded nil)

;; Calculator stack.
;; Entries are 3-lists:  Formula, Height (in lines), Selection (or nil).
(defvar calc-stack '((top-of-stack 1 nil)))

;; Index into calc-stack of "top" of stack.
;; This is 1 unless calc-truncate-stack has been used.
;;(defvar calc-stack-top 1)

Pavel Janík's avatar
Pavel Janík committed
256
;; If non-nil, load the calc-ext module automatically when calc is loaded.
Eli Zaretskii's avatar
Eli Zaretskii committed
257 258
;;(defvar calc-always-load-extensions nil)

Pavel Janík's avatar
Pavel Janík committed
259
;; If non-nil, display line numbers in Calculator stack.
Eli Zaretskii's avatar
Eli Zaretskii committed
260 261
;;(defvar calc-line-numbering t)

Pavel Janík's avatar
Pavel Janík committed
262
;; If non-nil, break long values across multiple lines in Calculator stack.
Eli Zaretskii's avatar
Eli Zaretskii committed
263 264
;;(defvar calc-line-breaking t)

Pavel Janík's avatar
Pavel Janík committed
265
;; If nil, stack display is left-justified.
Eli Zaretskii's avatar
Eli Zaretskii committed
266 267 268 269 270 271 272 273 274 275 276 277 278
;; If 'right, stack display is right-justified.
;; If 'center, stack display is centered."
;;(defvar calc-display-just nil)

;; Horizontal origin of displayed stack entries.
;; In left-justified mode, this is effectively indentation.  (Default 0).
;; In right-justified mode, this is effectively window width.
;; In centered mode, center of stack entry is placed here.
;;(defvar calc-display-origin nil)

;; Radix for entry and display of numbers in calc-mode, 2-36.
;;(defvar calc-number-radix 10)

Pavel Janík's avatar
Pavel Janík committed
279
;; If non-nil, leading zeros are provided to pad integers to calc-word-size.
Eli Zaretskii's avatar
Eli Zaretskii committed
280 281
;;(defvar calc-leading-zeros nil)

Pavel Janík's avatar
Pavel Janík committed
282
;; If non-nil, group digits in large displayed integers by inserting spaces.
Eli Zaretskii's avatar
Eli Zaretskii committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296
;; If an integer, group that many digits at a time.
;; If 't', use 4 for binary and hex, 3 otherwise.
;;(defvar calc-group-digits nil)

;; The character (in the form of a string) to be used for grouping digits.
;; This is used only when calc-group-digits mode is on.
;;(defvar calc-group-char ",")

;; The character (in the form of a string) to be used as a decimal point.
;;(defvar calc-point-char ".")

;; Format of displayed fractions; a string of one or two of ":" or "/".
;;(defvar calc-frac-format '(":" nil))

Pavel Janík's avatar
Pavel Janík committed
297
;; If non-nil, prefer fractional over floating-point results.
Eli Zaretskii's avatar
Eli Zaretskii committed
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
;;(defvar calc-prefer-frac nil)

;; Format of displayed hours-minutes-seconds angles, a format string.
;; String must contain three %s marks for hours, minutes, seconds respectively.
;;(defvar calc-hms-format "%s@ %s' %s\"")

;; Format of displayed date forms.
;;(defvar calc-date-format '((H ":" mm ":" SS pp " ") Www " " Mmm " " D ", " YYYY))

;; Format to use for display of floating-point numbers in calc-mode.
;; Must be a list of one of the following forms:
;;  (float 0)      Floating point format, display full precision.
;;  (float N)      N > 0: Floating point format, at most N significant figures.
;;  (float -N)     -N < 0: Floating point format, calc-internal-prec - N figs.
;;  (fix N)        N >= 0: Fixed point format, N places after decimal point.
;;  (sci 0)        Scientific notation, full precision.
;;  (sci N)        N > 0: Scientific notation, N significant figures.
;;  (sci -N)       -N < 0: Scientific notation, calc-internal-prec - N figs.
;;  (eng 0)        Engineering notation, full precision.
;;  (eng N)        N > 0: Engineering notation, N significant figures.
;;  (eng -N)       -N < 0: Engineering notation, calc-internal-prec - N figs.
;;(defvar calc-float-format '(float 0))

;; Format to use when full precision must be displayed.
;;(defvar calc-full-float-format '(float 0))

;; Format to use for display of complex numbers in calc-mode.  Must be one of:
;;   nil            Use (x, y) form.
;;   i              Use x + yi form.
;;   j              Use x + yj form.
;;(defvar calc-complex-format nil)

;; Preferred form, either 'cplx or 'polar, for complex numbers.
;;(defvar calc-complex-mode 'cplx)

Pavel Janík's avatar
Pavel Janík committed
333
;; If nil, 1 / 0 is left unsimplified.
Eli Zaretskii's avatar
Eli Zaretskii committed
334 335 336 337
;; If 0, 1 / 0 is changed to inf (zeros are considered positive).
;; Otherwise, 1 / 0 is changed to uinf (undirected infinity).
;;(defvar calc-infinite-mode nil)

Pavel Janík's avatar
Pavel Janík committed
338
;; If non-nil, display vectors of byte-sized integers as strings.
Eli Zaretskii's avatar
Eli Zaretskii committed
339 340
;;(defvar calc-display-strings nil)

Pavel Janík's avatar
Pavel Janík committed
341
;; If nil, vector elements are left-justified.
Eli Zaretskii's avatar
Eli Zaretskii committed
342 343 344 345
;; If 'right, vector elements are right-justified.
;; If 'center, vector elements are centered."
;;(defvar calc-matrix-just 'center)

Pavel Janík's avatar
Pavel Janík committed
346
;; If non-nil, display vectors one element per line.
Eli Zaretskii's avatar
Eli Zaretskii committed
347 348
;;(defvar calc-break-vectors nil)

Pavel Janík's avatar
Pavel Janík committed
349
;; If non-nil, display long vectors in full.  If nil, use abbreviated form.
Eli Zaretskii's avatar
Eli Zaretskii committed
350 351
;;(defvar calc-full-vectors t)

Pavel Janík's avatar
Pavel Janík committed
352
;; If non-nil, display long vectors in full in the trail.
Eli Zaretskii's avatar
Eli Zaretskii committed
353 354
;;(defvar calc-full-trail-vectors t)

Pavel Janík's avatar
Pavel Janík committed
355
;; If non-nil, separate elements of displayed vectors with this string.
Eli Zaretskii's avatar
Eli Zaretskii committed
356 357
;;(defvar calc-vector-commas ",")

Pavel Janík's avatar
Pavel Janík committed
358
;; If non-nil, surround displayed vectors with these characters.
Eli Zaretskii's avatar
Eli Zaretskii committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
;;(defvar calc-vector-brackets "[]")

;; A list of code-letter symbols that control "big" matrix display.
;; If 'R is present, display inner brackets for matrices.
;; If 'O is present, display outer brackets for matrices (above/below).
;; If 'C is present, display outer brackets for matrices (centered).
;;(defvar calc-matrix-brackets '(R O))

;; Language or format for entry and display of stack values.  Must be one of:
;;   nil            Use standard Calc notation.
;;   flat           Use standard Calc notation, one-line format.
;;   big 	    Display formulas in 2-d notation (enter w/std notation).
;;   unform	    Use unformatted display: add(a, mul(b,c)).
;;   c              Use C language notation.
;;   pascal         Use Pascal language notation.
;;   fortran        Use Fortran language notation.
;;   tex            Use TeX notation.
;;   eqn	    Use eqn notation.
;;   math           Use Mathematica(tm) notation.
;;   maple	    Use Maple notation.
;;(defvar calc-language nil)

;; Numeric prefix argument for the command that set calc-language.
;;(defvar calc-language-option nil)

;; Open-parenthesis string for function call notation.
;;(defvar calc-function-open "(")

;; Close-parenthesis string for function call notation.
;;(defvar calc-function-close ")")

;; Function through which to pass strings after formatting.
;;(defvar calc-language-output-filter nil)

;; Function through which to pass strings before parsing.
;;(defvar calc-language-input-filter nil)

;; Formatting function used for non-decimal numbers.
;;(defvar calc-radix-formatter nil)

;; Label to display at left of formula.
;;(defvar calc-left-label "")

;; Label to display at right of formula.
;;(defvar calc-right-label "")

;; Minimum number of bits per word, if any, for binary operations in calc-mode.
;;(defvar calc-word-size 32)

;; Most recently used value of M in a modulo form.
;;(defvar calc-previous-modulo nil)

;; Type of simplification applied to results.
;; If 'none, results are not simplified when pushed on the stack.
;; If 'num, functions are simplified only when args are constant.
Pavel Janík's avatar
Pavel Janík committed
414
;; If nil, only fast simplifications are applied.
Eli Zaretskii's avatar
Eli Zaretskii committed
415 416 417 418 419 420
;; If 'binary, math-clip is applied if appropriate.
;; If 'alg, math-simplify is applied.
;; If 'ext, math-simplify-extended is applied.
;; If 'units, math-simplify-units is applied.
;;(defvar calc-simplify-mode nil)

Pavel Janík's avatar
Pavel Janík committed
421
;; If non-nil, recompute evalto's automatically when necessary.
Eli Zaretskii's avatar
Eli Zaretskii committed
422 423
;;(defvar calc-auto-recompute t)

Pavel Janík's avatar
Pavel Janík committed
424
;; If non-nil, display shows unformatted Lisp exprs.  (For debugging)
Eli Zaretskii's avatar
Eli Zaretskii committed
425 426 427 428 429
;;(defvar calc-display-raw nil)

;; Number of digits of internal precision for calc-mode calculations.
;;(defvar calc-internal-prec 12)

Pavel Janík's avatar
Pavel Janík committed
430
;; If non-nil, next operation is Inverse.
Eli Zaretskii's avatar
Eli Zaretskii committed
431 432
;;(defvar calc-inverse-flag nil)

Pavel Janík's avatar
Pavel Janík committed
433
;; If non-nil, next operation is Hyperbolic.
Eli Zaretskii's avatar
Eli Zaretskii committed
434 435
;;(defvar calc-hyperbolic-flag nil)

Pavel Janík's avatar
Pavel Janík committed
436
;; If non-nil, next operation should not remove its arguments from stack.
Eli Zaretskii's avatar
Eli Zaretskii committed
437 438 439 440 441 442
;;(defvar calc-keep-args-flag nil)

;; If deg, angles are in degrees; if rad, angles are in radians.
;; If hms, angles are in degrees-minutes-seconds.
;;(defvar calc-angle-mode 'deg)

Pavel Janík's avatar
Pavel Janík committed
443 444
;; If non-nil, numeric entry accepts whole algebraic expressions.
;; If nil, algebraic expressions must be preceded by "'".
Eli Zaretskii's avatar
Eli Zaretskii committed
445 446 447 448 449
;;(defvar calc-algebraic-mode nil)

;; Like calc-algebraic-mode except only affects ( and [ keys.
;;(defvar calc-incomplete-algebraic-mode nil)

Pavel Janík's avatar
Pavel Janík committed
450 451
;; If non-nil, inexact numeric computations like sqrt(2) are postponed.
;; If nil, computations on numbers always yield numbers where possible.
Eli Zaretskii's avatar
Eli Zaretskii committed
452 453 454 455 456
;;(defvar calc-symbolic-mode nil)

;; If 'matrix, variables are assumed to be matrix-valued.
;; If a number, variables are assumed to be NxN matrices.
;; If 'scalar, variables are assumed to be scalar-valued.
Pavel Janík's avatar
Pavel Janík committed
457
;; If nil, symbolic math routines make no assumptions about variables.
Eli Zaretskii's avatar
Eli Zaretskii committed
458 459
;;(defvar calc-matrix-mode nil)

Pavel Janík's avatar
Pavel Janík committed
460
;; If non-nil, shifted letter keys are prefix keys rather than normal meanings.
Eli Zaretskii's avatar
Eli Zaretskii committed
461 462 463 464 465
;;(defvar calc-shift-prefix nil)

;; Initial height of Calculator window.
;;(defvar calc-window-height 7)

Pavel Janík's avatar
Pavel Janík committed
466
;; If non-nil, M-x calc creates a window to display Calculator trail.
Eli Zaretskii's avatar
Eli Zaretskii committed
467 468
;;(defvar calc-display-trail t)

Pavel Janík's avatar
Pavel Janík committed
469 470
;; If non-nil, selected sub-formulas are shown by obscuring rest of formula.
;; If nil, selected sub-formulas are highlighted by obscuring the sub-formulas.
Eli Zaretskii's avatar
Eli Zaretskii committed
471 472
;;(defvar calc-show-selections t)

Pavel Janík's avatar
Pavel Janík committed
473 474
;; If non-nil, commands operate only on selected portions of formulas.
;; If nil, selections displayed but ignored.
Eli Zaretskii's avatar
Eli Zaretskii committed
475 476
;;(defvar calc-use-selections t)

Pavel Janík's avatar
Pavel Janík committed
477
;; If non-nil, selection hides deep structure of associative formulas.
Eli Zaretskii's avatar
Eli Zaretskii committed
478 479
;;(defvar calc-assoc-selections t)

Pavel Janík's avatar
Pavel Janík committed
480
;; If non-nil, display "Working..." for potentially slow Calculator commands.
Eli Zaretskii's avatar
Eli Zaretskii committed
481 482
;;(defvar calc-display-working-message 'lots)

Pavel Janík's avatar
Pavel Janík committed
483
;; If non-nil, automatically execute a "why" command to explain odd results.
Eli Zaretskii's avatar
Eli Zaretskii committed
484 485
;;(defvar calc-auto-why nil)

Pavel Janík's avatar
Pavel Janík committed
486
;; If non-nil, display timing information on each slow command.
Eli Zaretskii's avatar
Eli Zaretskii committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
;;(defvar calc-timing nil)

;; Floating-point numbers with this positive exponent or higher above the
;; current precision are displayed in scientific notation in calc-mode.
(defvar calc-display-sci-high 0)

;; Floating-point numbers with this negative exponent or lower are displayed
;; scientific notation in calc-mode.
(defvar calc-display-sci-low -3)


;; List of used-defined strings to append to Calculator mode line.
(defvar calc-other-modes nil)

;; List of strings for Y prefix help.
(defvar calc-Y-help-msgs nil)

Pavel Janík's avatar
Pavel Janík committed
504
;; t if calc-settings-file has been loaded yet.
Eli Zaretskii's avatar
Eli Zaretskii committed
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
(defvar calc-loaded-settings-file nil)



(defconst calc-mode-var-list '((calc-always-load-extensions nil)
			       (calc-mode-save-mode local)
			       (calc-line-numbering t)
			       (calc-line-breaking t)
			       (calc-display-just nil)
			       (calc-display-origin nil)
			       (calc-left-label "")
			       (calc-right-label "")
			       (calc-number-radix 10)
			       (calc-leading-zeros nil)
			       (calc-group-digits nil)
			       (calc-group-char ",")
			       (calc-point-char ".")
			       (calc-frac-format (":" nil))
			       (calc-prefer-frac nil)
			       (calc-hms-format "%s@ %s' %s\"")
			       (calc-date-format ((H ":" mm C SS pp " ")
						  Www " " Mmm " " D ", " YYYY))
			       (calc-standard-date-formats
				("N"
				 "<H:mm:SSpp >Www Mmm D, YYYY"
				 "D Mmm YYYY<, h:mm:SS>"
				 "Www Mmm BD< hh:mm:ss> YYYY"
				 "M/D/Y< H:mm:SSpp>"
				 "D.M.Y< h:mm:SS>"
				 "M-D-Y< H:mm:SSpp>"
				 "D-M-Y< h:mm:SS>"
				 "j<, h:mm:SS>"
				 "YYddd< hh:mm:ss>"))
			       (calc-float-format (float 0))
			       (calc-full-float-format (float 0))
			       (calc-complex-format nil)
			       (calc-matrix-just center)
			       (calc-full-vectors t)
			       (calc-full-trail-vectors t)
			       (calc-break-vectors nil)
			       (calc-vector-commas ",")
			       (calc-vector-brackets "[]")
			       (calc-matrix-brackets (R O))
			       (calc-complex-mode cplx)
			       (calc-infinite-mode nil)
			       (calc-display-strings nil)
			       (calc-simplify-mode nil)
			       (calc-auto-recompute t)
			       (calc-word-size 32)
			       (calc-previous-modulo nil)
			       (calc-display-raw nil)
			       (calc-internal-prec 12)
			       (calc-angle-mode deg)
			       (calc-algebraic-mode nil)
			       (calc-incomplete-algebraic-mode nil)
			       (calc-symbolic-mode nil)
			       (calc-matrix-mode nil)
			       (calc-autorange-units nil)
			       (calc-shift-prefix nil)
			       (calc-window-height 7)
			       (calc-was-keypad-mode nil)
			       (calc-full-mode nil)
			       (calc-language nil)
			       (calc-language-option nil)
			       (calc-user-parse-tables nil)
			       (calc-show-selections t)
			       (calc-use-selections t)
			       (calc-assoc-selections t)
			       (calc-display-trail t)
			       (calc-display-working-message lots)
			       (calc-auto-why 'maybe)
			       (calc-timing nil)
			       (calc-gnuplot-default-device "default")
			       (calc-gnuplot-default-output "STDOUT")
			       (calc-gnuplot-print-device "postscript")
			       (calc-gnuplot-print-output "auto")
			       (calc-gnuplot-geometry nil)
			       (calc-graph-default-resolution 15)
			       (calc-graph-default-resolution-3d 5)
			       (calc-invocation-macro nil)))

(defconst calc-local-var-list '(calc-stack
				calc-stack-top
				calc-undo-list
				calc-redo-list
				calc-always-load-extensions
				calc-mode-save-mode
				calc-display-raw
				calc-line-numbering
				calc-line-breaking
				calc-display-just
				calc-display-origin
				calc-left-label
				calc-right-label
				calc-auto-why
				calc-algebraic-mode
				calc-incomplete-algebraic-mode
				calc-symbolic-mode
				calc-matrix-mode
				calc-inverse-flag
				calc-hyperbolic-flag
				calc-keep-args-flag
				calc-angle-mode
				calc-number-radix
				calc-leading-zeros
				calc-group-digits
				calc-group-char
				calc-point-char
				calc-frac-format
				calc-prefer-frac
				calc-hms-format
				calc-date-format
				calc-standard-date-formats
				calc-float-format
				calc-full-float-format
				calc-complex-format
				calc-matrix-just
				calc-full-vectors
				calc-full-trail-vectors
				calc-break-vectors
				calc-vector-commas
				calc-vector-brackets
				calc-matrix-brackets
				calc-complex-mode
				calc-infinite-mode
				calc-display-strings
				calc-simplify-mode
				calc-auto-recompute
				calc-autorange-units
				calc-show-plain
				calc-show-selections
				calc-use-selections
				calc-assoc-selections
				calc-word-size
				calc-internal-prec))


(defun calc-init-base ()

  ;; Verify that Calc is running on the right kind of system.
  (setq calc-emacs-type-epoch (and (fboundp 'epoch::version) epoch::version)
	calc-emacs-type-19 (not (or calc-emacs-type-epoch
				    (string-lessp emacs-version "19")))
	calc-emacs-type-lucid (not (not (string-match "Lucid" emacs-version)))
	calc-emacs-type-gnu19 (and calc-emacs-type-19
				   (not calc-emacs-type-lucid)))

  ;; Set up the standard keystroke (M-#) to run the Calculator, if that key
  ;; has not yet been bound to anything.  For best results, the user should
  ;; do this before Calc is even loaded, so that M-# can auto-load Calc.
  (or (global-key-binding "\e#")
      (global-set-key "\e#" 'calc-dispatch))

  ;; Set up the autoloading linkage.
  (let ((name (and (fboundp 'calc-dispatch)
		   (eq (car-safe (symbol-function 'calc-dispatch)) 'autoload)
		   (nth 1 (symbol-function 'calc-dispatch))))
	(p load-path))

    ;; If Calc files exist on the load-path, we're all set.
    (while (and p (not (file-exists-p
			(expand-file-name "calc-misc.elc" (car p)))))
      (setq p (cdr p)))
    (or p

	;; If Calc is autoloaded using a path name, look there for Calc files.
	;; This works for both relative ("calc/calc.elc") and absolute paths.
	(and name (file-name-directory name)
	     (let ((p2 load-path)
		   (name2 (concat (file-name-directory name)
				  "calc-misc.elc")))
	       (while (and p2 (not (file-exists-p
				    (expand-file-name name2 (car p2)))))
		 (setq p2 (cdr p2)))
	       (if p2
		   (setq load-path (nconc load-path
					  (list
					   (directory-file-name
					    (file-name-directory
					     (expand-file-name
					      name (car p2))))))))))

	;; If calc-autoload-directory is given, use that (and hope it works!).
	(and calc-autoload-directory
	     (not (equal calc-autoload-directory ""))
	     (setq load-path (nconc load-path
				    (list (directory-file-name
					   calc-autoload-directory)))))))

  ;; The following modes use specially-formatted data.
  (put 'calc-mode 'mode-class 'special)
  (put 'calc-trail-mode 'mode-class 'special)
  
  ;; Define "inexact-result" as an e-lisp error symbol.
  (put 'inexact-result 'error-conditions '(error inexact-result calc-error))
  (put 'inexact-result 'error-message "Calc internal error (inexact-result)")
  
  ;; Define "math-overflow" and "math-underflow" as e-lisp error symbols.
  (put 'math-overflow 'error-conditions '(error math-overflow calc-error))
  (put 'math-overflow 'error-message "Floating-point overflow occurred")
  (put 'math-underflow 'error-conditions '(error math-underflow calc-error))
  (put 'math-underflow 'error-message "Floating-point underflow occurred")
  
708 709
  (setq calc-version "2.02g"
	calc-version-date "Mon Nov 19 2001"
Eli Zaretskii's avatar
Eli Zaretskii committed
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
	calc-trail-pointer nil		; "Current" entry in trail buffer.
        calc-trail-overlay nil		; Value of overlay-arrow-string.
        calc-undo-list nil		; List of previous operations for undo.
        calc-redo-list nil		; List of recent undo operations.
        calc-main-buffer nil		; Pointer to Calculator buffer.
	calc-trail-buffer nil		; Pointer to Calc Trail buffer.
        calc-why nil			; Explanations of most recent errors.
        calc-next-why nil
	calc-inverse-flag nil
	calc-hyperbolic-flag nil
	calc-keep-args-flag nil
	calc-function-open "("
	calc-function-close ")"
	calc-language-output-filter nil
	calc-language-input-filter nil
	calc-radix-formatter nil
        calc-last-kill nil		; Last number killed in calc-mode.
        calc-previous-alg-entry nil	; Previous algebraic entry.
        calc-dollar-values nil		; Values to be used for '$'.
        calc-dollar-used nil		; Highest order of '$' that occurred.
	calc-hashes-used nil            ; Highest order of '#' that occurred.
        calc-quick-prev-results nil	; Previous results from Quick Calc.
	calc-said-hello nil		; Has welcome message been said yet?
	calc-executing-macro nil	; Kbd macro executing from "K" key.
	calc-any-selections nil 	; Nil means no selections present.
	calc-help-phase 0		; Count of consecutive "?" keystrokes.
	calc-full-help-flag nil		; Executing calc-full-help?
	calc-refresh-count 0		; Count of calc-refresh calls.
	calc-display-dirty nil
	calc-prepared-composition nil
	calc-selection-cache-default-entry nil
	calc-embedded-info nil
	calc-embedded-active nil
	calc-standalone-flag nil
	var-EvalRules nil
	math-eval-rules-cache-tag t
	math-radix-explicit-format t
	math-expr-function-mapping nil
	math-expr-variable-mapping nil
	math-read-expr-quotes nil
	math-working-step nil
	math-working-step-2 nil
        var-i '(special-const (math-imaginary 1))
        var-pi '(special-const (math-pi))
        var-e '(special-const (math-e))
	var-phi '(special-const (math-phi))
        var-gamma '(special-const (math-gamma-const))
	var-Modes '(special-const (math-get-modes-vec)))

  (mapcar (function (lambda (v) (or (boundp (car v)) (set (car v) (nth 1 v)))))
	  calc-mode-var-list)
  (mapcar (function (lambda (v) (or (boundp v) (set v nil))))
	  calc-local-var-list)

764
  (unless (boundp 'calc-mode-map)
Eli Zaretskii's avatar
Eli Zaretskii committed
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
    (setq calc-mode-map (make-keymap))
    (suppress-keymap calc-mode-map t)
    (define-key calc-mode-map "+" 'calc-plus)
    (define-key calc-mode-map "-" 'calc-minus)
    (define-key calc-mode-map "*" 'calc-times)
    (define-key calc-mode-map "/" 'calc-divide)
    (define-key calc-mode-map "%" 'calc-mod)
    (define-key calc-mode-map "&" 'calc-inv)
    (define-key calc-mode-map "^" 'calc-power)
    (define-key calc-mode-map "\M-%" 'calc-percent)
    (define-key calc-mode-map "e" 'calcDigit-start)
    (define-key calc-mode-map "i" 'calc-info)
    (define-key calc-mode-map "n" 'calc-change-sign)
    (define-key calc-mode-map "q" 'calc-quit)
    (define-key calc-mode-map "Y" 'nil)
    (define-key calc-mode-map "Y?" 'calc-shift-Y-prefix-help)
    (define-key calc-mode-map "?" 'calc-help)
    (define-key calc-mode-map " " 'calc-enter)
    (define-key calc-mode-map "'" 'calc-algebraic-entry)
    (define-key calc-mode-map "$" 'calc-auto-algebraic-entry)
    (define-key calc-mode-map "\"" 'calc-auto-algebraic-entry)
    (define-key calc-mode-map "\t" 'calc-roll-down)
    (define-key calc-mode-map "\M-\t" 'calc-roll-up)
    (define-key calc-mode-map "\C-m" 'calc-enter)
    (define-key calc-mode-map "\M-\C-m" 'calc-last-args-stub)
    (define-key calc-mode-map "\C-j" 'calc-over)

    (mapcar (function
	     (lambda (x)
	       (define-key calc-mode-map (char-to-string x) 'undefined)))
	    "lOW")
    (mapcar (function
	     (lambda (x)
	       (define-key calc-mode-map (char-to-string x)
		 'calc-missing-key)))
	    (concat "ABCDEFGHIJKLMNPQRSTUVXZabcdfghjkmoprstuvwxyz"
		    ":\\|!()[]<>{},;=~`\C-k\M-k\C-w\M-w\C-y\C-_"))
    (mapcar (function
	     (lambda (x)
	       (define-key calc-mode-map (char-to-string x) 'calcDigit-start)))
	    "_0123456789.#@")

    (setq calc-digit-map (make-keymap))
    (if calc-emacs-type-lucid
	(map-keymap (function
		     (lambda (keys bind)
		       (define-key calc-digit-map keys
			 (if (eq bind 'undefined)
			     'undefined 'calcDigit-nondigit))))
		    calc-mode-map)
      (let ((cmap (if calc-emacs-type-19 (nth 1 calc-mode-map) calc-mode-map))
	    (dmap (if calc-emacs-type-19 (nth 1 calc-digit-map)
		    calc-digit-map))
	    (i 0))
	(while (< i 128)
	  (aset dmap i
		(if (eq (aref cmap i) 'undefined)
		    'undefined 'calcDigit-nondigit))
	  (setq i (1+ i)))))
    (mapcar (function
	     (lambda (x)
	       (define-key calc-digit-map (char-to-string x)
		 'calcDigit-key)))
	    "_0123456789.e+-:n#@oh'\"mspM")
    (mapcar (function
	     (lambda (x)
	       (define-key calc-digit-map (char-to-string x)
		 'calcDigit-letter)))
	    "abcdfgijklqrtuvwxyzABCDEFGHIJKLNOPQRSTUVWXYZ")
    (define-key calc-digit-map "'" 'calcDigit-algebraic)
    (define-key calc-digit-map "`" 'calcDigit-edit)
    (define-key calc-digit-map "\C-g" 'abort-recursive-edit)

    (mapcar (function
	     (lambda (x)
	       (condition-case err
		   (progn
		     (define-key calc-digit-map x 'calcDigit-backspace)
		     (define-key calc-mode-map x 'calc-pop)
		     (define-key calc-mode-map
		       (if (vectorp x)
			   (if calc-emacs-type-lucid
			       (if (= (length x) 1)
				   (vector (if (consp (aref x 0))
					       (cons 'meta (aref x 0))
					     (list 'meta (aref x 0))))
				 "\e\C-d")
			     (vconcat "\e" x))
			 (concat "\e" x))
		       'calc-pop-above))
		 (error nil))))
	    (if calc-scan-for-dels
		(append (where-is-internal 'delete-backward-char global-map)
			(where-is-internal 'backward-delete-char global-map)
			'("\C-d"))
	      '("\177" "\C-d")))

    (setq calc-dispatch-map (make-keymap))
    (mapcar (function
	     (lambda (x)
	       (define-key calc-dispatch-map (char-to-string (car x)) (cdr x))
	       (if (string-match "abcdefhijklnopqrstuwxyz"
				 (char-to-string (car x)))
		   (define-key calc-dispatch-map
		     (char-to-string (- (car x) ?a -1)) (cdr x)))
	       (define-key calc-dispatch-map (format "\e%c" (car x)) (cdr x))))
	    '( ( ?a . calc-embedded-activate )
	       ( ?b . calc-big-or-small )
	       ( ?c . calc )
	       ( ?d . calc-embedded-duplicate )
	       ( ?e . calc-embedded )
	       ( ?f . calc-embedded-new-formula )
	       ( ?g . calc-grab-region )
	       ( ?h . calc-dispatch-help )
	       ( ?i . calc-info )
	       ( ?j . calc-embedded-select )
	       ( ?k . calc-keypad )
	       ( ?l . calc-load-everything )
	       ( ?m . read-kbd-macro )
	       ( ?n . calc-embedded-next )
	       ( ?o . calc-other-window )
	       ( ?p . calc-embedded-previous )
	       ( ?q . quick-calc )
	       ( ?r . calc-grab-rectangle )
	       ( ?s . calc-info-summary )
	       ( ?t . calc-tutorial )
	       ( ?u . calc-embedded-update-formula )
	       ( ?w . calc-embedded-word )
	       ( ?x . calc-quit )
	       ( ?y . calc-copy-to-buffer )
	       ( ?z . calc-user-invocation )
	       ( ?= . calc-embedded-update-formula )
	       ( ?\' . calc-embedded-new-formula )
	       ( ?\` . calc-embedded-edit )
	       ( ?: . calc-grab-sum-down )
	       ( ?_ . calc-grab-sum-across )
	       ( ?0 . calc-reset )
	       ( ?# . calc-same-interface )
	       ( ?? . calc-dispatch-help ) ))
    )

  (autoload 'calc-extensions "calc-ext")
  (autoload 'calc-need-macros "calc-macs")

;;;; (Autoloads here)
  (mapcar (function (lambda (x)
    (mapcar (function (lambda (func)
      (autoload func (car x)))) (cdr x))))
    '(

 ("calc-aent" calc-Need-calc-aent calc-alg-digit-entry calc-alg-entry
calc-check-user-syntax calc-do-alg-entry calc-do-calc-eval
calc-do-quick-calc calc-match-user-syntax math-build-parse-table
math-find-user-tokens math-read-expr-list math-read-exprs math-read-if
math-read-token math-remove-dashes)

Colin Walters's avatar
Colin Walters committed
921
 ("calc-misc" calc-Need-calc-misc 
Eli Zaretskii's avatar
Eli Zaretskii committed
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
calc-do-handle-whys calc-do-refresh calc-num-prefix-name
calc-record-list calc-record-why calc-report-bug calc-roll-down-stack
calc-roll-up-stack calc-temp-minibuffer-message calcFunc-floor
calcFunc-inv calcFunc-trunc math-concat math-constp math-div2
math-div2-bignum math-do-working math-evenp math-fixnatnump
math-fixnump math-floor math-imod math-ipow math-looks-negp math-mod
math-negp math-posp math-pow math-read-radix-digit math-reject-arg
math-trunc math-zerop)

))

  (mapcar (function (lambda (x)
    (mapcar (function (lambda (cmd)
      (autoload cmd (car x) nil t))) (cdr x))))
    '(

 ("calc-aent" calc-algebraic-entry calc-auto-algebraic-entry
calcDigit-algebraic calcDigit-edit)

 ("calc-misc" another-calc calc-big-or-small calc-dispatch-help
calc-help calc-info calc-info-summary calc-inv calc-last-args-stub
calc-missing-key calc-mod calc-other-window calc-over calc-percent
calc-pop-above calc-power calc-roll-down calc-roll-up
calc-shift-Y-prefix-help calc-tutorial calcDigit-letter
946
report-calc-bug))))
Eli Zaretskii's avatar
Eli Zaretskii committed
947 948 949 950 951 952 953 954

(calc-init-base)


;;;###autoload (global-set-key "\e#" 'calc-dispatch)

;;;###autoload
(defun calc-dispatch (&optional arg)
955
  "Invoke the GNU Emacs Calculator.  See `calc-dispatch-help' for details."
Eli Zaretskii's avatar
Eli Zaretskii committed
956 957 958 959 960 961 962 963 964 965 966 967 968 969
  (interactive "P")
  (sit-for echo-keystrokes)
  (condition-case err   ; look for other keys bound to calc-dispatch
      (let ((keys (this-command-keys)))
	(or (not (stringp keys))
	    (string-match "\\`\C-u\\|\\`\e[-0-9#]\\|`[\M--\M-0-\M-9]" keys)
	    (eq (lookup-key calc-dispatch-map keys) 'calc-same-interface)
	    (progn
	      (and (string-match "\\`[\C-@-\C-_]" keys)
		   (symbolp
		    (lookup-key calc-dispatch-map (substring keys 0 1)))
		   (define-key calc-dispatch-map (substring keys 0 1) nil))
	      (define-key calc-dispatch-map keys 'calc-same-interface))))
    (error nil))
970
  (calc-do-dispatch arg))
Eli Zaretskii's avatar
Eli Zaretskii committed
971

972
(defvar calc-dispatch-help nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
973 974 975 976 977 978 979 980 981 982 983 984 985
(defun calc-do-dispatch (arg)
  (let ((key (calc-read-key-sequence
	      (if calc-dispatch-help
		  "Calc options: Calc, Keypad, Quick, Embed; eXit; Info, Tutorial; Grab; ?=more"
		(format "%s  (Type ? for a list of Calc options)"
			(key-description (this-command-keys))))
	      calc-dispatch-map)))
    (setq key (lookup-key calc-dispatch-map key))
    (message "")
    (if key
	(progn
	  (or (commandp key) (calc-extensions))
	  (call-interactively key))
986
      (beep))))
Eli Zaretskii's avatar
Eli Zaretskii committed
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

(defun calc-read-key-sequence (prompt map)
  (let ((prompt2 (format "%s " (key-description (this-command-keys))))
	(glob (current-global-map))
	(loc (current-local-map)))
    (or (input-pending-p) (message prompt))
    (let ((key (calc-read-key t)))
      (calc-unread-command (cdr key))
      (unwind-protect
	  (progn
	    (use-global-map map)
	    (use-local-map nil)
	    (read-key-sequence
	     (if (commandp (key-binding (if calc-emacs-type-19
					    (vector (cdr key))
					  (char-to-string (cdr key)))))
		 "" prompt2)))
	(use-global-map glob)
1005
	(use-local-map loc)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058



(defun calc-mode ()
  "Calculator major mode.

This is an RPN calculator featuring arbitrary-precision integer, rational,
floating-point, complex, matrix, and symbolic arithmetic.

RPN calculation:  2 RET 3 +    produces 5.
Algebraic style:  ' 2+3 RET    produces 5.

Basic operators are +, -, *, /, ^, & (reciprocal), % (modulo), n (change-sign).

Press ? repeatedly for more complete help.  Press `h i' to read the
Calc manual on-line, `h s' to read the summary, or `h t' for the tutorial.

Notations:  3.14e6     3.14 * 10^6
            _23        negative number -23 (or type `23 n')
            17:3       the fraction 17/3
            5:2:3      the fraction 5 and 2/3
            16#12C     the integer 12C base 16 = 300 base 10
            8#177:100  the fraction 177:100 base 8 = 127:64 base 10
            (2, 4)     complex number 2 + 4i
            (2; 4)     polar complex number (r; theta)
            [1, 2, 3]  vector  ([[1, 2], [3, 4]] is a matrix)
            [1 .. 4)   semi-open interval, 1 <= x < 4
            2 +/- 3    (p key) number with mean 2, standard deviation 3
            2 mod 3    (M key) number 2 computed modulo 3
	    <1 jan 91> Date form (enter using ' key)


\\{calc-mode-map}
"
  (interactive)
  (mapcar (function
	   (lambda (v) (set-default v (symbol-value v)))) calc-local-var-list)
  (kill-all-local-variables)
  (use-local-map (if (eq calc-algebraic-mode 'total)
		     (progn (calc-extensions) calc-alg-map) calc-mode-map))
  (mapcar (function (lambda (v) (make-local-variable v))) calc-local-var-list)
  (make-local-variable 'overlay-arrow-position)
  (make-local-variable 'overlay-arrow-string)
  (setq truncate-lines t)
  (setq buffer-read-only t)
  (setq major-mode 'calc-mode)
  (setq mode-name "Calculator")
  (setq calc-stack-top (length (or (memq (assq 'top-of-stack calc-stack)
					 calc-stack)
				   (setq calc-stack (list (list 'top-of-stack
								1 nil))))))
  (setq calc-stack-top (- (length calc-stack) calc-stack-top -1))
  (or calc-loaded-settings-file
1059
      (null calc-settings-file)
Eli Zaretskii's avatar
Eli Zaretskii committed
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
      (string-match "\\.emacs" calc-settings-file)
      (progn
	(setq calc-loaded-settings-file t)
	(load calc-settings-file t)))   ; t = missing-ok
  (if (and (eq window-system 'x) (boundp 'mouse-map))
      (substitute-key-definition 'x-paste-text 'calc-x-paste-text
				 mouse-map))
  (let ((p command-line-args))
    (while p
      (and (equal (car p) "-f")
	   (string-match "calc" (nth 1 p))
	   (string-match "full" (nth 1 p))
	   (setq calc-standalone-flag t))
      (setq p (cdr p))))
  (run-hooks 'calc-mode-hook)
  (calc-refresh t)
  (calc-set-mode-line)
  ;; The calc-defs variable is a relic.  Use calc-define properties instead.
  (if (and (boundp 'calc-defs)
	   calc-defs)
      (progn
	(message "Evaluating calc-defs...")
	(calc-need-macros)
	(eval (cons 'progn calc-defs))
	(setq calc-defs nil)
	(calc-set-mode-line)))
1086
  (calc-check-defines))
Eli Zaretskii's avatar
Eli Zaretskii committed
1087

1088
(defvar calc-check-defines 'calc-check-defines)  ; suitable for run-hooks
Eli Zaretskii's avatar
Eli Zaretskii committed
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
(defun calc-check-defines ()
  (if (symbol-plist 'calc-define)
      (let ((plist (copy-sequence (symbol-plist 'calc-define))))
	(while (and plist (null (nth 1 plist)))
	  (setq plist (cdr (cdr plist))))
	(if plist
	    (save-excursion
	      (calc-extensions)
	      (calc-need-macros)
	      (set-buffer "*Calculator*")
	      (while plist
		(put 'calc-define (car plist) nil)
		(eval (nth 1 plist))
		(setq plist (cdr (cdr plist))))
	      ;; See if this has added any more calc-define properties.
	      (calc-check-defines))
1105
	  (setplist 'calc-define nil)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

(defun calc-trail-mode (&optional buf)
  "Calc Trail mode.
This mode is used by the *Calc Trail* buffer, which records all results
obtained by the GNU Emacs Calculator.

Calculator commands beginning with the `t' key are used to manipulate
the Trail.

This buffer uses the same key map as the *Calculator* buffer; calculator
commands given here will actually operate on the *Calculator* stack."
  (interactive)
  (fundamental-mode)
  (use-local-map calc-mode-map)
  (setq major-mode 'calc-trail-mode)
  (setq mode-name "Calc Trail")
  (setq truncate-lines t)
  (setq buffer-read-only t)
  (make-local-variable 'overlay-arrow-position)
  (make-local-variable 'overlay-arrow-string)
  (if buf
      (progn
	(make-local-variable 'calc-main-buffer)
	(setq calc-main-buffer buf)))
  (if (= (buffer-size) 0)
      (let ((buffer-read-only nil))
1132
	(insert "Emacs Calculator v" calc-version " by Dave Gillespie\n")))
1133
  (run-hooks 'calc-trail-mode-hook))
Eli Zaretskii's avatar
Eli Zaretskii committed
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

(defun calc-create-buffer ()
  (set-buffer (get-buffer-create "*Calculator*"))
  (or (eq major-mode 'calc-mode)
      (calc-mode))
  (setq max-lisp-eval-depth (max max-lisp-eval-depth 1000))
  (if calc-always-load-extensions
      (calc-extensions))
  (if calc-language
      (progn
	(calc-extensions)
1145
	(calc-set-language calc-language calc-language-option t))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189

;;;###autoload
(defun calc (&optional arg full-display interactive)
  "The Emacs Calculator.  Full documentation is listed under \"calc-mode\"."
  (interactive "P")
  (if arg
      (or (eq arg 0)
	  (progn
	    (calc-extensions)
	    (if (= (prefix-numeric-value arg) -1)
		(calc-grab-region (region-beginning) (region-end) nil)
	      (if (= (prefix-numeric-value arg) -2)
		  (calc-keypad)))))
    (if (get-buffer-window "*Calc Keypad*")
	(progn
	  (calc-keypad)
	  (set-buffer (window-buffer (selected-window)))))
    (if (eq major-mode 'calc-mode)
	(calc-quit)
      (let ((oldbuf (current-buffer)))
	(calc-create-buffer)
	(setq calc-was-keypad-mode nil)
	(if (or (eq full-display t)
		(and (null full-display) calc-full-mode))
	    (switch-to-buffer (current-buffer) t)
	  (if (get-buffer-window (current-buffer))
	      (select-window (get-buffer-window (current-buffer)))
	    (if (and (boundp 'calc-window-hook) calc-window-hook)
		(run-hooks 'calc-window-hook)
	      (let ((w (get-largest-window)))
		(if (and pop-up-windows
			 (> (window-height w)
			    (+ window-min-height calc-window-height 2)))
		    (progn
		      (setq w (split-window w
					    (- (window-height w)
					       calc-window-height 2)
					    nil))
		      (set-window-buffer w (current-buffer))
		      (select-window w))
		  (pop-to-buffer (current-buffer)))))))
	(save-excursion
	  (set-buffer (calc-trail-buffer))
	  (and calc-display-trail
1190
	       (= (window-width) (frame-width))
Eli Zaretskii's avatar
Eli Zaretskii committed
1191
	       (calc-trail-display 1 t)))
1192
	(message "Welcome to the GNU Emacs Calculator!  Press `?' or `h' for help, `q' to quit")
Eli Zaretskii's avatar
Eli Zaretskii committed
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
	(run-hooks 'calc-start-hook)
	(and (windowp full-display)
	     (window-point full-display)
	     (select-window full-display))
	(calc-check-defines)
	(and calc-said-hello
	     (or (interactive-p) interactive)
	     (progn
	       (sit-for 2)
	       (message "")))
1203
	(setq calc-said-hello t)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1204 1205 1206 1207 1208

;;;###autoload
(defun full-calc ()
  "Invoke the Calculator and give it a full-sized window."
  (interactive)
1209
  (calc nil t (interactive-p)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222

(defun calc-same-interface (arg)
  "Invoke the Calculator using the most recent interface (calc or calc-keypad)."
  (interactive "P")
  (if (and (equal (buffer-name) "*Gnuplot Trail*")
	   (> (recursion-depth) 0))
      (exit-recursive-edit)
    (if (eq major-mode 'calc-edit-mode)
	(calc-edit-finish arg)
      (if (eq major-mode 'MacEdit-mode)
	  (MacEdit-finish-edit)
	(if calc-was-keypad-mode
	    (calc-keypad)
1223
	  (calc arg calc-full-mode t))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240


(defun calc-quit (&optional non-fatal)
  (interactive)
  (and calc-standalone-flag (not non-fatal)
       (save-buffers-kill-emacs nil))
  (if (and (equal (buffer-name) "*Gnuplot Trail*")
	   (> (recursion-depth) 0))
      (exit-recursive-edit))
  (if (eq major-mode 'calc-edit-mode)
      (calc-edit-cancel)
    (if (eq major-mode 'MacEdit-mode)
	(MacEdit-cancel-edit)
      (if (and (interactive-p)
	       calc-embedded-info
	       (eq (current-buffer) (aref calc-embedded-info 0)))
	  (calc-embedded nil)
1241 1242
	(unless (eq major-mode 'calc-mode)
	  (calc-create-buffer))
Eli Zaretskii's avatar
Eli Zaretskii committed
1243 1244 1245 1246 1247 1248 1249 1250 1251
	(run-hooks 'calc-end-hook)
	(setq calc-undo-list nil calc-redo-list nil)
	(mapcar (function (lambda (v) (set-default v (symbol-value v))))
		calc-local-var-list)
	(let ((buf (current-buffer))
	      (win (get-buffer-window (current-buffer)))
	      (kbuf (get-buffer "*Calc Keypad*")))
	  (delete-windows-on (calc-trail-buffer))
	  (if (and win
1252 1253
		   (< (window-height win) (1- (frame-height)))
		   (= (window-width win) (frame-width))  ; avoid calc-keypad
Eli Zaretskii's avatar
Eli Zaretskii committed
1254 1255
		   (not (get-buffer-window "*Calc Keypad*")))
	      (setq calc-window-height (- (window-height win) 2)))
Colin Walters's avatar
Colin Walters committed
1256
	  (progn
Eli Zaretskii's avatar
Eli Zaretskii committed
1257 1258 1259 1260
	    (delete-windows-on buf)
	    (delete-windows-on kbuf))
	  (bury-buffer buf)
	  (bury-buffer calc-trail-buffer)
1261
	  (and kbuf (bury-buffer kbuf)))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1262 1263 1264 1265 1266

;;;###autoload
(defun quick-calc ()
  "Do a quick calculation in the minibuffer without invoking full Calculator."
  (interactive)
1267
  (calc-do-quick-calc))
Eli Zaretskii's avatar
Eli Zaretskii committed
1268 1269 1270 1271 1272 1273

;;;###autoload
(defun calc-eval (str &optional separator &rest args)
  "Do a quick calculation and return the result as a string.
Return value will either be the formatted result in string form,
or a list containing a character position and an error message in string form."
1274
  (calc-do-calc-eval str separator args))
Eli Zaretskii's avatar
Eli Zaretskii committed
1275 1276 1277 1278 1279 1280 1281 1282 1283

;;;###autoload
(defun calc-keypad ()
  "Invoke the Calculator in \"visual keypad\" mode.
This is most useful in the X window system.
In this mode, click on the Calc \"buttons\" using the left mouse button.
Or, position the cursor manually and do M-x calc-keypad-press."
  (interactive)
  (calc-extensions)
1284
  (calc-do-keypad calc-full-mode (interactive-p)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1285 1286 1287 1288 1289 1290 1291

;;;###autoload
(defun full-calc-keypad ()
  "Invoke the Calculator in full-screen \"visual keypad\" mode.
See calc-keypad for details."
  (interactive)
  (calc-extensions)
1292
  (calc-do-keypad t (interactive-p)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1293 1294


1295 1296
(defvar calc-aborted-prefix nil)
(defvar calc-start-time nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
;;; Note that modifications to this function may break calc-pass-errors.
(defun calc-do (do-body &optional do-slow)
  (calc-check-defines)
  (let* ((calc-command-flags nil)
	 (calc-start-time (and calc-timing (not calc-start-time)
			       (calc-extensions)
			       (current-time-string)))
	 (gc-cons-threshold (max gc-cons-threshold
				 (if calc-timing 2000000 100000))))
    (setq calc-aborted-prefix "")
    (unwind-protect
	(condition-case err
	    (save-excursion
	      (if calc-embedded-info
		  (calc-embedded-select-buffer)
		(calc-select-buffer))
	      (and (eq calc-algebraic-mode 'total)
		   (calc-extensions)
		   (use-local-map calc-alg-map))
1316 1317 1318
	      (when (and do-slow calc-display-working-message)
		(message "Working...")
		(calc-set-command-flag 'clear-message))
Eli Zaretskii's avatar
Eli Zaretskii committed
1319 1320
	      (funcall do-body)
	      (setq calc-aborted-prefix nil)
1321 1322 1323 1324
	      (when (memq 'renum-stack calc-command-flags)
		(calc-renumber-stack))
	      (when (memq 'clear-message calc-command-flags)
		(message "")))
Eli Zaretskii's avatar
Eli Zaretskii committed
1325 1326 1327 1328 1329
	  (error
	   (if (and (eq (car err) 'error)
		    (stringp (nth 1 err))
		    (string-match "max-specpdl-size\\|max-lisp-eval-depth"
				  (nth 1 err)))
1330
	       (error "Computation got stuck or ran too long.  Type `M' to increase the limit")
Eli Zaretskii's avatar
Eli Zaretskii committed
1331 1332 1333
	     (setq calc-aborted-prefix nil)
	     (signal (car err) (cdr err)))))
      (setq calc-old-aborted-prefix calc-aborted-prefix)
1334 1335
      (when calc-aborted-prefix
	(calc-record "<Aborted>" calc-aborted-prefix))
Eli Zaretskii's avatar
Eli Zaretskii committed
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
      (and calc-start-time
	   (let* ((calc-internal-prec 12)
		  (calc-date-format nil)
		  (end-time (current-time-string))
		  (time (if (equal calc-start-time end-time)
			    0
			  (math-sub
			   (calcFunc-unixtime (math-parse-date end-time) 0)
			   (calcFunc-unixtime (math-parse-date calc-start-time)
					      0)))))
	     (if (math-lessp 1 time)
		 (calc-record time "(t)"))))
      (or (memq 'no-align calc-command-flags)
	  (eq major-mode 'calc-trail-mode)
	  (calc-align-stack-window))
      (and (memq 'position-point calc-command-flags)
	   (if (eq major-mode 'calc-mode)
	       (progn
		 (goto-line calc-final-point-line)
		 (move-to-column calc-final-point-column))
	     (save-excursion
	       (calc-select-buffer)
	       (goto-line calc-final-point-line)
	       (move-to-column calc-final-point-column))))
1360 1361 1362 1363 1364 1365 1366 1367
      (unless (memq 'keep-flags calc-command-flags)
	(save-excursion
	  (calc-select-buffer)
	  (setq calc-inverse-flag nil
		calc-hyperbolic-flag nil
		calc-keep-args-flag nil)))
      (when (memq 'do-edit calc-command-flags)
	(switch-to-buffer (get-buffer-create "*Calc Edit*")))
Eli Zaretskii's avatar
Eli Zaretskii committed
1368
      (calc-set-mode-line)
1369 1370
      (when calc-embedded-info
	(calc-embedded-finish-command))))
1371 1372
  (identity nil))  ; allow a GC after timing is done

Eli Zaretskii's avatar
Eli Zaretskii committed
1373 1374

(defun calc-set-command-flag (f)
1375 1376
  (unless (memq f calc-command-flags)
    (setq calc-command-flags (cons f calc-command-flags))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1377 1378 1379 1380 1381 1382 1383 1384

(defun calc-select-buffer ()
  (or (eq major-mode 'calc-mode)
      (if calc-main-buffer
	  (set-buffer calc-main-buffer)
	(let ((buf (get-buffer "*Calculator*")))
	  (if buf
	      (set-buffer buf)
1385
	    (error "Calculator buffer not available"))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1386 1387 1388

(defun calc-cursor-stack-index (&optional index)
  (goto-char (point-max))
1389
  (forward-line (- (calc-substack-height (or index 1)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1390 1391

(defun calc-stack-size ()
1392
  (- (length calc-stack) calc-stack-top))
Eli Zaretskii's avatar
Eli Zaretskii committed
1393 1394 1395 1396 1397 1398 1399 1400 1401

(defun calc-substack-height (n)
  (let ((sum 0)
	(stack calc-stack))
    (setq n (+ n calc-stack-top))
    (while (and (> n 0) stack)
      (setq sum (+ sum (nth 1 (car stack)))
	    n (1- n)
	    stack (cdr stack)))
1402
    sum))
Eli Zaretskii's avatar
Eli Zaretskii committed
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506

(defun calc-set-mode-line ()
  (save-excursion
    (calc-select-buffer)
    (let* ((fmt (car calc-float-format))
	   (figs (nth 1 calc-float-format))
	   (new-mode-string
	    (format "Calc%s%s: %d %s %-14s"
		    (if calc-embedded-info "Embed" "")
		    (if (and (> (length (buffer-name)) 12)
			     (equal (substring (buffer-name) 0 12)
				    "*Calculator*"))
			(substring (buffer-name) 12)
		      "")
		    calc-internal-prec
		    (capitalize (symbol-name calc-angle-mode))
		    (concat

		     ;; Input-related modes
		     (if (eq calc-algebraic-mode 'total) "Alg* "
		       (if calc-algebraic-mode "Alg "
			 (if calc-incomplete-algebraic-mode "Alg[( " "")))

		     ;; Computational modes
		     (if calc-symbolic-mode "Symb " "")
		     (cond ((eq calc-matrix-mode 'matrix) "Matrix ")
			   ((integerp calc-matrix-mode)
			    (format "Matrix%d " calc-matrix-mode))
			   ((eq calc-matrix-mode 'scalar) "Scalar ")
			   (t ""))
		     (if (eq calc-complex-mode 'polar) "Polar " "")
		     (if calc-prefer-frac "Frac " "")
		     (cond ((null calc-infinite-mode) "")
			   ((eq calc-infinite-mode 1) "+Inf ")
			   (t "Inf "))
		     (cond ((eq calc-simplify-mode 'none) "NoSimp ")
			   ((eq calc-simplify-mode 'num) "NumSimp ")
			   ((eq calc-simplify-mode 'binary)
			    (format "BinSimp%d " calc-word-size))
			   ((eq calc-simplify-mode 'alg) "AlgSimp ")
			   ((eq calc-simplify-mode 'ext) "ExtSimp ")
			   ((eq calc-simplify-mode 'units) "UnitSimp ")
			   (t ""))

		     ;; Display modes
		     (cond ((= calc-number-radix 10) "")
			   ((= calc-number-radix 2) "Bin ")
			   ((= calc-number-radix 8) "Oct ")
			   ((= calc-number-radix 16) "Hex ")
			   (t (format "Radix%d " calc-number-radix)))
		     (if calc-leading-zeros "Zero " "")
		     (cond ((null calc-language) "")
			   ((eq calc-language 'tex) "TeX ")
			   (t (concat
			       (capitalize (symbol-name calc-language))
			       " ")))
		     (cond ((eq fmt 'float)
			    (if (zerop figs) "" (format "Norm%d " figs)))
			   ((eq fmt 'fix) (format "Fix%d " figs))
			   ((eq fmt 'sci)
			    (if (zerop figs) "Sci " (format "Sci%d " figs)))
			   ((eq fmt 'eng)
			    (if (zerop figs) "Eng " (format "Eng%d " figs))))
		     (cond ((not calc-display-just)
			    (if calc-display-origin
				(format "Left%d " calc-display-origin) ""))
			   ((eq calc-display-just 'right)
			    (if calc-display-origin
				(format "Right%d " calc-display-origin)
			      "Right "))
			   (t
			    (if calc-display-origin
				(format "Center%d " calc-display-origin)
			      "Center ")))
		     (cond ((integerp calc-line-breaking)
			    (format "Wid%d " calc-line-breaking))
			   (calc-line-breaking "")
			   (t "Wide "))

		     ;; Miscellaneous other modes/indicators
		     (if calc-assoc-selections "" "Break ")
		     (cond ((eq calc-mode-save-mode 'save) "Save ")
			   ((not calc-embedded-info) "")
			   ((eq calc-mode-save-mode 'local) "Local ")
			   ((eq calc-mode-save-mode 'edit) "LocEdit ")
			   ((eq calc-mode-save-mode 'perm) "LocPerm ")
			   ((eq calc-mode-save-mode 'global) "Global ")
			   (t ""))
		     (if calc-auto-recompute "" "Manual ")
		     (if (and (fboundp 'calc-gnuplot-alive)
			      (calc-gnuplot-alive)) "Graph " "")
		     (if (and calc-embedded-info
			      (> (calc-stack-size) 0)
			      (calc-top 1 'sel)) "Sel " "")
		     (if calc-display-dirty "Dirty " "")
		     (if calc-inverse-flag "Inv " "")
		     (if calc-hyperbolic-flag "Hyp " "")
		     (if calc-keep-args-flag "Keep " "")
		     (if (/= calc-stack-top 1) "Narrow " "")
		     (apply 'concat calc-other-modes)))))
      (if (equal new-mode-string mode-line-buffer-identification)
	  nil
	(setq mode-line-buffer-identification new-mode-string)
	(set-buffer-modified-p (buffer-modified-p))
1507
	(and calc-embedded-info (calc-embedded-mode-line-change))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522

(defun calc-align-stack-window ()
  (if (eq major-mode 'calc-mode)
      (progn
	(let ((win (get-buffer-window (current-buffer))))
	  (if win
	      (progn
		(calc-cursor-stack-index 0)
		(vertical-motion (- 2 (window-height win)))
		(set-window-start win (point)))))
	(calc-cursor-stack-index 0)
	(if (looking-at " *\\.$")
	    (goto-char (1- (match-end 0)))))
    (save-excursion
      (calc-select-buffer)
1523
      (calc-align-stack-window))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1524 1525 1526 1527 1528

(defun calc-check-stack (n)
  (if (> n (calc-stack-size))
      (error "Too few elements on stack"))
  (if (< n 0)
1529
      (error "Invalid argument")))
Eli Zaretskii's avatar
Eli Zaretskii committed
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549

(defun calc-push-list (vals &optional m sels)
  (while vals
    (if calc-executing-macro
	(calc-push-list-in-macro vals m sels)
      (save-excursion
	(calc-select-buffer)
	(let* ((val (car vals))
	       (entry (list val 1 (car sels)))
	       (mm (+ (or m 1) calc-stack-top)))
	  (calc-cursor-stack-index (1- (or m 1)))
	  (if (> mm 1)
	      (setcdr (nthcdr (- mm 2) calc-stack)
		      (cons entry (nthcdr (1- mm) calc-stack)))
	    (setq calc-stack (cons entry calc-stack)))
	  (let ((buffer-read-only nil))
	    (insert (math-format-stack-value entry) "\n"))
	  (calc-record-undo (list 'push mm))
	  (calc-set-command-flag 'renum-stack))))
    (setq vals (cdr vals)
1550
	  sels (cdr sels))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1551 1552 1553 1554 1555

(defun calc-pop-push-list (n vals &optional m sels)
  (if (and calc-any-selections (null sels))
      (calc-replace-selections n vals m)
    (calc-pop-stack n m sels)
1556
    (calc-push-list vals m sels)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568

(defun calc-pop-push-record-list (n prefix vals &optional m sels)
  (or (and (consp vals)
	   (or (integerp (car vals))
	       (consp (car vals))))
      (and vals (setq vals (list vals)
		      sels (and sels (list sels)))))
  (calc-check-stack (+ n (or m 1) -1))
  (if prefix
      (if (cdr vals)
	  (calc-record-list vals prefix)
	(calc-record (car vals) prefix)))
1569
  (calc-pop-push-list n vals m sels))
Eli Zaretskii's avatar
Eli Zaretskii committed
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584

(defun calc-enter-result (n prefix vals &optional m)
  (setq calc-aborted-prefix prefix)
  (if (and (consp vals)
	   (or (integerp (car vals))
	       (consp (car vals))))
      (setq vals (mapcar 'calc-normalize vals))
    (setq vals (calc-normalize vals)))
  (or (and (consp vals)
	   (or (integerp (car vals))
	       (consp (car vals))))
      (setq vals (list vals)))
  (if (equal vals '((nil)))
      (setq vals nil))
  (calc-pop-push-record-list n prefix vals m)
1585
  (calc-handle-whys))
Eli Zaretskii's avatar
Eli Zaretskii committed
1586 1587 1588 1589 1590

(defun calc-normalize (val)
  (if (memq calc-simplify-mode '(nil none num))
      (math-normalize val)
    (calc-extensions)
1591
    (calc-normalize-fancy val)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1592 1593 1594

(defun calc-handle-whys ()
  (if calc-next-why
1595
      (calc-do-handle-whys)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622


(defun calc-pop-stack (&optional n m sel-ok)  ; pop N objs at level M of stack.
  (or n (setq n 1))
  (or m (setq m 1))
  (or calc-keep-args-flag
      (let ((mm (+ m calc-stack-top)))
	(if (and calc-any-selections (not sel-ok)
		 (calc-top-selected n m))
	    (calc-sel-error))
	(if calc-executing-macro
	    (calc-pop-stack-in-macro n mm)
	  (calc-record-undo (list 'pop mm (calc-top-list n m 'full)))
	  (save-excursion
	    (calc-select-buffer)
	    (let ((buffer-read-only nil))
	      (if (> mm 1)
		  (progn
		    (calc-cursor-stack-index (1- m))
		    (let ((bot (point)))
		      (calc-cursor-stack-index (+ n m -1))
		      (delete-region (point) bot))
		    (setcdr (nthcdr (- mm 2) calc-stack)
			    (nthcdr (+ n mm -1) calc-stack)))
		(calc-cursor-stack-index n)
		(setq calc-stack (nthcdr n calc-stack))
		(delete-region (point) (point-max))))
1623
	    (calc-set-command-flag 'renum-stack))))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

(defun calc-get-stack-element (x)
  (cond ((eq sel-mode 'entry)
	 x)
	((eq sel-mode 'sel)
	 (nth 2 x))
	((or (null (nth 2 x))
	     (eq sel-mode 'full)
	     (not calc-use-selections))
	 (car x))
	(sel-mode
	 (calc-sel-error))
1636
	(t (nth 2 x))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1637 1638 1639 1640 1641

;; Get the Nth element of the stack (N=1 is the top element).
(defun calc-top (&optional n sel-mode)
  (or n (setq n 1))
  (calc-check-stack n)
1642
  (calc-get-stack-element (nth (+ n calc-stack-top -1) calc-stack)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1643 1644

(defun calc-top-n (&optional n sel-mode)    ; in case precision has changed
1645
  (math-check-complete (calc-normalize (calc-top n sel-mode))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1646 1647 1648 1649 1650 1651 1652 1653 1654

(defun calc-top-list (&optional n m sel-mode)
  (or n (setq n 1))
  (or m (setq m 1))
  (calc-check-stack (+ n m -1))
  (and (> n 0)
       (let ((top (copy-sequence (nthcdr (+ m calc-stack-top -1)
					 calc-stack))))
	 (setcdr (nthcdr (1- n) top) nil)
1655
	 (nreverse (mapcar 'calc-get-stack-element top)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1656 1657 1658

(defun calc-top-list-n (&optional n m sel-mode)
  (mapcar 'math-check-complete
1659
	  (mapcar 'calc-normalize (calc-top-list n m sel-mode))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690


(defun calc-renumber-stack ()
  (if calc-line-numbering
      (save-excursion
	(calc-cursor-stack-index 0)
	(let ((lnum 1)
	      (buffer-read-only nil)
	      (stack (nthcdr calc-stack-top calc-stack)))
	  (if (re-search-forward "^[0-9]+[:*]" nil t)
	      (progn
		(beginning-of-line)
		(while (re-search-forward "^[0-9]+[:*]" nil t)
		  (let ((buffer-read-only nil))
		    (beginning-of-line)
		    (delete-char 4)
		    (insert "    ")))
		(calc-cursor-stack-index 0)))
	  (while (re-search-backward "^[0-9]+[:*]" nil t)
	    (delete-char 4)
	    (if (> lnum 999)
		(insert (format "%03d%s" (% lnum 1000)
				(if (and (nth 2 (car stack))
					 calc-use-selections) "*" ":")))
	      (let ((prefix (int-to-string lnum)))
		(insert prefix (if (and (nth 2 (car stack))
					calc-use-selections) "*" ":")
			(make-string (- 3 (length prefix)) 32))))
	    (beginning-of-line)
	    (setq lnum (1+ lnum)
		  stack (cdr stack))))))
1691
  (and calc-embedded-info (calc-embedded-stack-change)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723

(defun calc-refresh (&optional align)
  (interactive)
  (and (eq major-mode 'calc-mode)
       (not calc-executing-macro)
       (let* ((buffer-read-only nil)
	      (save-point (point))
	      (save-mark (condition-case err (mark) (error nil)))
	      (save-aligned (looking-at "\\.$"))
	      (thing calc-stack))
	 (setq calc-any-selections nil
	       calc-any-evaltos nil)
	 (erase-buffer)
	 (insert "--- Emacs Calculator Mode ---\n")
	 (while thing
	   (goto-char (point-min))
	   (forward-line 1)
	   (insert (math-format-stack-value (car thing)) "\n")
	   (setq thing (cdr thing)))
	 (calc-renumber-stack)
	 (if calc-display-dirty
	     (calc-wrapper (setq calc-display-dirty nil)))
	 (and calc-any-evaltos calc-auto-recompute
	      (calc-wrapper (calc-refresh-evaltos)))
	 (if (or align save-aligned)
	     (calc-align-stack-window)
	   (goto-char save-point))
	 (if save-mark (set-mark save-mark))))
  (and calc-embedded-info (not (eq major-mode 'calc-mode))
       (save-excursion
	 (set-buffer (aref calc-embedded-info 1))
	 (calc-refresh align)))
1724
  (setq calc-refresh-count (1+ calc-refresh-count)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742


(defun calc-x-paste-text (arg)
  "Move point to mouse position and insert window system cut buffer contents.
If mouse is pressed in Calc window, push cut buffer contents onto the stack."
  (x-mouse-select arg)
  (if (memq major-mode '(calc-mode calc-trail-mode))
      (progn
	(calc-wrapper
	 (calc-extensions)
	 (let* ((buf (x-get-cut-buffer))
		(val (math-read-exprs (calc-clean-newlines buf))))
	   (if (eq (car-safe val) 'error)
	       (progn
		 (setq val (math-read-exprs buf))
		 (if (eq (car-safe val) 'error)
		     (error "%s in yanked data" (nth 2 val)))))
	   (calc-enter-result 0 "Xynk" val))))
1743
    (x-paste-text arg)))
Eli Zaretskii's avatar
Eli Zaretskii committed
1744 1745 1746 1747 1748 1749 1750 1751 1752



;;;; The Calc Trail buffer.

(defun calc-check-trail-aligned ()
  (save-excursion
    (let ((win (get-buffer-window (current-buffer))))
      (and win
1753
	   (pos-visible-in-window-p (1- (point-max)) win)))))
Eli Zaretskii's avatar
Eli Zaretskii committed
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771

(defun calc-trail-buffer ()
  (and (or (null calc-trail-buffer)
	   (null (buffer-name calc-trail-buffer)))
       (save-excursion
	 (setq calc-trail-buffer (get-buffer-create "*Calc Trail*"))
	 (let ((buf (or (and (not (eq major-mode 'calc-mode))
			     (get-buffer "*Calculator*"))
			(current-buffer))))
	   (set-buffer calc-trail-buffer)
	   (or (eq major-mode 'calc-trail-mode)
	       (calc-trail-mode buf)))))
  (or (and calc-trail-pointer
	   (eq (marker-buffer calc-trail-pointer) calc-trail-buffer))
      (save-excursion
	(set-buffer calc-trail-buffer)
	(goto-line 2)
	(setq calc-trail-pointer (point-marker))))
1772
  calc-trail-buffer)
Eli Zaretskii's avatar
Eli Zaretskii committed
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801

(defun calc-record (val &optional prefix)
  (setq calc-aborted-prefix nil)
  (or calc-executing-macro
      (let* ((mainbuf (current-buffer))
	     (buf (calc-trail-buffer))
	     (calc-display-raw nil)
	     (calc-can-abbrev-vectors t)
	     (fval (if val
		       (if (stringp val)
			   val
			 (math-showing-full-precision
			  (math-format-flat-expr val 0)))
		     "")))
	(save-excursion
	  (set-buffer buf)
	  (let ((aligned (calc-check-trail-aligned))
		(buffer-read-only nil))
	    (goto-char (point-max))
	    (cond ((null prefix) (insert "     "))
		  ((and (> (length prefix) 4)
			(string-match " " prefix 4))
		   (insert (substring prefix 0 4) " "))
		  (t (insert (format "%4s " prefix))))
	    (insert fval "\n")
	    (let ((win (get-buffer-window buf)))
	      (if (and aligned win (not (memq 'hold-trail calc-command-flags)))
		  (calc-trail-here))
	      (goto-char (1- (point-max))))))))
1802
  val)
Eli Zaretskii's avatar
Eli Zaretskii committed
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830


(defun calc-trail-display (flag &optional no-refresh)
  (interactive "P")
  (let ((win (get-buffer-window (calc-trail-buffer))))
    (if (setq calc-display-trail
	      (not (if flag (memq flag '(nil 0)) win)))
	(if (null win)
	    (progn
	      (if (and (boundp 'calc-trail-window-hook) calc-trail-window-hook)
		  (run-hooks 'calc-trail-window-hook)
		(let ((w (split-window nil (/ (* (window-width) 2) 3) t)))
		  (set-window-buffer w calc-trail-buffer)))
	      (calc-wrapper
	       (setq overlay-arrow-string calc-trail-overlay
		     overlay-arrow-position calc-trail-pointer)
	       (or no-refresh
		   (if (interactive-p)
		       (calc-do-refresh)
		     (calc-refresh))))))
      (if win
	  (progn
	    (delete-window win)
	    (calc-wrapper
	     (or no-refresh
		 (if (interactive-p)
		     (calc-do-refresh)
		   (calc-refresh))))))))
1831
  calc-trail-buffer)
Eli Zaretskii's avatar
Eli Zaretskii committed
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844