calc.el 138 KB

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