ses.el 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131
  1. ;;; ses.el -- Simple Emacs Spreadsheet -*- lexical-binding:t -*-
  2. ;; Copyright (C) 2002-2017 Free Software Foundation, Inc.
  3. ;; Author: Jonathan Yavner <jyavner@member.fsf.org>
  4. ;; Maintainer: Vincent Belaïche <vincentb1@users.sourceforge.net>
  5. ;; Keywords: spreadsheet Dijkstra
  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. ;;; To-do list:
  19. ;; * M-w should deactivate the mark.
  20. ;; * offer some way to use absolute cell addressing.
  21. ;; * Maybe some way to copy a reference to a cell's formula rather than the
  22. ;; formula itself.
  23. ;; * split (catch 'cycle ...) call back into one or more functions
  24. ;; * Use $ or … for truncated fields
  25. ;; * M-t to transpose 2 columns.
  26. ;; * M-d should kill the cell under point.
  27. ;; * C-t to transpose 2 rows.
  28. ;; * C-k and M-k should be ses-kill-row and ses-kill-column.
  29. ;; * C-o should insert the row below point rather than above?
  30. ;; * rows inserted with C-o should inherit formulas from surrounding rows.
  31. ;; * Add command to make a range of columns be temporarily invisible.
  32. ;; * Allow paste of one cell to a range of cells -- copy formula to each.
  33. ;; * Do something about control characters & octal codes in cell print
  34. ;; areas. Use string-width?
  35. ;; * Input validation functions. How specified?
  36. ;; * Faces (colors & styles) in print cells.
  37. ;; * Move a column by dragging its letter in the header line.
  38. ;; * Left-margin column for row number.
  39. ;; * Move a row by dragging its number in the left-margin.
  40. ;;; Cycle detection
  41. ;; Cycles used to be detected by stationarity of ses--deferred-recalc. This was
  42. ;; working fine in most cases, however failed in some cases of several path
  43. ;; racing together.
  44. ;;
  45. ;; The current algorithm is based on Dijkstra's algorithm. The cycle length is
  46. ;; stored in some cell property. In order not to reset in all cells such
  47. ;; property at each update, the cycle length is stored in this property along
  48. ;; with some update attempt id that is incremented at each update. The current
  49. ;; update id is ses--Dijkstra-attempt-nb. In case there is a cycle the cycle
  50. ;; length diverge to infinite so it will exceed ses--Dijkstra-weight-bound at
  51. ;; some point of time that allows detection. Otherwise it converges to the
  52. ;; longest path length in the update tree.
  53. ;;; Code:
  54. (require 'unsafep)
  55. (require 'macroexp)
  56. (eval-when-compile (require 'cl-lib))
  57. ;;----------------------------------------------------------------------------
  58. ;; User-customizable variables
  59. ;;----------------------------------------------------------------------------
  60. (defgroup ses nil
  61. "Simple Emacs Spreadsheet."
  62. :tag "SES"
  63. :group 'applications
  64. :link '(custom-manual "(ses) Top")
  65. :prefix "ses-"
  66. :version "21.1")
  67. (defcustom ses-initial-size '(1 . 1)
  68. "Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
  69. :group 'ses
  70. :type '(cons (integer :tag "numrows") (integer :tag "numcols")))
  71. (defcustom ses-initial-column-width 7
  72. "Initial width of columns in a new spreadsheet."
  73. :group 'ses
  74. :type '(integer :match (lambda (widget value) (> value 0))))
  75. (defcustom ses-initial-default-printer "%.7g"
  76. "Initial default printer for a new spreadsheet."
  77. :group 'ses
  78. :type '(choice string
  79. (list :tag "Parenthesized string" string)
  80. function))
  81. (defcustom ses-after-entry-functions '(forward-char)
  82. "Things to do after entering a value into a cell.
  83. An abnormal hook that usually runs a cursor-movement function.
  84. Each function is called with ARG=1."
  85. :group 'ses
  86. :type 'hook
  87. :options '(forward-char backward-char next-line previous-line))
  88. (defcustom ses-mode-hook nil
  89. "Hook functions to be run upon entering SES mode."
  90. :group 'ses
  91. :type 'hook)
  92. ;;----------------------------------------------------------------------------
  93. ;; Global variables and constants
  94. ;;----------------------------------------------------------------------------
  95. (defvar ses-read-cell-history nil
  96. "List of formulas that have been typed in.")
  97. (defvar ses-read-printer-history nil
  98. "List of printer functions that have been typed in.")
  99. (easy-menu-define ses-header-line-menu nil
  100. "Context menu when mouse-3 is used on the header-line in an SES buffer."
  101. '("SES header row"
  102. ["Set current row" ses-set-header-row t]
  103. ["Unset row" ses-unset-header-row (> ses--header-row 0)]))
  104. (defconst ses-mode-map
  105. (let ((keys `("\C-c\M-\C-l" ses-reconstruct-all
  106. "\C-c\C-l" ses-recalculate-all
  107. "\C-c\C-n" ses-renarrow-buffer
  108. "\C-c\C-c" ses-recalculate-cell
  109. "\C-c\M-\C-s" ses-sort-column
  110. "\C-c\M-\C-h" ses-set-header-row
  111. "\C-c\C-t" ses-truncate-cell
  112. "\C-c\C-j" ses-jump
  113. "\C-c\C-p" ses-read-default-printer
  114. "\M-\C-l" ses-reprint-all
  115. [?\S-\C-l] ses-reprint-all
  116. [header-line down-mouse-3] ,ses-header-line-menu
  117. [header-line mouse-2] ses-sort-column-click))
  118. (newmap (make-sparse-keymap)))
  119. (while keys
  120. (define-key (1value newmap) (car keys) (cadr keys))
  121. (setq keys (cddr keys)))
  122. newmap)
  123. "Local keymap for Simple Emacs Spreadsheet.")
  124. (easy-menu-define ses-menu ses-mode-map
  125. "Menu bar menu for SES."
  126. '("SES"
  127. ["Insert row" ses-insert-row (ses-in-print-area)]
  128. ["Delete row" ses-delete-row (ses-in-print-area)]
  129. ["Insert column" ses-insert-column (ses-in-print-area)]
  130. ["Delete column" ses-delete-column (ses-in-print-area)]
  131. ["Set column printer" ses-read-column-printer t]
  132. ["Set column width" ses-set-column-width t]
  133. ["Set default printer" ses-read-default-printer t]
  134. ["Jump to cell" ses-jump t]
  135. ["Set cell printer" ses-read-cell-printer t]
  136. ["Recalculate cell" ses-recalculate-cell t]
  137. ["Truncate cell display" ses-truncate-cell t]
  138. ["Export values" ses-export-tsv t]
  139. ["Export formulas" ses-export-tsf t]))
  140. (defconst ses-completion-keys '("\M-\C-i" "\C-i")
  141. "List for keys that can be used for completion while editing.")
  142. (defvar ses--completion-table nil
  143. "Set globally to what completion table to use depending on type
  144. of completion (local printers, cells, etc.). We need to go
  145. through a local variable to pass the SES buffer local variable
  146. to completing function while the current buffer is the
  147. minibuffer.")
  148. (defvar ses--list-orig-buffer nil
  149. "Calling buffer for SES listing help. Used for listing local
  150. printers or renamed cells.")
  151. (defconst ses-mode-edit-map
  152. (let ((keys '("\C-c\C-r" ses-insert-range
  153. "\C-c\C-s" ses-insert-ses-range
  154. [S-mouse-3] ses-insert-range-click
  155. [C-S-mouse-3] ses-insert-ses-range-click
  156. "\C-h\C-p" ses-list-local-printers
  157. "\C-h\C-n" ses-list-named-cells
  158. "\M-\C-i" lisp-complete-symbol)) ; redefined
  159. ; dynamically in
  160. ; editing
  161. ; functions
  162. (newmap (make-sparse-keymap)))
  163. (set-keymap-parent newmap minibuffer-local-map)
  164. (while keys
  165. (define-key newmap (pop keys) (pop keys)))
  166. newmap)
  167. "Local keymap for SES minibuffer cell-editing.")
  168. ;Local keymap for SES print area
  169. (defalias 'ses-mode-print-map
  170. (let ((keys '([backtab] backward-char
  171. [tab] ses-forward-or-insert
  172. "\C-i" ses-forward-or-insert ; Needed for ses-coverage.el?
  173. "\M-o" ses-insert-column
  174. "\C-o" ses-insert-row
  175. "\C-m" ses-edit-cell
  176. "\M-k" ses-delete-column
  177. "\M-y" ses-yank-pop
  178. "\C-k" ses-delete-row
  179. "\C-j" ses-append-row-jump-first-column
  180. "\M-h" ses-mark-row
  181. "\M-H" ses-mark-column
  182. "\C-d" ses-clear-cell-forward
  183. "\C-?" ses-clear-cell-backward
  184. "(" ses-read-cell
  185. "\"" ses-read-cell
  186. "'" ses-read-symbol
  187. "=" ses-edit-cell
  188. "c" ses-recalculate-cell
  189. "j" ses-jump
  190. "p" ses-read-cell-printer
  191. "t" ses-truncate-cell
  192. "w" ses-set-column-width
  193. "x" ses-export-keymap
  194. "\M-p" ses-read-column-printer))
  195. (repl '(;;We'll replace these wherever they appear in the keymap
  196. clipboard-kill-region ses-kill-override
  197. end-of-line ses-end-of-line
  198. kill-line ses-delete-row
  199. kill-region ses-kill-override
  200. open-line ses-insert-row))
  201. (numeric "0123456789.-")
  202. (newmap (make-keymap)))
  203. ;;Get rid of printables
  204. (suppress-keymap newmap t)
  205. ;;These keys insert themselves as the beginning of a numeric value
  206. (dotimes (x (length numeric))
  207. (define-key newmap (substring numeric x (1+ x)) 'ses-read-cell))
  208. ;;Override these global functions wherever they're bound
  209. (while repl
  210. (substitute-key-definition (car repl) (cadr repl) newmap
  211. (current-global-map))
  212. (setq repl (cddr repl)))
  213. ;;Apparently substitute-key-definition doesn't catch this?
  214. (define-key newmap [(menu-bar) edit cut] 'ses-kill-override)
  215. ;;Define our other local keys
  216. (while keys
  217. (define-key newmap (car keys) (cadr keys))
  218. (setq keys (cddr keys)))
  219. newmap))
  220. ;;Helptext for ses-mode wants keymap as variable, not function
  221. (defconst ses-mode-print-map (symbol-function 'ses-mode-print-map))
  222. ;;Key map used for 'x' key.
  223. (defalias 'ses-export-keymap
  224. (let ((map (make-sparse-keymap "SES export")))
  225. (define-key map "T" (cons " tab-formulas" 'ses-export-tsf))
  226. (define-key map "t" (cons " tab-values" 'ses-export-tsv))
  227. map))
  228. (defconst ses-print-data-boundary "\n\014\n"
  229. "Marker string denoting the boundary between print area and data area.")
  230. (defconst ses-initial-global-parameters
  231. "\n( ;Global parameters (these are read first)\n 2 ;SES file-format\n 1 ;numrows\n 1 ;numcols\n)\n\n"
  232. "Initial contents for the three-element list at the bottom of the data area.")
  233. (defconst ses-initial-global-parameters-re
  234. "\n( ;Global parameters (these are read first)\n [23] ;SES file-format\n [0-9]+ ;numrows\n [0-9]+ ;numcols\n\\( [0-9]+ ;numlocprn\n\\)?)\n\n"
  235. "Match Global parameters for .")
  236. (defconst ses-initial-file-trailer
  237. ";; Local Variables:\n;; mode: ses\n;; End:\n"
  238. "Initial contents for the file-trailer area at the bottom of the file.")
  239. (defconst ses-initial-file-contents
  240. (concat " \n" ; One blank cell in print area.
  241. ses-print-data-boundary
  242. "(ses-cell A1 nil nil nil nil)\n" ; One blank cell in data area.
  243. "\n" ; End-of-row terminator for the one row in data area.
  244. "(ses-column-widths [7])\n"
  245. "(ses-column-printers [nil])\n"
  246. "(ses-default-printer \"%.7g\")\n"
  247. "(ses-header-row 0)\n"
  248. ses-initial-global-parameters
  249. ses-initial-file-trailer)
  250. "The initial contents of an empty spreadsheet.")
  251. (defconst ses-box-prop '(:box (:line-width 2 :style released-button))
  252. "Display properties to create a raised box for cells in the header line.")
  253. (defconst ses-standard-printer-functions
  254. '(ses-center
  255. ses-center-span ses-dashfill ses-dashfill-span
  256. ses-tildefill-span
  257. ses-prin1)
  258. "List of print functions to be included in initial history of
  259. printer functions. None of these standard-printer functions,
  260. except function `ses-prin1', is suitable for use as a column
  261. printer or a global-default printer because they invoke the
  262. column or default printer and then modify its output.")
  263. ;;----------------------------------------------------------------------------
  264. ;; Local variables and constants
  265. ;;----------------------------------------------------------------------------
  266. (eval-and-compile
  267. (defconst ses-localvars
  268. '(ses--blank-line ses--cells ses--col-printers
  269. ses--col-widths ses--curcell ses--curcell-overlay
  270. ses--default-printer
  271. (ses--local-printer-hashmap . :hashmap)
  272. (ses--numlocprn . 0); count of local printers
  273. ses--deferred-narrow ses--deferred-recalc
  274. ses--deferred-write ses--file-format
  275. ses--named-cell-hashmap
  276. (ses--header-hscroll . -1) ; Flag for "initial recalc needed"
  277. ses--header-row ses--header-string ses--linewidth
  278. ses--numcols ses--numrows ses--symbolic-formulas
  279. ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
  280. ses--Dijkstra-weight-bound
  281. ;; This list is useful for clean-up of symbols when an area
  282. ;; containing renamed cell is deleted.
  283. ses--in-killing-named-cell-list
  284. ;; Global variables that we override
  285. next-line-add-newlines transient-mark-mode)
  286. "Buffer-local variables used by SES."))
  287. (defmacro ses--metaprogramming (exp) (declare (debug t)) (eval exp t))
  288. (ses--metaprogramming
  289. `(progn ,@(mapcar (lambda (x) `(defvar ,(or (car-safe x) x))) ses-localvars)))
  290. (defun ses-set-localvars ()
  291. "Set buffer-local and initialize some SES variables."
  292. (dolist (x ses-localvars)
  293. (cond
  294. ((symbolp x)
  295. (set (make-local-variable x) nil))
  296. ((consp x)
  297. (cond
  298. ((integerp (cdr x))
  299. (set (make-local-variable (car x)) (cdr x)))
  300. ((eq (cdr x) :hashmap)
  301. (set (make-local-variable (car x)) (make-hash-table :test 'eq)))
  302. (t (error "Unexpected initializer `%S' in list `ses-localvars' for entry %S"
  303. (cdr x) (car x)) ) ))
  304. (t (error "Unexpected elements `%S' in list `ses-localvars'" x)))))
  305. ;;; This variable is documented as being permitted in file-locals:
  306. (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
  307. (defconst ses-paramlines-plist
  308. '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
  309. ses--header-row -2 ses--file-format 1 ses--numrows 2
  310. ses--numcols 3 ses--numlocprn 4)
  311. "Offsets from \"Global parameters\" line to various parameter lines in the
  312. data area of a spreadsheet.")
  313. (defconst ses-paramfmt-plist
  314. '(ses--col-widths "(ses-column-widths %S)"
  315. ses--col-printers "(ses-column-printers %S)"
  316. ses--default-printer "(ses-default-printer %S)"
  317. ses--header-row "(ses-header-row %S)"
  318. ses--file-format " %S ;SES file-format"
  319. ses--numrows " %S ;numrows"
  320. ses--numcols " %S ;numcols"
  321. ses--numlocprn " %S ;numlocprn")
  322. "Formats of \"Global parameters\" various parameters in the data
  323. area of a spreadsheet.")
  324. ;;
  325. ;; "Side-effect variables". They are set in one function, altered in
  326. ;; another as a side effect, then read back by the first, as a way of
  327. ;; passing back more than one value. These declarations are just to make
  328. ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
  329. ;; think the make-local-variable trick above is cleaner).
  330. ;;
  331. (defvar ses-relocate-return nil
  332. "Set by `ses-relocate-formula' and `ses-relocate-range', read by
  333. `ses-relocate-all'. Set to `delete' if a cell-reference was deleted from a
  334. formula--so the formula needs recalculation. Set to `range' if the size of a
  335. `ses-range' was changed--so both the formula's value and list of dependents
  336. need to be recalculated.")
  337. (defvar ses-call-printer-return nil
  338. "Set to t if last cell printer invoked by `ses-call-printer' requested
  339. left-justification of the result. Set to error-signal if `ses-call-printer'
  340. encountered an error during printing. Otherwise nil.")
  341. (defvar ses-start-time nil
  342. "Time when current operation started. Used by `ses-time-check' to decide
  343. when to emit a progress message.")
  344. ;;----------------------------------------------------------------------------
  345. ;; Macros
  346. ;;----------------------------------------------------------------------------
  347. (defmacro ses-get-cell (row col)
  348. "Return the cell structure that stores information about cell (ROW,COL)."
  349. (declare (debug t))
  350. `(aref (aref ses--cells ,row) ,col))
  351. (cl-defstruct (ses-cell
  352. (:constructor nil)
  353. (:constructor ses-make-cell
  354. (&optional symbol formula printer references))
  355. (:copier nil)
  356. ;; This is treated as an 4-elem array in various places.
  357. ;; Mostly in ses-set-cell.
  358. (:type vector) ;Not named.
  359. (:conc-name ses-cell--))
  360. symbol formula printer references properties)
  361. (cl-defstruct (ses--locprn
  362. (:constructor)
  363. (:constructor ses-make-local-printer-info
  364. (def &optional (compiled (ses-local-printer-compile def))
  365. (number ses--numlocprn))))
  366. def
  367. compiled
  368. number
  369. local-printer-list)
  370. (defmacro ses-cell-symbol (row &optional col)
  371. "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
  372. (declare (debug t))
  373. `(ses-cell--symbol ,(if col `(ses-get-cell ,row ,col) row)))
  374. (put 'ses-cell-symbol 'safe-function t)
  375. (defmacro ses-cell-formula (row &optional col)
  376. "From a CELL or a pair (ROW,COL), get the function that computes its value."
  377. (declare (debug t))
  378. `(ses-cell--formula ,(if col `(ses-get-cell ,row ,col) row)))
  379. (defmacro ses-cell-printer (row &optional col)
  380. "From a CELL or a pair (ROW,COL), get the function that prints its value."
  381. (declare (debug t))
  382. `(ses-cell--printer ,(if col `(ses-get-cell ,row ,col) row)))
  383. (defmacro ses-cell-references (row &optional col)
  384. "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
  385. functions refer to its value."
  386. (declare (debug t))
  387. `(ses-cell--references ,(if col `(ses-get-cell ,row ,col) row)))
  388. (defmacro ses-sym-rowcol (sym)
  389. "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0). Result
  390. is nil if SYM is not a symbol that names a cell."
  391. (declare (debug t))
  392. `(let ((rc (and (symbolp ,sym) (get ,sym 'ses-cell))))
  393. (if (eq rc :ses-named)
  394. (and ses--named-cell-hashmap (gethash ,sym ses--named-cell-hashmap))
  395. rc)))
  396. (defun ses-cell-p (cell)
  397. "Return non-nil if CELL is a cell of current buffer."
  398. (and (vectorp cell)
  399. (= (length cell) 5)
  400. (eq cell (let ((rowcol (ses-sym-rowcol (ses-cell-symbol cell))))
  401. (and (consp rowcol)
  402. (ses-get-cell (car rowcol) (cdr rowcol)))))))
  403. (defun ses-plist-delq (plist prop)
  404. "Return PLIST after deleting the first pair (if any) with symbol PROP.
  405. This can alter PLIST."
  406. (cond
  407. ((null plist) nil)
  408. ((eq (car plist) prop) (cddr plist))
  409. (t (let* ((plist-1 (cdr plist))
  410. (plist-2 (cdr plist-1)))
  411. (setcdr plist-1 (ses-plist-delq plist-2 prop))
  412. plist))))
  413. (defvar ses--ses-buffer-list nil "A list of buffers containing a SES spreadsheet.")
  414. (defun ses--unbind-cell-name (name)
  415. "Make NAME non longer a renamed cell name."
  416. (remhash name ses--named-cell-hashmap)
  417. (kill-local-variable name)
  418. ;; remove symbol property 'ses-cell from symbol NAME, unless this
  419. ;; symbol is also a renamed cell name in another SES buffer.
  420. (let (used-elsewhere (buffer-list ses--ses-buffer-list) buf)
  421. (while buffer-list
  422. (setq buf (pop buffer-list))
  423. (cond
  424. ((eq buf (current-buffer)))
  425. ;; This case should not happen, some SES buffer has been
  426. ;; killed without the ses-killbuffer-hook being called.
  427. ((null (buffer-live-p buf))
  428. ;; Silently repair ses--ses-buffer-list
  429. (setq ses--ses-buffer-list (delq buf ses--ses-buffer-list)))
  430. (t
  431. (with-current-buffer buf
  432. (when (gethash name ses--named-cell-hashmap)
  433. (setq used-elsewhere t
  434. buffer-list nil))))))
  435. (unless used-elsewhere
  436. (setplist name (ses-plist-delq (symbol-plist name) 'ses-cell))) ))
  437. (defmacro ses--letref (vars place &rest body)
  438. (declare (indent 2) (debug (sexp form &rest body)))
  439. (gv-letplace (getter setter) place
  440. `(cl-macrolet ((,(nth 0 vars) () ',getter)
  441. (,(nth 1 vars) (v) (funcall ',setter v)))
  442. ,@body)))
  443. (defmacro ses-cell-property (property-name row &optional col)
  444. "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
  445. When COL is omitted, CELL=ROW is a cell object. When COL is
  446. present ROW and COL are the integer coordinates of the cell of
  447. interest."
  448. (declare (debug t))
  449. `(alist-get ,property-name
  450. (ses-cell--properties
  451. ,(if col `(ses-get-cell ,row ,col) row))))
  452. (defmacro ses-cell-property-pop (property-name row &optional col)
  453. "From a CELL or a pair (ROW,COL), get and remove the property value of
  454. the corresponding cell with name PROPERTY-NAME."
  455. `(ses--letref (pget pset)
  456. (alist-get ,property-name
  457. (ses-cell--properties
  458. ,(if col `(ses-get-cell ,row ,col) row))
  459. nil t)
  460. (prog1 (pget) (pset nil))))
  461. (defmacro ses-cell-value (row &optional col)
  462. "From a CELL or a pair (ROW,COL), get the current value for that cell."
  463. (declare (debug t))
  464. `(symbol-value (ses-cell-symbol ,row ,col)))
  465. (defmacro ses-col-width (col)
  466. "Return the width for column COL."
  467. (declare (debug t))
  468. `(aref ses--col-widths ,col))
  469. (defmacro ses-col-printer (col)
  470. "Return the default printer for column COL."
  471. (declare (debug t))
  472. `(aref ses--col-printers ,col))
  473. (defun ses-is-cell-sym-p (sym)
  474. "Check whether SYM point at a cell of this spread sheet."
  475. (let ((rowcol (get sym 'ses-cell)))
  476. (and rowcol
  477. (if (eq rowcol :ses-named)
  478. (and ses--named-cell-hashmap (gethash sym ses--named-cell-hashmap))
  479. (and (< (car rowcol) ses--numrows)
  480. (< (cdr rowcol) ses--numcols)
  481. (eq (ses-cell-symbol (car rowcol) (cdr rowcol)) sym))))))
  482. (defun ses--cell (sym value formula printer references)
  483. "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
  484. FORMULA, does not reprint using PRINTER, does not check REFERENCES.
  485. Safety-checking for FORMULA and PRINTER are deferred until first use."
  486. (let ((rowcol (ses-sym-rowcol sym)))
  487. (ses-formula-record formula)
  488. (ses-printer-record printer)
  489. (unless (or formula (eq value '*skip*))
  490. (setq formula (macroexp-quote value)))
  491. (or (atom formula)
  492. (eq safe-functions t)
  493. (setq formula `(ses-safe-formula ,formula)))
  494. (or (not printer)
  495. (stringp printer)
  496. (eq safe-functions t)
  497. (setq printer `(ses-safe-printer ,printer)))
  498. (setf (ses-get-cell (car rowcol) (cdr rowcol))
  499. (ses-make-cell sym formula printer references)))
  500. (set sym value))
  501. (defun ses-local-printer-compile (printer)
  502. "Convert local printer function into faster printer
  503. definition."
  504. (cond
  505. ((functionp printer) printer)
  506. ((stringp printer)
  507. `(lambda (x)
  508. (if (null x) ""
  509. (format ,printer x))))
  510. ((stringp (car-safe printer))
  511. `(lambda (x)
  512. (if (null x) ""
  513. (setq ses-call-printer-return t)
  514. (format ,(car printer) x))))
  515. (t (error "Invalid printer %S" printer))))
  516. (defun ses--local-printer (name def)
  517. "Define a local printer with name NAME and definition DEF.
  518. Return the printer info."
  519. (or
  520. (and (symbolp name)
  521. (ses-printer-validate def))
  522. (error "Invalid local printer definition"))
  523. (and (gethash name ses--local-printer-hashmap)
  524. (error "Duplicate printer definition %S" name))
  525. (add-to-list 'ses-read-printer-history (symbol-name name))
  526. (puthash name
  527. (ses-make-local-printer-info (ses-safe-printer def))
  528. ses--local-printer-hashmap))
  529. (defmacro ses-column-widths (widths)
  530. "Load the vector of column widths from the spreadsheet file. This is a
  531. macro to prevent propagate-on-load viruses."
  532. (or (and (vectorp widths) (= (length widths) ses--numcols))
  533. (error "Bad column-width vector"))
  534. ;;To save time later, we also calculate the total width of each line in the
  535. ;;print area (excluding the terminating newline)
  536. (setq ses--col-widths widths
  537. ses--linewidth (apply #'+ -1 (mapcar #'1+ widths))
  538. ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
  539. t)
  540. (defmacro ses-column-printers (printers)
  541. "Load the vector of column printers from the spreadsheet file and checks
  542. them for safety. This is a macro to prevent propagate-on-load viruses."
  543. (or (and (vectorp printers) (= (length printers) ses--numcols))
  544. (error "Bad column-printers vector"))
  545. (dotimes (x ses--numcols)
  546. (aset printers x (ses-safe-printer (aref printers x))))
  547. (setq ses--col-printers printers)
  548. (mapc #'ses-printer-record printers)
  549. t)
  550. (defmacro ses-default-printer (def)
  551. "Load the global default printer from the spreadsheet file and checks it
  552. for safety. This is a macro to prevent propagate-on-load viruses."
  553. (setq ses--default-printer (ses-safe-printer def))
  554. (ses-printer-record def)
  555. t)
  556. (defmacro ses-header-row (row)
  557. "Load the header row from the spreadsheet file and checks it
  558. for safety. This is a macro to prevent propagate-on-load viruses."
  559. (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
  560. (error "Bad header-row"))
  561. (setq ses--header-row row)
  562. t)
  563. (defmacro ses-dorange (curcell &rest body)
  564. "Execute BODY repeatedly, with the variables `row' and `col' set to each
  565. cell in the range specified by CURCELL. The range is available in the
  566. variables `minrow', `maxrow', `mincol', and `maxcol'."
  567. (declare (indent defun) (debug (form body)))
  568. (let ((cur (make-symbol "cur"))
  569. (min (make-symbol "min"))
  570. (max (make-symbol "max"))
  571. (r (make-symbol "r"))
  572. (c (make-symbol "c")))
  573. `(let* ((,cur ,curcell)
  574. (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
  575. (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
  576. (let ((minrow (car ,min))
  577. (maxrow (car ,max))
  578. (mincol (cdr ,min))
  579. (maxcol (cdr ,max)))
  580. (if (or (> minrow maxrow) (> mincol maxcol))
  581. (error "Empty range"))
  582. (dotimes (,r (- maxrow minrow -1))
  583. (let ((row (+ ,r minrow)))
  584. (dotimes (,c (- maxcol mincol -1))
  585. (let ((col (+ ,c mincol)))
  586. ,@body))))))))
  587. ;;Support for coverage testing.
  588. (defmacro 1value (form)
  589. "For code-coverage testing, indicate that FORM is expected to always have
  590. the same value."
  591. (declare (debug t))
  592. form)
  593. (defmacro noreturn (form)
  594. "For code-coverage testing, indicate that FORM will always signal an error."
  595. (declare (debug t))
  596. form)
  597. ;;----------------------------------------------------------------------------
  598. ;; Utility functions
  599. ;;----------------------------------------------------------------------------
  600. (defun ses-vector-insert (array idx new)
  601. "Create a new vector which is one larger than ARRAY and has NEW inserted
  602. before element IDX."
  603. (let* ((len (length array))
  604. (result (make-vector (1+ len) new)))
  605. (dotimes (x len)
  606. (aset result
  607. (if (< x idx) x (1+ x))
  608. (aref array x)))
  609. result))
  610. ;;Allow ARRAY to be a symbol for use in buffer-undo-list
  611. (defun ses-vector-delete (array idx count)
  612. "Create a new vector which is a copy of ARRAY with COUNT objects removed
  613. starting at element IDX. ARRAY is either a vector or a symbol whose value
  614. is a vector--if a symbol, the new vector is assigned as the symbol's value."
  615. (let* ((a (if (arrayp array) array (symbol-value array)))
  616. (len (- (length a) count))
  617. (result (make-vector len nil)))
  618. (dotimes (x len)
  619. (aset result x (aref a (if (< x idx) x (+ x count)))))
  620. (if (symbolp array)
  621. (set array result))
  622. result))
  623. (defun ses-delete-line (count)
  624. "Like `kill-line', but no kill ring."
  625. (let ((pos (point)))
  626. (forward-line count)
  627. (delete-region pos (point))))
  628. (defun ses-printer-validate (printer)
  629. "Signal an error if PRINTER is not a valid SES cell printer."
  630. (or (not printer)
  631. (stringp printer)
  632. ;; printer is a local printer
  633. (and (symbolp printer) (gethash printer ses--local-printer-hashmap))
  634. (functionp printer)
  635. (and (stringp (car-safe printer)) (not (cdr printer)))
  636. (error "Invalid printer function %S" printer))
  637. printer)
  638. (defun ses-printer-record (printer)
  639. "Add PRINTER to `ses-read-printer-history' if not already there, after first
  640. checking that it is a valid printer function."
  641. (ses-printer-validate printer)
  642. ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
  643. (if printer
  644. (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
  645. (defun ses-formula-record (formula)
  646. "If FORMULA is of the form \\='SYMBOL, add it to the list of symbolic formulas
  647. for this spreadsheet."
  648. (when (and (eq (car-safe formula) 'quote)
  649. (symbolp (cadr formula)))
  650. (add-to-list 'ses--symbolic-formulas
  651. (list (symbol-name (cadr formula))))))
  652. (defun ses-column-letter (col)
  653. "Return the alphabetic name of column number COL.
  654. 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
  655. (let ((units (char-to-string (+ ?A (% col 26)))))
  656. (if (< col 26)
  657. units
  658. (concat (ses-column-letter (1- (/ col 26))) units))))
  659. (defun ses-create-cell-symbol (row col)
  660. "Produce a symbol that names the cell (ROW,COL). (0,0) => A1."
  661. (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
  662. (defun ses-decode-cell-symbol (str)
  663. "Decode a symbol \"A1\" => (0,0). Return nil if STR is not a
  664. canonical cell name."
  665. (let (case-fold-search)
  666. (and (string-match "\\`\\([A-Z]+\\)\\([0-9]+\\)\\'" str)
  667. (let* ((col-str (match-string-no-properties 1 str))
  668. (col 0)
  669. (col-base 1)
  670. (col-idx (1- (length col-str)))
  671. (row (1- (string-to-number
  672. (match-string-no-properties 2 str)))))
  673. (and (>= row 0)
  674. (progn
  675. (while
  676. (progn
  677. (setq col (+ col (* (- (aref col-str col-idx) ?A)
  678. col-base))
  679. col-base (* col-base 26)
  680. col-idx (1- col-idx))
  681. (and (>= col-idx 0)
  682. (setq col (+ col col-base)))))
  683. (cons row col)))))))
  684. (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
  685. "Create buffer-local variables for cells. This is undoable."
  686. (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
  687. buffer-undo-list)
  688. (let (sym xrow xcol)
  689. (dotimes (row (1+ (- maxrow minrow)))
  690. (dotimes (col (1+ (- maxcol mincol)))
  691. (setq xrow (+ row minrow)
  692. xcol (+ col mincol)
  693. sym (ses-create-cell-symbol xrow xcol))
  694. (put sym 'ses-cell (cons xrow xcol))
  695. (make-local-variable sym)))))
  696. (defun ses-create-cell-variable (sym row col)
  697. "Create a buffer-local variable `SYM' for cell at position (ROW, COL).
  698. SYM is the symbol for that variable, ROW and COL are integers for
  699. row and column of the cell, with numbering starting from 0.
  700. Return nil in case of failure."
  701. (unless (local-variable-p sym)
  702. (make-local-variable sym)
  703. (if (let (case-fold-search) (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name sym)))
  704. (put sym 'ses-cell (cons row col))
  705. (put sym 'ses-cell :ses-named)
  706. (setq ses--named-cell-hashmap (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
  707. (puthash sym (cons row col) ses--named-cell-hashmap))))
  708. ;; We do not delete the ses-cell properties for the cell-variables, in
  709. ;; case a formula that refers to this cell is in the kill-ring and is
  710. ;; later pasted back in.
  711. (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
  712. "Destroy buffer-local variables for cells. This is undoable."
  713. (let (sym)
  714. (dotimes (row (1+ (- maxrow minrow)))
  715. (dotimes (col (1+ (- maxcol mincol)))
  716. (let ((xrow (+ row minrow)) (xcol (+ col mincol)))
  717. (setq sym (if (and (< xrow ses--numrows) (< xcol ses--numcols))
  718. (ses-cell-symbol xrow xcol)
  719. (ses-create-cell-symbol xrow xcol))))
  720. (if (boundp sym)
  721. (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
  722. buffer-undo-list))
  723. (kill-local-variable sym))))
  724. (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
  725. buffer-undo-list))
  726. (defun ses-reset-header-string ()
  727. "Flag the header string for update. Upon undo, the header string will be
  728. updated again."
  729. (push '(apply ses-reset-header-string) buffer-undo-list)
  730. (setq ses--header-hscroll -1))
  731. ;;Split this code off into a function to avoid coverage-testing difficulties
  732. (defmacro ses--time-check (format &rest args)
  733. "If `ses-start-time' is more than a second ago, call `message' with FORMAT
  734. and ARGS and reset `ses-start-time' to the current time."
  735. `(when (> (- (float-time) ses-start-time) 1.0)
  736. (message ,format ,@args)
  737. (setq ses-start-time (float-time))))
  738. ;;----------------------------------------------------------------------------
  739. ;; The cells
  740. ;;----------------------------------------------------------------------------
  741. (defmacro ses-set-cell (row col field val)
  742. "Install VAL as the contents for field FIELD (named by a quoted symbol) of
  743. cell (ROW,COL). This is undoable. The cell's data will be updated through
  744. `post-command-hook'."
  745. `(let ((row ,row)
  746. (col ,col)
  747. (val ,val))
  748. (let* ((cell (ses-get-cell row col))
  749. (change
  750. ,(let ((field (progn (cl-assert (eq (car field) 'quote))
  751. (cadr field))))
  752. (if (eq field 'value)
  753. `(ses-set-with-undo (ses-cell-symbol cell) val)
  754. ;; (let* ((slots (get 'ses-cell 'cl-struct-slots))
  755. ;; (slot (or (assq field slots)
  756. ;; (error "Unknown field %S" field)))
  757. ;; (idx (- (length slots)
  758. ;; (length (memq slot slots)))))
  759. ;; `(ses-aset-with-undo cell ,idx val))
  760. (let ((getter (intern-soft (format "ses-cell--%s" field))))
  761. `(ses-setter-with-undo
  762. (eval-when-compile
  763. (cons #',getter
  764. (lambda (newval cell)
  765. (setf (,getter cell) newval))))
  766. val cell))))))
  767. (if change
  768. (add-to-list 'ses--deferred-write (cons row col))))
  769. nil)) ; Make coverage-tester happy.
  770. (defun ses-cell-set-formula (row col formula)
  771. "Store a new formula for (ROW . COL) and enqueue the cell for
  772. recalculation via `post-command-hook'. Updates the reference lists for the
  773. cells that this cell refers to. Does not update cell value or reprint the
  774. cell. To avoid inconsistencies, this function is not interruptible, which
  775. means Emacs will crash if FORMULA contains a circular list."
  776. (let* ((cell (ses-get-cell row col))
  777. (old (ses-cell-formula cell)))
  778. (let ((sym (ses-cell-symbol cell))
  779. (oldref (ses-formula-references old))
  780. (newref (ses-formula-references formula))
  781. (inhibit-quit t)
  782. not-a-cell-ref-list
  783. x xrow xcol)
  784. (cl-pushnew sym ses--deferred-recalc)
  785. ;;Delete old references from this cell. Skip the ones that are also
  786. ;;in the new list.
  787. (dolist (ref oldref)
  788. (unless (memq ref newref)
  789. ;; because we do not cancel edit when the user provides a
  790. ;; false reference in it, then we need to check that ref
  791. ;; points to a cell that is within the spreadsheet.
  792. (setq x (ses-sym-rowcol ref))
  793. (and x
  794. (< (setq xrow (car x)) ses--numrows)
  795. (< (setq xcol (cdr x)) ses--numcols)
  796. (ses-set-cell xrow xcol 'references
  797. (delq sym (ses-cell-references xrow xcol))))))
  798. ;;Add new ones. Skip ones left over from old list
  799. (dolist (ref newref)
  800. (setq x (ses-sym-rowcol ref))
  801. ;;Do not trust the user, the reference may be outside the spreadsheet
  802. (if (and
  803. x
  804. (< (setq xrow (car x)) ses--numrows)
  805. (< (setq xcol (cdr x)) ses--numcols))
  806. (progn
  807. (setq x (ses-cell-references xrow xcol))
  808. (or (memq sym x)
  809. (ses-set-cell xrow xcol 'references (cons sym x))))
  810. (cl-pushnew ref not-a-cell-ref-list)))
  811. (ses-formula-record formula)
  812. (ses-set-cell row col 'formula formula)
  813. (and not-a-cell-ref-list
  814. (error "Found in formula cells not in spreadsheet: %S" not-a-cell-ref-list)))))
  815. (defun ses-repair-cell-reference-all ()
  816. "Repair cell reference and warn if there was some reference corruption."
  817. (interactive "*")
  818. (let (errors)
  819. ;; Step 1, reset :ses-repair-reference cell property in the whole sheet.
  820. (dotimes (row ses--numrows)
  821. (dotimes (col ses--numcols)
  822. (let ((references (ses-cell-property-pop :ses-repair-reference
  823. row col)))
  824. (when references
  825. (push (list (ses-cell-symbol row col)
  826. :corrupt-property
  827. references)
  828. errors)))))
  829. ;; Step 2, build new.
  830. (dotimes (row ses--numrows)
  831. (dotimes (col ses--numcols)
  832. (let* ((cell (ses-get-cell row col))
  833. (sym (ses-cell-symbol cell))
  834. (formula (ses-cell-formula cell))
  835. (new-ref (ses-formula-references formula)))
  836. (dolist (ref new-ref)
  837. (let ((rowcol (ses-sym-rowcol ref)))
  838. (cl-pushnew sym (ses-cell-property :ses-repair-reference
  839. (car rowcol)
  840. (cdr rowcol))))))))
  841. ;; Step 3, overwrite with check.
  842. (dotimes (row ses--numrows)
  843. (dotimes (col ses--numcols)
  844. (let* ((cell (ses-get-cell row col))
  845. (irrelevant (ses-cell-references cell))
  846. (new-ref (ses-cell-property-pop :ses-repair-reference cell))
  847. missing)
  848. (dolist (ref new-ref)
  849. (if (memq ref irrelevant)
  850. (setq irrelevant (delq ref irrelevant))
  851. (push ref missing)))
  852. (ses-set-cell row col 'references new-ref)
  853. (when (or missing irrelevant)
  854. (push `( ,(ses-cell-symbol cell)
  855. ,@(and missing (list :missing missing))
  856. ,@(and irrelevant (list :irrelevant irrelevant)))
  857. errors)))))
  858. (if errors
  859. (warn "----------------------------------------------------------------
  860. Some references were corrupted.
  861. The following is a list where each element ELT is such
  862. that (car ELT) is the reference of cell CELL with corruption,
  863. and (cdr ELT) is a property list where
  864. * property `:corrupt-property' means that
  865. property `:ses-repair-reference' of cell CELL was initially non
  866. nil,
  867. * property `:missing' is a list of missing references
  868. * property `:irrelevant' is a list of non needed references
  869. %S" errors)
  870. (message "No reference corruption found"))))
  871. (defun ses-calculate-cell (row col force)
  872. "Calculate and print the value for cell (ROW,COL) using the cell's formula
  873. function and print functions, if any. Result is nil for normal operation, or
  874. the error signal if the formula or print function failed. The old value is
  875. left unchanged if it was *skip* and the new value is nil.
  876. Any cells that depend on this cell are queued for update after the end of
  877. processing for the current keystroke, unless the new value is the same as
  878. the old and FORCE is nil."
  879. (let ((cell (ses-get-cell row col))
  880. cycle-error formula-error printer-error)
  881. (let ((oldval (ses-cell-value cell))
  882. (formula (ses-cell-formula cell))
  883. newval
  884. this-cell-Dijkstra-attempt+1)
  885. (when (eq (car-safe formula) 'ses-safe-formula)
  886. (setq formula (ses-safe-formula (cadr formula)))
  887. (ses-set-cell row col 'formula formula))
  888. (condition-case sig
  889. (setq newval (eval formula t))
  890. (error
  891. ;; Variable `sig' can't be nil.
  892. (nconc sig (list (ses-cell-symbol cell)))
  893. (setq formula-error sig
  894. newval '*error*)))
  895. (if (and (not newval) (eq oldval '*skip*))
  896. ;; Don't lose the *skip* --- previous field spans this one.
  897. (setq newval '*skip*))
  898. (catch 'cycle
  899. (when (or force (not (eq newval oldval)))
  900. (cl-pushnew (cons row col) ses--deferred-write :test #'equal) ; In case force=t.
  901. (ses--letref (pget pset)
  902. (ses-cell-property :ses-Dijkstra-attempt cell)
  903. (let ((this-cell-Dijkstra-attempt (pget)))
  904. (if (null this-cell-Dijkstra-attempt)
  905. (pset
  906. (setq this-cell-Dijkstra-attempt
  907. (cons ses--Dijkstra-attempt-nb 0)))
  908. (unless (= ses--Dijkstra-attempt-nb
  909. (car this-cell-Dijkstra-attempt))
  910. (setcar this-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
  911. (setcdr this-cell-Dijkstra-attempt 0)))
  912. (setq this-cell-Dijkstra-attempt+1
  913. (1+ (cdr this-cell-Dijkstra-attempt)))))
  914. (ses-set-cell row col 'value newval)
  915. (dolist (ref (ses-cell-references cell))
  916. (cl-pushnew ref ses--deferred-recalc)
  917. (ses--letref (pget pset)
  918. (let ((ref-rowcol (ses-sym-rowcol ref)))
  919. (ses-cell-property
  920. :ses-Dijkstra-attempt
  921. (car ref-rowcol) (cdr ref-rowcol)))
  922. (let ((ref-cell-Dijkstra-attempt (pget)))
  923. (if (null ref-cell-Dijkstra-attempt)
  924. (pset
  925. (setq ref-cell-Dijkstra-attempt
  926. (cons ses--Dijkstra-attempt-nb
  927. this-cell-Dijkstra-attempt+1)))
  928. (if (= (car ref-cell-Dijkstra-attempt) ses--Dijkstra-attempt-nb)
  929. (setcdr ref-cell-Dijkstra-attempt
  930. (max (cdr ref-cell-Dijkstra-attempt)
  931. this-cell-Dijkstra-attempt+1))
  932. (setcar ref-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
  933. (setcdr ref-cell-Dijkstra-attempt
  934. this-cell-Dijkstra-attempt+1)))))
  935. (when (> this-cell-Dijkstra-attempt+1 ses--Dijkstra-weight-bound)
  936. ;; Update print of this cell.
  937. (throw 'cycle (setq formula-error
  938. `(error ,(format "Found cycle on cells %S"
  939. (ses-cell-symbol cell)))
  940. cycle-error formula-error)))))))
  941. (setq printer-error (ses-print-cell row col))
  942. (or
  943. (and cycle-error
  944. (error (error-message-string cycle-error)))
  945. formula-error printer-error)))
  946. (defun ses-clear-cell (row col)
  947. "Delete formula and printer for cell (ROW,COL)."
  948. (ses-set-cell row col 'printer nil)
  949. (ses-cell-set-formula row col nil))
  950. (defcustom ses-self-reference-early-detection nil
  951. "True if cycle detection is early for cells that refer to themselves."
  952. :version "24.1"
  953. :type 'boolean
  954. :group 'ses)
  955. (defun ses-update-cells (list &optional force)
  956. "Recalculate cells in LIST, checking for dependency loops. Prints
  957. progress messages every second. Dependent cells are not recalculated
  958. if the cell's value is unchanged and FORCE is nil."
  959. (let ((ses--deferred-recalc list)
  960. (nextlist list)
  961. (pos (point))
  962. curlist prevlist this-sym this-rowcol formula)
  963. (with-temp-message " "
  964. (while ses--deferred-recalc
  965. ;; In each loop, recalculate cells that refer only to other cells that
  966. ;; have already been recalculated or aren't in the recalculation region.
  967. ;; Repeat until all cells have been processed or until the set of cells
  968. ;; being worked on stops changing.
  969. (if prevlist
  970. (message "Recalculating... (%d cells left)"
  971. (length ses--deferred-recalc)))
  972. (setq curlist ses--deferred-recalc
  973. ses--deferred-recalc nil
  974. prevlist nextlist)
  975. (while curlist
  976. ;; this-sym has to be popped from curlist *BEFORE* the check, and not
  977. ;; after because of the case of cells referring to themselves.
  978. (setq this-sym (pop curlist)
  979. this-rowcol (ses-sym-rowcol this-sym)
  980. formula (ses-cell-formula (car this-rowcol)
  981. (cdr this-rowcol)))
  982. (or (catch 'ref
  983. (dolist (ref (ses-formula-references formula))
  984. (if (and ses-self-reference-early-detection (eq ref this-sym))
  985. (error "Cycle found: cell %S is self-referring" this-sym)
  986. (when (or (memq ref curlist)
  987. (memq ref ses--deferred-recalc))
  988. ;; This cell refers to another that isn't done yet
  989. (cl-pushnew this-sym ses--deferred-recalc :test #'equal)
  990. (throw 'ref t)))))
  991. ;; ses-update-cells is called from post-command-hook, so
  992. ;; inhibit-quit is implicitly bound to t.
  993. (when quit-flag
  994. ;; Abort the recalculation. User will probably undo now.
  995. (error "Quit"))
  996. (ses-calculate-cell (car this-rowcol) (cdr this-rowcol) force)))
  997. (dolist (ref ses--deferred-recalc)
  998. (cl-pushnew ref nextlist :test #'equal)))
  999. (when ses--deferred-recalc
  1000. ;; Just couldn't finish these.
  1001. (dolist (x ses--deferred-recalc)
  1002. (let ((this-rowcol (ses-sym-rowcol x)))
  1003. (ses-set-cell (car this-rowcol) (cdr this-rowcol) 'value '*error*)
  1004. (1value (ses-print-cell (car this-rowcol) (cdr this-rowcol)))))
  1005. (error "Circular references: %s" ses--deferred-recalc))
  1006. (message " "))
  1007. ;; Can't use save-excursion here: if the cell under point is updated,
  1008. ;; save-excursion's marker will move past the cell.
  1009. (goto-char pos)))
  1010. ;;----------------------------------------------------------------------------
  1011. ;; The print area
  1012. ;;----------------------------------------------------------------------------
  1013. (defun ses-in-print-area ()
  1014. "Return t if point is in print area of spreadsheet."
  1015. (<= (point) ses--data-marker))
  1016. ;; We turn off point-motion-hooks and explicitly position the cursor, in case
  1017. ;; the intangible properties have gotten screwed up (e.g., when ses-goto-print
  1018. ;; is called during a recursive ses-print-cell).
  1019. (defun ses-goto-print (row col)
  1020. "Move point to print area for cell (ROW,COL)."
  1021. (let ((n 0))
  1022. (goto-char (point-min))
  1023. (forward-line row)
  1024. ;; Calculate column position.
  1025. (dotimes (c col)
  1026. (setq n (+ n (ses-col-width c) 1)))
  1027. ;; Move to the position.
  1028. (and (> n (move-to-column n))
  1029. (eolp)
  1030. ;; Move point to the bol of next line (for TAB at the last cell).
  1031. (forward-char))))
  1032. (defun ses--cell-at-pos (pos &optional object)
  1033. (or (get-text-property pos 'cursor-intangible object)
  1034. ;; (when (> pos (if object 0 (point-min)))
  1035. ;; (get-text-property (1- pos) 'cursor-intangible object))
  1036. ))
  1037. (defun ses--curcell (&optional pos)
  1038. "Return the current cell symbol, or a cons (BEG,END) for a
  1039. region, or nil if cursor is not at a cell."
  1040. (unless pos (setq pos (point)))
  1041. (if (or (not mark-active)
  1042. deactivate-mark
  1043. (= pos (mark t)))
  1044. ;; Single cell.
  1045. (ses--cell-at-pos pos)
  1046. ;; Range.
  1047. (let* ((re (max pos (mark t)))
  1048. (bcell (ses--cell-at-pos (min pos (mark t))))
  1049. (ecell (ses--cell-at-pos (1- re))))
  1050. (when (= re ses--data-marker)
  1051. ;; Correct for overflow.
  1052. (setq ecell (ses--cell-at-pos (- (region-end) 2))))
  1053. (if (and bcell ecell)
  1054. (cons bcell ecell)
  1055. nil))))
  1056. (defun ses-set-curcell ()
  1057. "Set `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
  1058. region, or nil if cursor is not at a cell."
  1059. (setq ses--curcell (ses--curcell))
  1060. nil)
  1061. (defun ses-check-curcell (&rest args)
  1062. "Signal an error if `ses--curcell' is inappropriate.
  1063. The end marker is appropriate if some argument is `end'.
  1064. A range is appropriate if some argument is `range'.
  1065. A single cell is appropriate unless some argument is `needrange'."
  1066. (ses-set-curcell); fix bug#21054
  1067. (cond
  1068. ((not ses--curcell)
  1069. (or (memq 'end args)
  1070. (error "Not at cell")))
  1071. ((consp ses--curcell)
  1072. (or (memq 'range args)
  1073. (memq 'needrange args)
  1074. (error "Can't use a range")))
  1075. ((memq 'needrange args)
  1076. (error "Need a range"))))
  1077. (defvar ses--row)
  1078. (defvar ses--col)
  1079. (defun ses-print-cell (row col)
  1080. "Format and print the value of cell (ROW,COL) to the print area.
  1081. Use the cell's printer function. If the cell's new print form is too wide,
  1082. it will spill over into the following cell, but will not run off the end of the
  1083. row or overwrite the next non-nil field. Result is nil for normal operation,
  1084. or the error signal if the printer function failed and the cell was formatted
  1085. with \"%s\". If the cell's value is *skip*, nothing is printed because the
  1086. preceding cell has spilled over."
  1087. (catch 'ses-print-cell
  1088. (let* ((cell (ses-get-cell row col))
  1089. (value (ses-cell-value cell))
  1090. (printer (ses-cell-printer cell))
  1091. (maxcol (1+ col))
  1092. text sig startpos x)
  1093. ;; Create the string to print.
  1094. (cond
  1095. ((eq value '*skip*)
  1096. ;; Don't print anything.
  1097. (throw 'ses-print-cell nil))
  1098. ((eq value '*error*)
  1099. (setq text (make-string (ses-col-width col) ?#)))
  1100. (t
  1101. ;; Deferred safety-check on printer.
  1102. (if (eq (car-safe printer) 'ses-safe-printer)
  1103. (ses-set-cell row col 'printer
  1104. (setq printer (ses-safe-printer (cadr printer)))))
  1105. ;; Print the value.
  1106. (setq text
  1107. (let ((ses--row row)
  1108. (ses--col col))
  1109. (ses-call-printer (or printer
  1110. (ses-col-printer col)
  1111. ses--default-printer)
  1112. value)))
  1113. (if (consp ses-call-printer-return)
  1114. ;; Printer returned an error.
  1115. (setq sig ses-call-printer-return))))
  1116. ;; Adjust print width to match column width.
  1117. (let ((width (ses-col-width col))
  1118. (len (string-width text)))
  1119. (cond
  1120. ((< len width)
  1121. ;; Fill field to length with spaces.
  1122. (setq len (make-string (- width len) ?\s)
  1123. text (if (or (stringp value)
  1124. (eq ses-call-printer-return t))
  1125. (concat text len)
  1126. (concat len text))))
  1127. ((> len width)
  1128. ;; Spill over into following cells, if possible.
  1129. (let ((maxwidth width))
  1130. (while (and (> len maxwidth)
  1131. (< maxcol ses--numcols)
  1132. (or (not (setq x (ses-cell-value row maxcol)))
  1133. (eq x '*skip*)))
  1134. (unless x
  1135. ;; Set this cell to '*skip* so it won't overwrite our spillover.
  1136. (ses-set-cell row maxcol 'value '*skip*))
  1137. (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
  1138. maxcol (1+ maxcol)))
  1139. (if (<= len maxwidth)
  1140. ;; Fill to complete width of all the fields spanned.
  1141. (setq text (concat text (make-string (- maxwidth len) ?\s)))
  1142. ;; Not enough room to end of line or next non-nil field. Truncate
  1143. ;; if string or decimal; otherwise fill with error indicator.
  1144. (setq sig `(error "Too wide" ,text))
  1145. (cond
  1146. ((stringp value)
  1147. (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
  1148. ((and (numberp value)
  1149. (string-match "\\.[0-9]+" text)
  1150. (>= 0 (setq width
  1151. (- len maxwidth
  1152. (- (match-end 0) (match-beginning 0))))))
  1153. ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
  1154. (setq text (concat (substring text
  1155. 0
  1156. (- (match-beginning 0) width))
  1157. (substring text (match-end 0)))))
  1158. (t
  1159. (setq text (make-string maxwidth ?#)))))))))
  1160. ;; Substitute question marks for tabs and newlines. Newlines are used as
  1161. ;; row-separators; tabs could confuse the reimport logic.
  1162. (setq text (replace-regexp-in-string "[\t\n]" "?" text))
  1163. (ses-goto-print row col)
  1164. (setq startpos (point))
  1165. ;; Install the printed result. This is not interruptible.
  1166. (let ((inhibit-read-only t)
  1167. (inhibit-quit t))
  1168. (delete-region (point) (progn
  1169. (move-to-column (+ (current-column)
  1170. (string-width text)))
  1171. (1+ (point))))
  1172. ;; We use concat instead of inserting separate strings in order to
  1173. ;; reduce the number of cells in the undo list.
  1174. (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
  1175. ;; We use set-text-properties to prevent a wacky print function from
  1176. ;; inserting rogue properties, and to ensure that the keymap property is
  1177. ;; inherited (is it a bug that only unpropertized strings actually
  1178. ;; inherit from surrounding text?)
  1179. (set-text-properties 0 (length x) nil x)
  1180. (insert-and-inherit x)
  1181. (put-text-property startpos (point) 'cursor-intangible
  1182. (ses-cell-symbol cell))
  1183. (when (and (zerop row) (zerop col))
  1184. ;; Reconstruct special beginning-of-buffer attributes.
  1185. (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
  1186. (put-text-property (point-min) (point) 'read-only 'ses)
  1187. (put-text-property (point-min) (1+ (point-min))
  1188. ;; `cursor-intangible' shouldn't be sticky at BOB.
  1189. 'front-sticky '(read-only keymap))))
  1190. (if (= row (1- ses--header-row))
  1191. ;; This line is part of the header --- force recalc.
  1192. (ses-reset-header-string))
  1193. ;; If this cell (or a preceding one on the line) previously spilled over
  1194. ;; and has gotten shorter, redraw following cells on line recursively.
  1195. (when (and (< maxcol ses--numcols)
  1196. (eq (ses-cell-value row maxcol) '*skip*))
  1197. (ses-set-cell row maxcol 'value nil)
  1198. (ses-print-cell row maxcol))
  1199. ;; Return to start of cell.
  1200. (goto-char startpos)
  1201. sig)))
  1202. (defun ses-call-printer (printer &optional value)
  1203. "Invoke PRINTER (a string or parenthesized string or function-symbol or
  1204. lambda of one argument) on VALUE. Result is the printed cell as a string.
  1205. The variable `ses-call-printer-return' is set to t if the printer used
  1206. parenthesis to request left-justification, or the error-signal if the
  1207. printer signaled one (and \"%s\" is used as the default printer), else nil."
  1208. (setq ses-call-printer-return nil)
  1209. (condition-case signal
  1210. (cond
  1211. ((stringp printer)
  1212. (if value
  1213. (format printer value)
  1214. ""))
  1215. ((stringp (car-safe printer))
  1216. (setq ses-call-printer-return t)
  1217. (if value
  1218. (format (car printer) value)
  1219. ""))
  1220. (t
  1221. (setq value
  1222. (funcall
  1223. (or (and (symbolp printer)
  1224. (let ((locprn (gethash printer
  1225. ses--local-printer-hashmap)))
  1226. (and locprn
  1227. (ses--locprn-compiled locprn))))
  1228. printer)
  1229. value))
  1230. (if (stringp value)
  1231. value
  1232. (or (stringp (car-safe value))
  1233. (error "Printer should return \"string\" or (\"string\")"))
  1234. (setq ses-call-printer-return t)
  1235. (car value))))
  1236. (error
  1237. (setq ses-call-printer-return signal)
  1238. (ses-prin1 value))))
  1239. (defun ses-adjust-print-width (col change)
  1240. "Insert CHANGE spaces in front of column COL, or at end of line if
  1241. COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
  1242. `inhibit-quit' to t."
  1243. (let ((inhibit-read-only t)
  1244. (blank (if (> change 0) (make-string change ?\s)))
  1245. (at-end (= col ses--numcols)))
  1246. (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
  1247. ;; ses-set-with-undo always returns t for strings.
  1248. (1value (ses-set-with-undo 'ses--blank-line
  1249. (concat (make-string ses--linewidth ?\s) "\n")))
  1250. (dotimes (row ses--numrows)
  1251. (ses-goto-print row col)
  1252. (when at-end
  1253. ;; Insert new columns before newline.
  1254. (backward-char 1))
  1255. (if blank
  1256. (insert blank)
  1257. (delete-char (- change))))))
  1258. (defun ses-print-cell-new-width (row col)
  1259. "Same as `ses-print-cell', except if the cell's value is *skip*,
  1260. the preceding nonskipped cell is reprinted. This function is used
  1261. when the width of cell (ROW,COL) has changed."
  1262. (if (not (eq (ses-cell-value row col) '*skip*))
  1263. (ses-print-cell row col)
  1264. ;;Cell was skipped over - reprint previous
  1265. (ses-goto-print row col)
  1266. (backward-char 1)
  1267. (let ((rowcol (ses-sym-rowcol (ses--cell-at-pos (point)))))
  1268. (ses-print-cell (car rowcol) (cdr rowcol)))))
  1269. ;;----------------------------------------------------------------------------
  1270. ;; The data area
  1271. ;;----------------------------------------------------------------------------
  1272. (defun ses-widen ()
  1273. "Turn off narrowing, to be reenabled at end of command loop."
  1274. (if (buffer-narrowed-p)
  1275. (setq ses--deferred-narrow t))
  1276. (widen))
  1277. (defun ses-goto-data (def &optional col)
  1278. "Move point to data area for (DEF,COL). If DEF is a row
  1279. number, COL is the column number for a data cell -- otherwise DEF
  1280. is one of the symbols ses--col-widths, ses--col-printers,
  1281. ses--default-printer, ses--numrows, or ses--numcols."
  1282. (ses-widen)
  1283. (if col
  1284. ;; It's a cell.
  1285. (progn
  1286. (goto-char ses--data-marker)
  1287. (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
  1288. ;; Convert def-symbol to offset.
  1289. (setq def (plist-get ses-paramlines-plist def))
  1290. (or def (signal 'args-out-of-range nil))
  1291. (goto-char ses--params-marker)
  1292. (forward-line def)))
  1293. (defun ses-file-format-extend-parameter-list (new-file-format)
  1294. "Extend the global parameters list when file format is updated
  1295. from 2 to 3. This happens when local printer function are added
  1296. to a sheet that was created with SES version 2. This is not
  1297. undoable. Return nil when there was no change, and non nil otherwise."
  1298. (save-excursion
  1299. (cond
  1300. ((and (= ses--file-format 2) (= 3 new-file-format))
  1301. (ses-set-parameter 'ses--file-format 3)
  1302. (message "Upgrading from SES-2 to SES-3 file format")
  1303. (ses-widen)
  1304. (goto-char ses--params-marker)
  1305. (forward-line (plist-get ses-paramlines-plist 'ses--numlocprn ))
  1306. (insert (format (plist-get ses-paramfmt-plist 'ses--numlocprn)
  1307. ses--numlocprn)
  1308. ?\n)
  1309. t) )))
  1310. (defun ses-set-parameter (def value &optional elem)
  1311. "Set parameter DEF to VALUE (with undo) and write the value to the data area.
  1312. See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
  1313. If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
  1314. (save-excursion
  1315. ;; We call ses-goto-data early, using the old values of numrows and numcols
  1316. ;; in case one of them is being changed.
  1317. (ses-goto-data def)
  1318. (let ((inhibit-read-only t)
  1319. (fmt (plist-get ses-paramfmt-plist
  1320. def))
  1321. oldval)
  1322. (if elem
  1323. (progn
  1324. (setq oldval (aref (symbol-value def) elem))
  1325. (aset (symbol-value def) elem value))
  1326. (setq oldval (symbol-value def))
  1327. (set def value))
  1328. ;; Special undo since it's outside the narrowed buffer.
  1329. (let (buffer-undo-list)
  1330. (delete-region (point) (line-end-position))
  1331. (insert (format fmt (symbol-value def))))
  1332. (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
  1333. (defun ses-write-cells ()
  1334. "Write cells in `ses--deferred-write' from local variables to data area.
  1335. Newlines in the data are escaped."
  1336. (let* ((inhibit-read-only t)
  1337. (print-escape-newlines t)
  1338. rowcol row col cell sym formula printer text)
  1339. (setq ses-start-time (float-time))
  1340. (with-temp-message " "
  1341. (save-excursion
  1342. (while ses--deferred-write
  1343. (ses--time-check "Writing... (%d cells left)"
  1344. (length ses--deferred-write))
  1345. (setq rowcol (pop ses--deferred-write)
  1346. row (car rowcol)
  1347. col (cdr rowcol)
  1348. cell (ses-get-cell row col)
  1349. sym (ses-cell-symbol cell)
  1350. formula (ses-cell-formula cell)
  1351. printer (ses-cell-printer cell))
  1352. (if (eq (car-safe formula) 'ses-safe-formula)
  1353. (setq formula (cadr formula)))
  1354. (if (eq (car-safe printer) 'ses-safe-printer)
  1355. (setq printer (cadr printer)))
  1356. (setq text (prin1-to-string
  1357. ;; We could shorten it to (ses-cell SYM VAL) when
  1358. ;; the other parameters are nil, but in practice most
  1359. ;; cells have non-nil `references', so it's
  1360. ;; rather pointless.
  1361. `(ses-cell ,sym
  1362. ,(symbol-value sym)
  1363. ,(unless (equal formula (symbol-value sym))
  1364. formula)
  1365. ,printer
  1366. ,(ses-cell-references cell))))
  1367. (ses-goto-data row col)
  1368. (delete-region (point) (line-end-position))
  1369. (insert text)))
  1370. (message " "))))
  1371. ;;----------------------------------------------------------------------------
  1372. ;; Formula relocation
  1373. ;;----------------------------------------------------------------------------
  1374. (defun ses-formula-references (formula &optional result-so-far)
  1375. "Produce a list of symbols for cells that this FORMULA's value
  1376. refers to. For recursive calls, RESULT-SO-FAR is the list being
  1377. constructed, or t to get a wrong-type-argument error when the
  1378. first reference is found."
  1379. (if (ses-sym-rowcol formula)
  1380. ;; Entire formula is one symbol.
  1381. (cl-pushnew formula result-so-far :test #'equal)
  1382. (if (consp formula)
  1383. (cond
  1384. ((eq (car formula) 'ses-range)
  1385. (dolist (cur
  1386. (cdr (funcall 'macroexpand
  1387. (list 'ses-range (nth 1 formula)
  1388. (nth 2 formula)))))
  1389. (cl-pushnew cur result-so-far :test #'equal)))
  1390. ((null (eq (car formula) 'quote))
  1391. ;;Recursive call for subformulas
  1392. (dolist (cur formula)
  1393. (setq result-so-far (ses-formula-references cur result-so-far))))
  1394. (t
  1395. ;;Ignore other stuff
  1396. ))
  1397. ;; other type of atom are ignored
  1398. ))
  1399. result-so-far)
  1400. (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
  1401. "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
  1402. COL). Cells starting at (STARTROW,STARTCOL) are being shifted
  1403. by (ROWINCR,COLINCR)."
  1404. (let ((row (car rowcol))
  1405. (col (cdr rowcol)))
  1406. (if (or (< row startrow) (< col startcol))
  1407. sym
  1408. (setq row (+ row rowincr)
  1409. col (+ col colincr))
  1410. (if (and (>= row startrow) (>= col startcol)
  1411. (< row ses--numrows) (< col ses--numcols))
  1412. ;;Relocate this variable, unless it is a named cell
  1413. (if (eq (get sym 'ses-cell) :ses-named)
  1414. sym
  1415. ;; otherwise, we create the relocated cell symbol because
  1416. ;; ses-cell-symbol gives the old symbols, however since
  1417. ;; renamed cell are not relocated we keep the relocated
  1418. ;; cell old symbol in this case.
  1419. (if (eq (get (setq sym (ses-cell-symbol row col)) 'ses-cell) :ses-named)
  1420. sym
  1421. (ses-create-cell-symbol row col)))
  1422. ;;Delete reference to a deleted cell
  1423. nil))))
  1424. (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
  1425. "Produce a copy of FORMULA where all symbols that refer to cells in row
  1426. STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
  1427. and COLINCR. STARTROW and STARTCOL are 0-based. Example:
  1428. (ses-relocate-formula \\='(+ A1 B2 D3) 1 2 1 -1)
  1429. => (+ A1 B2 C4)
  1430. If ROWINCR or COLINCR is negative, references to cells being deleted are
  1431. removed. Example:
  1432. (ses-relocate-formula \\='(+ A1 B2 D3) 0 1 0 -1)
  1433. => (+ A1 C3)
  1434. Sets `ses-relocate-return' to `delete' if cell-references were removed."
  1435. (let (rowcol result)
  1436. (if (or (atom formula) (eq (car formula) 'quote))
  1437. (if (setq rowcol (ses-sym-rowcol formula))
  1438. (ses-relocate-symbol formula rowcol
  1439. startrow startcol rowincr colincr)
  1440. ;; Constants pass through as-is.
  1441. formula)
  1442. (dolist (cur formula)
  1443. (setq rowcol (ses-sym-rowcol cur))
  1444. (cond
  1445. (rowcol
  1446. (setq cur (ses-relocate-symbol cur rowcol
  1447. startrow startcol rowincr colincr))
  1448. (if cur
  1449. (push cur result)
  1450. ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
  1451. ;; don't change the flag if it's already 'range, since range implies
  1452. ;; 'delete.
  1453. (unless ses-relocate-return
  1454. (setq ses-relocate-return 'delete))))
  1455. ((eq (car-safe cur) 'ses-range)
  1456. (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
  1457. (if cur
  1458. (push cur result)))
  1459. ((or (atom cur) (eq (car cur) 'quote))
  1460. ;; Constants pass through unchanged.
  1461. (push cur result))
  1462. (t
  1463. ;; Recursively copy and alter subformulas.
  1464. (push (ses-relocate-formula cur startrow startcol
  1465. rowincr colincr)
  1466. result))))
  1467. (nreverse result))))
  1468. (defun ses-relocate-range (range startrow startcol rowincr colincr)
  1469. "Relocate one RANGE, of the form (ses-range MIN MAX). Cells starting
  1470. at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
  1471. new range, or nil if the entire range is deleted. If new rows are being added
  1472. just beyond the end of a row range, or new columns just beyond a column range,
  1473. the new rows/columns will be added to the range. Sets `ses-relocate-return'
  1474. if the range was altered."
  1475. (let* ((minorig (cadr range))
  1476. (minrowcol (ses-sym-rowcol minorig))
  1477. (min (ses-relocate-symbol minorig minrowcol
  1478. startrow startcol
  1479. rowincr colincr))
  1480. (maxorig (nth 2 range))
  1481. (maxrowcol (ses-sym-rowcol maxorig))
  1482. (max (ses-relocate-symbol maxorig maxrowcol
  1483. startrow startcol
  1484. rowincr colincr))
  1485. field)
  1486. (cond
  1487. ((and (not min) (not max))
  1488. (setq range nil)) ; The entire range is deleted.
  1489. ((zerop colincr)
  1490. ;; Inserting or deleting rows.
  1491. (setq field 'car)
  1492. (if (not min)
  1493. ;; Chopped off beginning of range.
  1494. (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
  1495. ses-relocate-return 'range))
  1496. (if (not max)
  1497. (if (> rowincr 0)
  1498. ;; Trying to insert a nonexistent row.
  1499. (setq max (ses-create-cell-symbol (1- ses--numrows)
  1500. (cdr minrowcol)))
  1501. ;; End of range is being deleted.
  1502. (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
  1503. ses-relocate-return 'range))
  1504. (and (> rowincr 0)
  1505. (= (car maxrowcol) (1- startrow))
  1506. (= (cdr minrowcol) (cdr maxrowcol))
  1507. ;; Insert after ending row of vertical range --- include it.
  1508. (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
  1509. (cdr maxrowcol))))))
  1510. (t
  1511. ;; Inserting or deleting columns.
  1512. (setq field 'cdr)
  1513. (if (not min)
  1514. ;; Chopped off beginning of range.
  1515. (setq min (ses-create-cell-symbol (car minrowcol) startcol)
  1516. ses-relocate-return 'range))
  1517. (if (not max)
  1518. (if (> colincr 0)
  1519. ;; Trying to insert a nonexistent column.
  1520. (setq max (ses-create-cell-symbol (car maxrowcol)
  1521. (1- ses--numcols)))
  1522. ;; End of range is being deleted.
  1523. (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
  1524. ses-relocate-return 'range))
  1525. (and (> colincr 0)
  1526. (= (cdr maxrowcol) (1- startcol))
  1527. (= (car minrowcol) (car maxrowcol))
  1528. ;; Insert after ending column of horizontal range --- include it.
  1529. (setq max (ses-create-cell-symbol (car maxrowcol)
  1530. (+ startcol colincr -1)))))))
  1531. (when range
  1532. (if (/= (- (funcall field maxrowcol)
  1533. (funcall field minrowcol))
  1534. (- (funcall field (ses-sym-rowcol max))
  1535. (funcall field (ses-sym-rowcol min))))
  1536. ;; This range has changed size.
  1537. (setq ses-relocate-return 'range))
  1538. `(ses-range ,min ,max ,@(cl-cdddr range)))))
  1539. (defun ses-relocate-all (minrow mincol rowincr colincr)
  1540. "Alter all cell values, symbols, formulas, and reference-lists to relocate
  1541. the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
  1542. to each symbol."
  1543. (let (reform)
  1544. (let (mycell newval xrow)
  1545. (dotimes-with-progress-reporter
  1546. (row ses--numrows) "Relocating formulas..."
  1547. (dotimes (col ses--numcols)
  1548. (setq ses-relocate-return nil
  1549. mycell (ses-get-cell row col)
  1550. newval (ses-relocate-formula (ses-cell-formula mycell)
  1551. minrow mincol rowincr colincr)
  1552. xrow (- row rowincr))
  1553. (ses-set-cell row col 'formula newval)
  1554. (if (eq ses-relocate-return 'range)
  1555. ;; This cell contains a (ses-range X Y) where a cell has been
  1556. ;; inserted or deleted in the middle of the range.
  1557. (push (cons row col) reform))
  1558. (if ses-relocate-return
  1559. ;; This cell referred to a cell that's been deleted or is no
  1560. ;; longer part of the range. We can't fix that now because
  1561. ;; reference lists cells have been partially updated.
  1562. (cl-pushnew (ses-create-cell-symbol row col)
  1563. ses--deferred-recalc :test #'equal))
  1564. (setq newval (ses-relocate-formula (ses-cell-references mycell)
  1565. minrow mincol rowincr colincr))
  1566. (ses-set-cell row col 'references newval)
  1567. (and (>= row minrow) (>= col mincol)
  1568. (let ((sym (ses-cell-symbol row col))
  1569. (xcol (- col colincr)))
  1570. (if (and
  1571. sym
  1572. (>= xrow 0)
  1573. (>= xcol 0)
  1574. ;; the following could also be tested as
  1575. ;; (null (eq sym (ses-create-cell-symbol xrow xcol)))
  1576. (eq (get sym 'ses-cell) :ses-named))
  1577. ;; This is a renamed cell, do not update the cell
  1578. ;; name, but just update the coordinate property.
  1579. (puthash sym (cons row col) ses--named-cell-hashmap)
  1580. (ses-set-cell row col 'symbol
  1581. (setq sym (ses-create-cell-symbol row col)))
  1582. (unless (local-variable-if-set-p sym)
  1583. (set (make-local-variable sym) nil)
  1584. (put sym 'ses-cell (cons row col)))))) )))
  1585. ;; Relocate the cell values.
  1586. (let (oldval myrow mycol xrow xcol sym)
  1587. (cond
  1588. ((and (<= rowincr 0) (<= colincr 0))
  1589. ;; Deletion of rows and/or columns.
  1590. (dotimes-with-progress-reporter
  1591. (row (- ses--numrows minrow)) "Relocating variables..."
  1592. (setq myrow (+ row minrow))
  1593. (dotimes (col (- ses--numcols mincol))
  1594. (setq mycol (+ col mincol)
  1595. xrow (- myrow rowincr)
  1596. xcol (- mycol colincr)
  1597. sym (ses-cell-symbol myrow mycol))
  1598. ;; We don't need to relocate value for renamed cells, as they keep the same
  1599. ;; symbol.
  1600. (unless (eq (get sym 'ses-cell) :ses-named)
  1601. (ses-set-cell myrow mycol 'value
  1602. (if (and (< xrow ses--numrows) (< xcol ses--numcols))
  1603. (ses-cell-value xrow xcol)
  1604. ;; Cell is off the end of the array.
  1605. (symbol-value (ses-create-cell-symbol xrow xcol)))))))
  1606. (when ses--in-killing-named-cell-list
  1607. (message "Unbinding killed named cell symbols...")
  1608. (setq ses-start-time (float-time))
  1609. (while ses--in-killing-named-cell-list
  1610. (ses--time-check "Unbinding killed named cell symbols... (%d left)" (length ses--in-killing-named-cell-list))
  1611. (ses--unbind-cell-name (pop ses--in-killing-named-cell-list)) )
  1612. (message nil)) )
  1613. ((and (wholenump rowincr) (wholenump colincr))
  1614. ;; Insertion of rows and/or columns. Run the loop backwards.
  1615. (let ((disty (1- ses--numrows))
  1616. (distx (1- ses--numcols))
  1617. myrow mycol)
  1618. (dotimes-with-progress-reporter
  1619. (row (- ses--numrows minrow)) "Relocating variables..."
  1620. (setq myrow (- disty row))
  1621. (dotimes (col (- ses--numcols mincol))
  1622. (setq mycol (- distx col)
  1623. xrow (- myrow rowincr)
  1624. xcol (- mycol colincr)
  1625. sym (ses-cell-symbol myrow mycol))
  1626. ;; We don't need to relocate value for renamed cells, as they keep the same
  1627. ;; symbol.
  1628. (unless (eq (get sym 'ses-cell) :ses-named)
  1629. (if (or (< xrow minrow) (< xcol mincol))
  1630. ;; Newly-inserted value.
  1631. (setq oldval nil)
  1632. ;; Transfer old value.
  1633. (setq oldval (ses-cell-value xrow xcol)))
  1634. (ses-set-cell myrow mycol 'value oldval))))
  1635. t)) ; Make testcover happy by returning non-nil here.
  1636. (t
  1637. (error "ROWINCR and COLINCR must have the same sign"))))
  1638. ;; Reconstruct reference lists for cells that contain ses-ranges that have
  1639. ;; changed size.
  1640. (when reform
  1641. (message "Fixing ses-ranges...")
  1642. (let (row col)
  1643. (setq ses-start-time (float-time))
  1644. (while reform
  1645. (ses--time-check "Fixing ses-ranges... (%d left)" (length reform))
  1646. (setq row (caar reform)
  1647. col (cdar reform)
  1648. reform (cdr reform))
  1649. (ses-cell-set-formula row col (ses-cell-formula row col))))
  1650. (message nil))))
  1651. ;;----------------------------------------------------------------------------
  1652. ;; Undo control
  1653. ;;----------------------------------------------------------------------------
  1654. (defun ses-begin-change ()
  1655. "For undo, remember point before we start changing hidden stuff."
  1656. (let ((inhibit-read-only t))
  1657. (insert-and-inherit "X")
  1658. (delete-region (1- (point)) (point))))
  1659. (defun ses-setter-with-undo (accessors newval &rest args)
  1660. "Set a field/variable and record it so it can be undone.
  1661. Result is non-nil if field/variable has changed."
  1662. (let ((oldval (apply (car accessors) args)))
  1663. (unless (equal-including-properties oldval newval)
  1664. (push `(apply ses-setter-with-undo ,accessors ,oldval ,@args)
  1665. buffer-undo-list)
  1666. (apply (cdr accessors) newval args)
  1667. t)))
  1668. (defun ses-aset-with-undo (array idx newval)
  1669. (ses-setter-with-undo (eval-when-compile
  1670. (cons #'aref
  1671. (lambda (newval array idx) (aset array idx newval))))
  1672. newval array idx))
  1673. (defun ses-set-with-undo (sym newval)
  1674. (ses-setter-with-undo
  1675. (eval-when-compile
  1676. (cons (lambda (sym) (if (boundp sym) (symbol-value sym) :ses--unbound))
  1677. (lambda (newval sym) (if (eq newval :ses--unbound)
  1678. (makunbound sym)
  1679. (set sym newval)))))
  1680. newval sym))
  1681. ;;----------------------------------------------------------------------------
  1682. ;; Startup for major mode
  1683. ;;----------------------------------------------------------------------------
  1684. (defun ses-load ()
  1685. "Parse the current buffer and set up buffer-local variables.
  1686. Does not execute cell formulas or print functions."
  1687. (widen)
  1688. ;; Read our global parameters, which should be a 3-element list.
  1689. (goto-char (point-max))
  1690. (search-backward ";; Local Variables:\n" nil t)
  1691. (backward-list 1)
  1692. (setq ses--params-marker (point-marker))
  1693. (let* ((params (ignore-errors (read (current-buffer))))
  1694. (params-len (safe-length params)))
  1695. (or (and (>= params-len 3)
  1696. (<= params-len 4)
  1697. (numberp (car params))
  1698. (numberp (cadr params))
  1699. (>= (cadr params) 0)
  1700. (numberp (nth 2 params))
  1701. (> (nth 2 params) 0)
  1702. (or (<= params-len 3)
  1703. (let ((numlocprn (nth 3 params)))
  1704. (and (integerp numlocprn) (>= numlocprn 0)))))
  1705. (error "Invalid SES file"))
  1706. (setq ses--file-format (car params)
  1707. ses--numrows (cadr params)
  1708. ses--numcols (nth 2 params)
  1709. ses--numlocprn (or (nth 3 params) 0))
  1710. (when (= ses--file-format 1)
  1711. (let (buffer-undo-list) ; This is not undoable.
  1712. (ses-goto-data 'ses--header-row)
  1713. (insert "(ses-header-row 0)\n")
  1714. (ses-set-parameter 'ses--file-format 3)
  1715. (message "Upgrading from SES-1 to SES-2 file format")))
  1716. (or (<= ses--file-format 3)
  1717. (error "This file needs a newer version of the SES library code"))
  1718. ;; Initialize cell array.
  1719. (setq ses--cells (make-vector ses--numrows nil))
  1720. (dotimes (row ses--numrows)
  1721. (aset ses--cells row (make-vector ses--numcols nil)))
  1722. ;; initialize local printer map.
  1723. (clrhash ses--local-printer-hashmap))
  1724. ;; Skip over print area, which we assume is correct.
  1725. (goto-char (point-min))
  1726. (forward-line ses--numrows)
  1727. (or (looking-at-p ses-print-data-boundary)
  1728. (error "Missing marker between print and data areas"))
  1729. (forward-char 1)
  1730. (setq ses--data-marker (point-marker))
  1731. (forward-char (1- (length ses-print-data-boundary)))
  1732. ;; Initialize printer and symbol lists.
  1733. (mapc #'ses-printer-record ses-standard-printer-functions)
  1734. (setq ses--symbolic-formulas nil)
  1735. ;; Load local printer definitions.
  1736. ;; This must be loaded *BEFORE* cells and column printers because the latter
  1737. ;; may call them.
  1738. (save-excursion
  1739. (forward-line (* ses--numrows (1+ ses--numcols)))
  1740. (let ((numlocprn ses--numlocprn))
  1741. (setq ses--numlocprn 0)
  1742. (dotimes (_ numlocprn)
  1743. (let ((x (read (current-buffer))))
  1744. (or (and (= (following-char) ?\n)
  1745. (eq (car-safe x) 'ses-local-printer)
  1746. (apply #'ses--local-printer (cdr x)))
  1747. (error "local printer-def error"))
  1748. (setq ses--numlocprn (1+ ses--numlocprn))))))
  1749. ;; Load cell definitions.
  1750. (dotimes (row ses--numrows)
  1751. (dotimes (col ses--numcols)
  1752. (let* ((x (read (current-buffer)))
  1753. (sym (car-safe (cdr-safe x))))
  1754. (or (and (= (following-char) ?\n)
  1755. (eq (car-safe x) 'ses-cell)
  1756. (ses-create-cell-variable sym row col))
  1757. (error "Cell-def error"))
  1758. (apply #'ses--cell (cdr x))))
  1759. (or (looking-at-p "\n\n")
  1760. (error "Missing blank line between rows")))
  1761. ;; Skip local printer function declaration --- that were already loaded.
  1762. (forward-line (+ 2 ses--numlocprn))
  1763. ;; Load global parameters.
  1764. (let ((widths (read (current-buffer)))
  1765. (n1 (char-after (point)))
  1766. (printers (read (current-buffer)))
  1767. (n2 (char-after (point)))
  1768. (def-printer (read (current-buffer)))
  1769. (n3 (char-after (point)))
  1770. (head-row (read (current-buffer)))
  1771. (n4 (char-after (point))))
  1772. (or (and (eq (car-safe widths) 'ses-column-widths)
  1773. (= n1 ?\n)
  1774. (eq (car-safe printers) 'ses-column-printers)
  1775. (= n2 ?\n)
  1776. (eq (car-safe def-printer) 'ses-default-printer)
  1777. (= n3 ?\n)
  1778. (eq (car-safe head-row) 'ses-header-row)
  1779. (= n4 ?\n))
  1780. (error "Invalid SES global parameters"))
  1781. (1value (eval widths t))
  1782. (1value (eval def-printer t))
  1783. (1value (eval printers t))
  1784. (1value (eval head-row t)))
  1785. ;; Should be back at global-params.
  1786. (forward-char 1)
  1787. (or (looking-at-p ses-initial-global-parameters-re)
  1788. (error "Problem with column-defs or global-params"))
  1789. ;; Check for overall newline count in definitions area.
  1790. (forward-line 3)
  1791. (let ((start (point)))
  1792. (ses-goto-data 'ses--numrows)
  1793. (or (= (point) start)
  1794. (error "Extraneous newlines someplace?"))))
  1795. (defun ses-setup ()
  1796. "Set up for display of only the printed cell values.
  1797. Narrows the buffer to show only the print area. Gives it `read-only' and
  1798. `intangible' properties. Sets up highlighting for current cell."
  1799. (interactive)
  1800. (let ((end (point-min))
  1801. pos sym)
  1802. (with-silent-modifications
  1803. (ses-goto-data 0 0) ; Include marker between print-area and data-area.
  1804. (set-text-properties (point) (point-max) nil) ; Delete garbage props.
  1805. (mapc #'delete-overlay (overlays-in (point-min) (point-max)))
  1806. ;; The print area is read-only (except for our special commands) and
  1807. ;; uses a special keymap.
  1808. (put-text-property (point-min) (1- (point)) 'read-only 'ses)
  1809. (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
  1810. ;; For the beginning of the buffer, we want the read-only and keymap
  1811. ;; attributes to be inherited from the first character.
  1812. (put-text-property (point-min) (1+ (point-min))
  1813. ;; `cursor-intangible' shouldn't be sticky at BOB.
  1814. 'front-sticky '(read-only keymap))
  1815. ;; Create intangible properties, which also indicate which cell the text
  1816. ;; came from.
  1817. (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
  1818. (dotimes (col ses--numcols)
  1819. (setq pos end
  1820. sym (ses-cell-symbol row col))
  1821. (unless (eq (symbol-value sym) '*skip*)
  1822. ;; Include skipped cells following this one.
  1823. (while (and (< col (1- ses--numcols))
  1824. (eq (ses-cell-value row (1+ col)) '*skip*))
  1825. (setq end (+ end (ses-col-width col) 1)
  1826. ;; Beware: Modifying the iteration variable of `dotimes'
  1827. ;; may or may not affect the iteration!
  1828. col (1+ col)))
  1829. (setq end (save-excursion
  1830. (goto-char pos)
  1831. (move-to-column (+ (current-column) (- end pos)
  1832. (ses-col-width col)))
  1833. (if (eolp)
  1834. (+ end (ses-col-width col) 1)
  1835. (forward-char)
  1836. (point))))
  1837. (put-text-property pos end 'cursor-intangible sym))))))
  1838. ;; Create the underlining overlay. It's impossible for (point) to be 2,
  1839. ;; because column A must be at least 1 column wide.
  1840. (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
  1841. (overlay-put ses--curcell-overlay 'face 'underline))
  1842. (defun ses-cleanup ()
  1843. "Cleanup when changing a buffer from SES mode to something else.
  1844. Delete overlays, remove special text properties."
  1845. (widen)
  1846. (let ((inhibit-read-only t)
  1847. ;; When reverting, hide the buffer name, otherwise Emacs will ask the
  1848. ;; user "the file is modified, do you really want to make modifications
  1849. ;; to this buffer", where the "modifications" refer to the irrelevant
  1850. ;; set-text-properties below.
  1851. (buffer-file-name nil)
  1852. (was-modified (buffer-modified-p)))
  1853. ;; Delete read-only, keymap, and intangible properties.
  1854. (set-text-properties (point-min) (point-max) nil)
  1855. ;; Delete overlay.
  1856. (mapc #'delete-overlay (overlays-in (point-min) (point-max)))
  1857. (unless was-modified
  1858. (restore-buffer-modified-p nil))))
  1859. (defun ses-killbuffer-hook ()
  1860. "Hook when the current buffer is killed."
  1861. (setq ses--ses-buffer-list (delq (current-buffer) ses--ses-buffer-list)))
  1862. ;;;###autoload
  1863. (defun ses-mode ()
  1864. "Major mode for Simple Emacs Spreadsheet.
  1865. When you invoke SES in a new buffer, it is divided into cells
  1866. that you can enter data into. You can navigate the cells with
  1867. the arrow keys and add more cells with the tab key. The contents
  1868. of these cells can be numbers, text, or Lisp expressions. (To
  1869. enter text, enclose it in double quotes.)
  1870. In an expression, you can use cell coordinates to refer to the
  1871. contents of another cell. For example, you can sum a range of
  1872. cells with `(+ A1 A2 A3)'. There are specialized functions like
  1873. `ses+' (addition for ranges with empty cells), `ses-average' (for
  1874. performing calculations on cells), and `ses-range' and `ses-select'
  1875. \(for extracting ranges of cells).
  1876. Each cell also has a print function that controls how it is
  1877. displayed.
  1878. Each SES buffer is divided into a print area and a data area.
  1879. Normally, you can simply use SES to look at and manipulate the print
  1880. area, and let SES manage the data area outside the visible region.
  1881. See \"ses-example.ses\" (in `data-directory') for an example
  1882. spreadsheet, and the Info node `(ses)Top.'
  1883. In the following, note the separate keymaps for cell editing mode
  1884. and print mode specifications. Key definitions:
  1885. \\{ses-mode-map}
  1886. These key definitions are active only in the print area (the visible
  1887. part):
  1888. \\{ses-mode-print-map}
  1889. These are active only in the minibuffer, when entering or editing a
  1890. formula:
  1891. \\{ses-mode-edit-map}"
  1892. (interactive)
  1893. (unless (and (boundp 'ses--deferred-narrow)
  1894. (eq ses--deferred-narrow 'ses-mode))
  1895. (kill-all-local-variables)
  1896. (ses-set-localvars)
  1897. (setq major-mode 'ses-mode
  1898. mode-name "SES"
  1899. next-line-add-newlines nil
  1900. truncate-lines t
  1901. ;; SES deliberately puts lots of trailing whitespace in its buffer.
  1902. show-trailing-whitespace nil
  1903. ;; Cell ranges do not work reasonably without this.
  1904. transient-mark-mode t
  1905. ;; Not to use tab characters for safe (tabs may do bad for column
  1906. ;; calculation).
  1907. indent-tabs-mode nil)
  1908. (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
  1909. (1value (add-hook 'kill-buffer-hook 'ses-killbuffer-hook nil t))
  1910. (cl-pushnew (current-buffer) ses--ses-buffer-list :test 'eq)
  1911. ;; This makes revert impossible if the buffer is read-only.
  1912. ;; (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
  1913. (setq header-line-format '(:eval (progn
  1914. (when (/= (window-hscroll)
  1915. ses--header-hscroll)
  1916. ;; Reset ses--header-hscroll first,
  1917. ;; to avoid recursion problems when
  1918. ;; debugging ses-create-header-string
  1919. (setq ses--header-hscroll
  1920. (window-hscroll))
  1921. (ses-create-header-string))
  1922. ses--header-string)))
  1923. (setq-local mode-line-process '(:eval (ses--mode-line-process)))
  1924. (add-hook 'pre-redisplay-functions #'ses--cursor-sensor-highlight
  1925. ;; Highlight the cell after moving cursor out of intangible.
  1926. 'append t)
  1927. (cursor-intangible-mode 1)
  1928. (let ((was-empty (zerop (buffer-size)))
  1929. (was-modified (buffer-modified-p)))
  1930. (save-excursion
  1931. (if was-empty
  1932. ;; Initialize buffer to contain one cell, for now.
  1933. (insert ses-initial-file-contents))
  1934. (ses-load)
  1935. (ses-setup))
  1936. (when was-empty
  1937. (unless (equal ses-initial-default-printer
  1938. (1value ses--default-printer))
  1939. (1value (ses-read-default-printer ses-initial-default-printer)))
  1940. (unless (= ses-initial-column-width (1value (ses-col-width 0)))
  1941. (1value (ses-set-column-width 0 ses-initial-column-width)))
  1942. (ses-set-curcell)
  1943. (if (> (car ses-initial-size) (1value ses--numrows))
  1944. (1value (ses-insert-row (1- (car ses-initial-size)))))
  1945. (if (> (cdr ses-initial-size) (1value ses--numcols))
  1946. (1value (ses-insert-column (1- (cdr ses-initial-size)))))
  1947. (ses-write-cells)
  1948. (restore-buffer-modified-p was-modified)
  1949. (buffer-disable-undo)
  1950. (buffer-enable-undo)
  1951. (goto-char (point-min))))
  1952. (use-local-map ses-mode-map)
  1953. ;; Set the deferred narrowing flag (we can't narrow until after
  1954. ;; after-find-file completes). If .ses is on the auto-load alist and the
  1955. ;; file has "mode: ses", our ses-mode function will be called twice! Use a
  1956. ;; special flag to detect this (will be reset by ses-command-hook). For
  1957. ;; find-alternate-file, post-command-hook doesn't get run for some reason,
  1958. ;; so use an idle timer to make sure.
  1959. (setq ses--deferred-narrow 'ses-mode)
  1960. (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
  1961. (run-with-idle-timer 0.01 nil 'ses-command-hook)
  1962. (run-mode-hooks 'ses-mode-hook)))
  1963. (put 'ses-mode 'mode-class 'special)
  1964. (defun ses-command-hook ()
  1965. "Invoked from `post-command-hook'. If point has moved to a different cell,
  1966. moves the underlining overlay. Performs any recalculations or cell-data
  1967. writes that have been deferred. If buffer-narrowing has been deferred,
  1968. narrows the buffer now."
  1969. (condition-case err
  1970. (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
  1971. (when ses--deferred-recalc
  1972. ;; We reset the deferred list before starting on the recalc --- in
  1973. ;; case of error, we don't want to retry the recalc after every
  1974. ;; keystroke!
  1975. (ses-initialize-Dijkstra-attempt)
  1976. (let ((old ses--deferred-recalc))
  1977. (setq ses--deferred-recalc nil)
  1978. (ses-update-cells old)))
  1979. (when ses--deferred-write
  1980. ;; We don't reset the deferred list before starting --- the most
  1981. ;; likely error is keyboard-quit, and we do want to keep trying these
  1982. ;; writes after a quit.
  1983. (ses-write-cells)
  1984. (push '(apply ses-widen) buffer-undo-list))
  1985. (when ses--deferred-narrow
  1986. ;; We're not allowed to narrow the buffer until after-find-file has
  1987. ;; read the local variables at the end of the file. Now it's safe to
  1988. ;; do the narrowing.
  1989. (narrow-to-region (point-min) ses--data-marker)
  1990. (setq ses--deferred-narrow nil)))
  1991. ;; Prevent errors in this post-command-hook from silently erasing the hook!
  1992. (error
  1993. (unless executing-kbd-macro
  1994. (ding))
  1995. (message "%s" (error-message-string err))))
  1996. nil) ; Make coverage-tester happy.
  1997. (defun ses--mode-line-process ()
  1998. (let ((cmlp (window-parameter nil 'ses--mode-line-process))
  1999. (curcell (ses--curcell (window-point))))
  2000. (if (equal curcell (car cmlp))
  2001. (cdr cmlp)
  2002. (let ((mlp
  2003. (cond
  2004. ((not curcell) nil)
  2005. ((atom curcell) (list " cell " (symbol-name curcell)))
  2006. (t
  2007. (list " range "
  2008. (symbol-name (car curcell))
  2009. "-"
  2010. (symbol-name (cdr curcell)))))))
  2011. (set-window-parameter nil 'ses--mode-line-process (cons curcell mlp))
  2012. mlp))))
  2013. (defun ses--cursor-sensor-highlight (window)
  2014. (let ((curcell (ses--curcell))
  2015. (ol (window-parameter window 'ses--curcell-overlay)))
  2016. (unless ol
  2017. (setq ol (make-overlay (point) (point)))
  2018. (overlay-put ol 'window window)
  2019. (overlay-put ol 'face 'underline)
  2020. (set-window-parameter window 'ses--curcell-overlay ol))
  2021. ;; Use underline overlay for single-cells only, turn off otherwise.
  2022. (if (listp curcell)
  2023. (delete-overlay ol)
  2024. (let* ((pos (window-point window))
  2025. (next (next-single-property-change pos 'cursor-intangible)))
  2026. (move-overlay ol pos (1- next))))))
  2027. (defun ses-create-header-string ()
  2028. "Set up `ses--header-string' as the buffer's header line.
  2029. Based on the current set of columns and `window-hscroll' position."
  2030. (let ((totwidth (- (window-hscroll)))
  2031. result width x)
  2032. ;; Leave room for the left-side fringe and scrollbar.
  2033. (push (propertize " " 'display '((space :align-to 0))) result)
  2034. (dotimes (col ses--numcols)
  2035. (setq width (ses-col-width col)
  2036. totwidth (+ totwidth width 1))
  2037. (if (= totwidth 1)
  2038. ;; Scrolled so intercolumn space is leftmost.
  2039. (push " " result))
  2040. (when (> totwidth 1)
  2041. (if (> ses--header-row 0)
  2042. (save-excursion
  2043. (ses-goto-print (1- ses--header-row) col)
  2044. (setq x (buffer-substring-no-properties (point)
  2045. (+ (point) width)))
  2046. ;; Strip trailing space.
  2047. (if (string-match "[ \t]+\\'" x)
  2048. (setq x (substring x 0 (match-beginning 0))))
  2049. ;; Cut off excess text.
  2050. (if (>= (length x) totwidth)
  2051. (setq x (substring x 0 (- totwidth -1)))))
  2052. (setq x (ses-column-letter col)))
  2053. (push (propertize x 'face ses-box-prop) result)
  2054. (push (propertize "."
  2055. 'display `((space :align-to ,(1- totwidth)))
  2056. 'face ses-box-prop)
  2057. result)
  2058. ;; Allow the following space to be squished to make room for the 3-D box
  2059. ;; Coverage test ignores properties, thinks this is always a space!
  2060. (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
  2061. result)))
  2062. (if (> ses--header-row 0)
  2063. (push (propertize (format " [row %d]" ses--header-row)
  2064. 'display '((height (- 1))))
  2065. result))
  2066. (setq ses--header-string (apply #'concat (nreverse result)))))
  2067. ;;----------------------------------------------------------------------------
  2068. ;; Redisplay and recalculation
  2069. ;;----------------------------------------------------------------------------
  2070. (defun ses-jump (sym)
  2071. "Move point to cell SYM."
  2072. (interactive (let* (names
  2073. (s (completing-read
  2074. "Jump to cell: "
  2075. (and ses--named-cell-hashmap
  2076. (progn (maphash (lambda (key _val)
  2077. (push (symbol-name key) names))
  2078. ses--named-cell-hashmap)
  2079. names)))))
  2080. (if
  2081. (string= s "")
  2082. (error "Invalid cell name")
  2083. (list (intern s)))))
  2084. (let ((rowcol (ses-sym-rowcol sym)))
  2085. (or rowcol (error "Invalid cell name"))
  2086. (if (eq (symbol-value sym) '*skip*)
  2087. (error "Cell is covered by preceding cell"))
  2088. (ses-goto-print (car rowcol) (cdr rowcol))))
  2089. (defun ses-jump-safe (cell)
  2090. "Like `ses-jump', but no error if invalid cell."
  2091. (ignore-errors
  2092. (ses-jump cell)))
  2093. (defun ses-reprint-all (&optional nonarrow)
  2094. "Recreate the display area. Calls all printer functions. Narrows to
  2095. print area if NONARROW is nil."
  2096. (interactive "*P")
  2097. (widen)
  2098. (unless nonarrow
  2099. (setq ses--deferred-narrow t))
  2100. (let ((startcell (ses--cell-at-pos (point)))
  2101. (inhibit-read-only t))
  2102. (ses-begin-change)
  2103. (goto-char (point-min))
  2104. (search-forward ses-print-data-boundary)
  2105. (backward-char (length ses-print-data-boundary))
  2106. (delete-region (point-min) (point))
  2107. ;; Insert all blank lines before printing anything, so ses-print-cell can
  2108. ;; find the data area when inserting or deleting *skip* values for cells.
  2109. (dotimes (_ ses--numrows)
  2110. (insert-and-inherit ses--blank-line))
  2111. (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
  2112. (if (eq (ses-cell-value row 0) '*skip*)
  2113. ;; Column deletion left a dangling skip.
  2114. (ses-set-cell row 0 'value nil))
  2115. (dotimes (col ses--numcols)
  2116. (ses-print-cell row col))
  2117. (beginning-of-line 2))
  2118. (ses-jump-safe startcell)))
  2119. (defun ses-initialize-Dijkstra-attempt ()
  2120. (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
  2121. ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
  2122. ;; These functions use the variables 'row' and 'col' that are dynamically bound
  2123. ;; by ses-print-cell. We define these variables at compile-time to make the
  2124. ;; compiler happy.
  2125. ;; (defvar row)
  2126. ;; (defvar col)
  2127. ;; (defvar maxrow)
  2128. ;; (defvar maxcol)
  2129. (defun ses-recalculate-cell (&optional curcell)
  2130. "Recalculate and reprint the current cell or range.
  2131. If CURCELL is non nil use it as current cell or range
  2132. without any check, otherwise function (ses-check-curcell 'range)
  2133. is called.
  2134. For an individual cell, shows the error if the formula or printer
  2135. signals one, or otherwise shows the cell's complete value. For a range, the
  2136. cells are recalculated in \"natural\" order, so cells that other cells refer
  2137. to are recalculated first."
  2138. (interactive "*")
  2139. (if curcell (setq ses--curcell curcell)
  2140. (ses-check-curcell 'range))
  2141. (ses-begin-change)
  2142. (ses-initialize-Dijkstra-attempt)
  2143. (let (sig cur-rowcol)
  2144. (setq ses-start-time (float-time))
  2145. (if (atom ses--curcell)
  2146. (when
  2147. (setq cur-rowcol (ses-sym-rowcol ses--curcell)
  2148. sig (progn
  2149. (setf (ses-cell-property :ses-Dijkstra-attempt
  2150. (car cur-rowcol)
  2151. (cdr cur-rowcol))
  2152. (cons ses--Dijkstra-attempt-nb 0))
  2153. (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
  2154. (nconc sig (list (ses-cell-symbol (car cur-rowcol)
  2155. (cdr cur-rowcol)))))
  2156. ;; First, recalculate all cells that don't refer to other cells and
  2157. ;; produce a list of cells with references.
  2158. (ses-dorange ses--curcell
  2159. (ses--time-check "Recalculating... %s" (ses-cell-symbol row col))
  2160. (condition-case nil
  2161. (progn
  2162. ;; The t causes an error if the cell has references. If no
  2163. ;; references, the t will be the result value.
  2164. (1value (ses-formula-references (ses-cell-formula row col) t))
  2165. (setf (ses-cell-property :ses-Dijkstra-attempt row col)
  2166. (cons ses--Dijkstra-attempt-nb 0))
  2167. (when (setq sig (ses-calculate-cell row col t))
  2168. (nconc sig (list (ses-cell-symbol row col)))))
  2169. (wrong-type-argument
  2170. ;; The formula contains a reference.
  2171. (cl-pushnew (ses-cell-symbol row col) ses--deferred-recalc
  2172. :test #'equal)))))
  2173. ;; Do the update now, so we can force recalculation.
  2174. (let ((x ses--deferred-recalc))
  2175. (setq ses--deferred-recalc nil)
  2176. (condition-case hold
  2177. (ses-update-cells x t)
  2178. (error (setq sig hold))))
  2179. (cond
  2180. (sig
  2181. (message "%s" (error-message-string sig)))
  2182. ((consp ses--curcell)
  2183. (message " "))
  2184. (t
  2185. (princ (symbol-value ses--curcell))))))
  2186. (defun ses-recalculate-all ()
  2187. "Recalculate and reprint all cells."
  2188. (interactive "*")
  2189. (let ((startcell (ses--cell-at-pos (point)))
  2190. (ses--curcell (cons (ses-cell-symbol 0 0)
  2191. (ses-cell-symbol (1- ses--numrows)
  2192. (1- ses--numcols)))))
  2193. (ses-recalculate-cell ses--curcell)
  2194. (ses-jump-safe startcell)))
  2195. (defun ses-truncate-cell ()
  2196. "Reprint current cell, but without spillover into any following blank cells."
  2197. (interactive "*")
  2198. (ses-check-curcell)
  2199. (let* ((rowcol (ses-sym-rowcol ses--curcell))
  2200. (row (car rowcol))
  2201. (col (cdr rowcol)))
  2202. (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
  2203. (eq (ses-cell-value row (1+ col)) '*skip*))
  2204. ;; This cell has spill-over. We'll momentarily pretend the following cell
  2205. ;; has a t in it.
  2206. (cl-progv
  2207. (list (ses-cell-symbol row (1+ col)))
  2208. '(t)
  2209. (ses-print-cell row col))
  2210. ;; Now remove the *skip*. ses-print-cell is always nil here.
  2211. (ses-set-cell row (1+ col) 'value nil)
  2212. (1value (ses-print-cell row (1+ col))))))
  2213. (defun ses-reconstruct-all ()
  2214. "Reconstruct buffer based on cell data stored in Emacs variables."
  2215. (interactive "*")
  2216. (ses-begin-change)
  2217. ;;Reconstruct reference lists.
  2218. (let (x yrow ycol)
  2219. ;;Delete old reference lists
  2220. (dotimes-with-progress-reporter
  2221. (row ses--numrows) "Deleting references..."
  2222. (dotimes (col ses--numcols)
  2223. (ses-set-cell row col 'references nil)))
  2224. ;;Create new reference lists
  2225. (dotimes-with-progress-reporter
  2226. (row ses--numrows) "Computing references..."
  2227. (dotimes (col ses--numcols)
  2228. (dolist (ref (ses-formula-references (ses-cell-formula row col)))
  2229. (setq x (ses-sym-rowcol ref)
  2230. yrow (car x)
  2231. ycol (cdr x))
  2232. (ses-set-cell yrow ycol 'references
  2233. (cons (ses-cell-symbol row col)
  2234. (ses-cell-references yrow ycol)))))))
  2235. ;; Delete everything and reconstruct basic data area.
  2236. (ses-widen)
  2237. (let ((inhibit-read-only t))
  2238. (goto-char (point-max))
  2239. (if (search-backward ";; Local Variables:\n" nil t)
  2240. (delete-region (point-min) (point))
  2241. ;; Buffer is quite screwed up --- can't even save the user-specified
  2242. ;; locals.
  2243. (delete-region (point-min) (point-max))
  2244. (insert ses-initial-file-trailer)
  2245. (goto-char (point-min)))
  2246. ;; Create a blank display area.
  2247. (dotimes (_ ses--numrows)
  2248. (insert ses--blank-line))
  2249. (insert ses-print-data-boundary)
  2250. (backward-char (1- (length ses-print-data-boundary)))
  2251. (setq ses--data-marker (point-marker))
  2252. (forward-char (1- (length ses-print-data-boundary)))
  2253. ;; Placeholders for cell data.
  2254. (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
  2255. ;; Placeholders for col-widths, col-printers, default-printer, header-row.
  2256. (insert "\n\n\n\n")
  2257. (insert ses-initial-global-parameters)
  2258. (backward-char (1- (length ses-initial-global-parameters)))
  2259. (setq ses--params-marker (point-marker))
  2260. (forward-char (1- (length ses-initial-global-parameters))))
  2261. (ses-set-parameter 'ses--col-widths ses--col-widths)
  2262. (ses-set-parameter 'ses--col-printers ses--col-printers)
  2263. (ses-set-parameter 'ses--default-printer ses--default-printer)
  2264. (ses-set-parameter 'ses--header-row ses--header-row)
  2265. (ses-set-parameter 'ses--numrows ses--numrows)
  2266. (ses-set-parameter 'ses--numcols ses--numcols)
  2267. ;;Keep our old narrowing
  2268. (ses-setup)
  2269. (ses-recalculate-all)
  2270. (goto-char (point-min)))
  2271. ;;----------------------------------------------------------------------------
  2272. ;; Input of cell formulas
  2273. ;;----------------------------------------------------------------------------
  2274. (defun ses-edit-cell-complete-symbol ()
  2275. (interactive)
  2276. (let ((completion-at-point-functions (cons 'ses--edit-cell-completion-at-point-function
  2277. completion-at-point-functions)))
  2278. (completion-at-point)))
  2279. (defun ses--edit-cell-completion-at-point-function ()
  2280. (and
  2281. ses--completion-table
  2282. (let* ((bol (save-excursion (move-beginning-of-line nil) (point)))
  2283. start end collection
  2284. (prefix
  2285. (save-excursion
  2286. (setq end (point))
  2287. (backward-sexp)
  2288. (if (< (point) bol)
  2289. (progn
  2290. (setq start bol)
  2291. (buffer-substring start end))
  2292. (setq start (point))
  2293. (forward-sexp)
  2294. (if (>= (point) end)
  2295. (progn
  2296. (setq end (point))
  2297. (buffer-substring start end))
  2298. nil))))
  2299. prefix-length)
  2300. (when (and prefix (null (string= prefix "")))
  2301. (setq prefix-length (length prefix))
  2302. (maphash (lambda (key val)
  2303. (let ((key-name (symbol-name key)))
  2304. (when (and (>= (length key-name) prefix-length)
  2305. (string= prefix (substring key-name 0 prefix-length)))
  2306. (push key-name collection))))
  2307. ses--completion-table)
  2308. (and collection (list start end collection))))))
  2309. (defun ses-edit-cell (row col newval)
  2310. "Display current cell contents in minibuffer, for editing. Returns nil if
  2311. cell formula was unsafe and user declined confirmation."
  2312. (interactive
  2313. (progn
  2314. (barf-if-buffer-read-only)
  2315. (ses-check-curcell)
  2316. (let* ((rowcol (ses-sym-rowcol ses--curcell))
  2317. (row (car rowcol))
  2318. (col (cdr rowcol))
  2319. (formula (ses-cell-formula row col))
  2320. initial)
  2321. (if (eq (car-safe formula) 'ses-safe-formula)
  2322. (setq formula (cadr formula)))
  2323. (if (eq (car-safe formula) 'quote)
  2324. (setq initial (format "'%S" (cadr formula)))
  2325. (setq initial (prin1-to-string formula)))
  2326. (if (stringp formula)
  2327. ;; Position cursor inside close-quote.
  2328. (setq initial (cons initial (length initial))))
  2329. (dolist (key ses-completion-keys)
  2330. (define-key ses-mode-edit-map key 'ses-edit-cell-complete-symbol))
  2331. ;; make it globally visible, so that it can be visible from the minibuffer.
  2332. (setq ses--completion-table ses--named-cell-hashmap)
  2333. (list row col
  2334. (read-from-minibuffer (format "Cell %s: " ses--curcell)
  2335. initial
  2336. ses-mode-edit-map
  2337. t ; Convert to Lisp object.
  2338. 'ses-read-cell-history)))))
  2339. (when (ses-warn-unsafe newval 'unsafep)
  2340. (ses-begin-change)
  2341. (ses-cell-set-formula row col newval)
  2342. t))
  2343. (defun ses-read-cell (row col newval)
  2344. "Self-insert for initial character of cell function."
  2345. (interactive
  2346. (let* ((initial (this-command-keys))
  2347. (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
  2348. (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
  2349. (barf-if-buffer-read-only)
  2350. (list (car rowcol)
  2351. (cdr rowcol)
  2352. (if (equal initial "\"")
  2353. (progn
  2354. (if (not (stringp curval)) (setq curval nil))
  2355. (read-string (if curval
  2356. (format "String Cell %s (default %s): "
  2357. ses--curcell curval)
  2358. (format "String Cell %s: " ses--curcell))
  2359. nil 'ses-read-string-history curval))
  2360. (read-from-minibuffer
  2361. (format "Cell %s: " ses--curcell)
  2362. (cons (if (equal initial "(") "()" initial) 2)
  2363. ses-mode-edit-map
  2364. t ; Convert to Lisp object.
  2365. 'ses-read-cell-history
  2366. (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
  2367. (cadr curval)
  2368. curval)))))))
  2369. (when (ses-edit-cell row col newval)
  2370. (ses-command-hook) ; Update cell widths before movement.
  2371. (dolist (x ses-after-entry-functions)
  2372. (funcall x 1))))
  2373. (defun ses-read-symbol (row col symb)
  2374. "Self-insert for a symbol as a cell formula. The set of all symbols that
  2375. have been used as formulas in this spreadsheet is available for completions."
  2376. (interactive
  2377. (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
  2378. newval)
  2379. (barf-if-buffer-read-only)
  2380. (setq newval (completing-read (format "Cell %s ': " ses--curcell)
  2381. ses--symbolic-formulas))
  2382. (list (car rowcol)
  2383. (cdr rowcol)
  2384. (if (string= newval "")
  2385. nil ; Don't create zero-length symbols!
  2386. (list 'quote (intern newval))))))
  2387. (when (ses-edit-cell row col symb)
  2388. (ses-command-hook) ; Update cell widths before movement.
  2389. (dolist (x ses-after-entry-functions)
  2390. (funcall x 1))))
  2391. (defun ses-clear-cell-forward (count)
  2392. "Delete formula and printer for current cell and then move to next cell.
  2393. With prefix, deletes several cells."
  2394. (interactive "*p")
  2395. (if (< count 0)
  2396. (1value (ses-clear-cell-backward (- count)))
  2397. (ses-check-curcell)
  2398. (ses-begin-change)
  2399. (dotimes (_ count)
  2400. (ses-set-curcell)
  2401. (let ((rowcol (ses-sym-rowcol ses--curcell)))
  2402. (or rowcol (signal 'end-of-buffer nil))
  2403. (ses-clear-cell (car rowcol) (cdr rowcol)))
  2404. (forward-char 1))))
  2405. (defun ses-clear-cell-backward (count)
  2406. "Move to previous cell and then delete it. With prefix, deletes several
  2407. cells."
  2408. (interactive "*p")
  2409. (if (< count 0)
  2410. (1value (ses-clear-cell-forward (- count)))
  2411. (ses-check-curcell 'end)
  2412. (ses-begin-change)
  2413. (dotimes (_ count)
  2414. (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
  2415. (ses-set-curcell)
  2416. (let ((rowcol (ses-sym-rowcol ses--curcell)))
  2417. (ses-clear-cell (car rowcol) (cdr rowcol))))))
  2418. ;;----------------------------------------------------------------------------
  2419. ;; Input of cell-printer functions
  2420. ;;----------------------------------------------------------------------------
  2421. (defun ses-read-printer-complete-symbol ()
  2422. (interactive)
  2423. (let ((completion-at-point-functions (cons 'ses--read-printer-completion-at-point-function
  2424. completion-at-point-functions)))
  2425. (completion-at-point)))
  2426. (defun ses--read-printer-completion-at-point-function ()
  2427. (let* ((bol (save-excursion (move-beginning-of-line nil) (point)))
  2428. start end collection
  2429. (prefix
  2430. (save-excursion
  2431. (setq end (point))
  2432. (backward-sexp)
  2433. (if (< (point) bol)
  2434. (progn
  2435. (setq start bol)
  2436. (buffer-substring start end))
  2437. (setq start (point))
  2438. (forward-sexp)
  2439. (if (>= (point) end)
  2440. (progn
  2441. (setq end (point))
  2442. (buffer-substring start end))
  2443. nil))))
  2444. prefix-length)
  2445. (when prefix
  2446. (setq prefix-length (length prefix))
  2447. (maphash (lambda (key val)
  2448. (let ((key-name (symbol-name key)))
  2449. (when (and (>= (length key-name) prefix-length)
  2450. (string= prefix (substring key-name 0 prefix-length)))
  2451. (push key-name collection))))
  2452. ses--completion-table)
  2453. (and collection (list start end collection)))))
  2454. (defun ses-read-printer (prompt default)
  2455. "Common code for functions `ses-read-cell-printer', `ses-read-column-printer',
  2456. `ses-read-default-printer' and `ses-define-local-printer'.
  2457. PROMPT should end with \": \". Result is t if operation was
  2458. canceled."
  2459. (barf-if-buffer-read-only)
  2460. (if (eq default t)
  2461. (setq default "")
  2462. (setq prompt (format "%s (default %S): "
  2463. (substring prompt 0 -2)
  2464. default)))
  2465. (dolist (key ses-completion-keys)
  2466. (define-key ses-mode-edit-map key 'ses-read-printer-complete-symbol))
  2467. ;; make it globally visible, so that it can be visible from the minibuffer.
  2468. (setq ses--completion-table ses--local-printer-hashmap)
  2469. (let ((new (read-from-minibuffer prompt
  2470. nil ; Initial contents.
  2471. ses-mode-edit-map
  2472. t ; Evaluate the result.
  2473. 'ses-read-printer-history
  2474. (prin1-to-string default))))
  2475. (if (equal new default)
  2476. ;; User changed mind, decided not to change printer.
  2477. (setq new t)
  2478. (ses-printer-validate new)
  2479. (or (not new)
  2480. (stringp new)
  2481. (stringp (car-safe new))
  2482. (and (symbolp new) (gethash new ses--local-printer-hashmap))
  2483. (ses-warn-unsafe new 'unsafep-function)
  2484. (setq new t)))
  2485. new))
  2486. (defun ses-read-cell-printer (newval)
  2487. "Set the printer function for the current cell or range.
  2488. A printer function is either a string (a format control-string with one
  2489. %-sequence -- result from format will be right-justified), or a list of one
  2490. string (result from format will be left-justified), or a lambda-expression of
  2491. one argument, or a symbol that names a function of one argument. In the
  2492. latter two cases, the function's result should be either a string (will be
  2493. right-justified) or a list of one string (will be left-justified)."
  2494. (interactive
  2495. (let ((default t))
  2496. (ses-check-curcell 'range)
  2497. ;;Default is none if not all cells in range have same printer
  2498. (catch 'ses-read-cell-printer
  2499. (ses-dorange ses--curcell
  2500. (let ((x (ses-cell-printer row col)))
  2501. (if (eq (car-safe x) 'ses-safe-printer)
  2502. (setq x (cadr x)))
  2503. (if (eq default t)
  2504. (setq default x)
  2505. (unless (equal default x)
  2506. ;;Range contains differing printer functions
  2507. (setq default t)
  2508. (throw 'ses-read-cell-printer t))))))
  2509. (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
  2510. default))))
  2511. (unless (eq newval t)
  2512. (ses-begin-change)
  2513. (ses-dorange ses--curcell
  2514. (ses-set-cell row col 'printer newval)
  2515. (ses-print-cell row col))))
  2516. (defun ses-read-column-printer (col newval)
  2517. "Set the printer function for the current column.
  2518. See `ses-read-cell-printer' for input forms."
  2519. (interactive
  2520. (let ((col (cdr (ses-sym-rowcol ses--curcell))))
  2521. (ses-check-curcell)
  2522. (list col (ses-read-printer (format "Column %s printer: "
  2523. (ses-column-letter col))
  2524. (ses-col-printer col)))))
  2525. (unless (eq newval t)
  2526. (ses-begin-change)
  2527. (ses-set-parameter 'ses--col-printers newval col)
  2528. (save-excursion
  2529. (dotimes (row ses--numrows)
  2530. (ses-print-cell row col)))))
  2531. (defun ses-read-default-printer (newval)
  2532. "Set the default printer function for cells that have no other.
  2533. See `ses-read-cell-printer' for input forms."
  2534. (interactive
  2535. (list (ses-read-printer "Default printer: " ses--default-printer)))
  2536. (unless (eq newval t)
  2537. (ses-begin-change)
  2538. (ses-set-parameter 'ses--default-printer newval)
  2539. (ses-reprint-all t)))
  2540. ;;----------------------------------------------------------------------------
  2541. ;; Spreadsheet size adjustments
  2542. ;;----------------------------------------------------------------------------
  2543. (defun ses-insert-row (count)
  2544. "Insert a new row before the current one.
  2545. With prefix, insert COUNT rows before current one."
  2546. (interactive "*p")
  2547. (ses-check-curcell 'end)
  2548. (or (> count 0) (signal 'args-out-of-range nil))
  2549. (ses-begin-change)
  2550. (let ((inhibit-quit t)
  2551. (inhibit-read-only t)
  2552. (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
  2553. newrow)
  2554. ;;Create a new set of cell-variables
  2555. (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
  2556. 0 (1- ses--numcols))
  2557. (ses-set-parameter 'ses--numrows (+ ses--numrows count))
  2558. ;;Insert each row
  2559. (ses-goto-print row 0)
  2560. (dotimes-with-progress-reporter (x count) "Inserting row..."
  2561. ;;Create a row of empty cells. The `symbol' fields will be set by
  2562. ;;the call to ses-relocate-all.
  2563. (setq newrow (make-vector ses--numcols nil))
  2564. (dotimes (col ses--numcols)
  2565. (aset newrow col (ses-make-cell)))
  2566. (setq ses--cells (ses-vector-insert ses--cells row newrow))
  2567. (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
  2568. (insert ses--blank-line))
  2569. ;;Insert empty lines in cell data area (will be replaced by
  2570. ;;ses-relocate-all)
  2571. (ses-goto-data row 0)
  2572. (insert (make-string (* (1+ ses--numcols) count) ?\n))
  2573. (ses-relocate-all row 0 count 0)
  2574. ;;If any cell printers insert constant text, insert that text
  2575. ;;into the line.
  2576. (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
  2577. (global (ses-call-printer ses--default-printer)))
  2578. (if (or (> (length cols) 0) (> (length global) 0))
  2579. (dotimes (x count)
  2580. (dotimes (col ses--numcols)
  2581. ;;These cells are always nil, only constant formatting printed
  2582. (1value (ses-print-cell (+ x row) col))))))
  2583. (when (> ses--header-row row)
  2584. ;;Inserting before header
  2585. (ses-set-parameter 'ses--header-row (+ ses--header-row count))
  2586. (ses-reset-header-string)))
  2587. ;;Reconstruct text attributes
  2588. (ses-setup)
  2589. ;;Prepare for undo
  2590. (push '(apply ses-widen) buffer-undo-list)
  2591. ;;Return to current cell
  2592. (if ses--curcell
  2593. (ses-jump-safe ses--curcell)
  2594. (ses-goto-print (1- ses--numrows) 0)))
  2595. (defun ses-delete-row (count)
  2596. "Delete the current row.
  2597. With prefix, deletes COUNT rows starting from the current one."
  2598. (interactive "*p")
  2599. (ses-check-curcell)
  2600. (or (> count 0) (signal 'args-out-of-range nil))
  2601. (let ((inhibit-quit t)
  2602. (inhibit-read-only t)
  2603. (row (car (ses-sym-rowcol ses--curcell))))
  2604. (setq count (min count (- ses--numrows row)))
  2605. (ses-begin-change)
  2606. (ses-set-parameter 'ses--numrows (- ses--numrows count))
  2607. ;;Delete lines from print area
  2608. (ses-goto-print row 0)
  2609. (ses-delete-line count)
  2610. ;;Delete lines from cell data area
  2611. (ses-goto-data row 0)
  2612. (ses-delete-line (* count (1+ ses--numcols)))
  2613. ;; Collect named cells in the deleted rows, in order to clean the
  2614. ;; symbols out of the named cell hash map, once the deletion is
  2615. ;; complete
  2616. (unless (null ses--in-killing-named-cell-list)
  2617. (warn "Internal error, `ses--in-killing-named-cell-list' should be nil, but is equal to %S"
  2618. ses--in-killing-named-cell-list)
  2619. (setq ses--in-killing-named-cell-list nil))
  2620. (dotimes-with-progress-reporter (nrow count)
  2621. "Collecting named cell in deleted rows..."
  2622. (dotimes (col ses--numcols)
  2623. (let* ((row (+ row nrow))
  2624. (sym (ses-cell-symbol row col)))
  2625. (and (eq (get sym 'ses-cell) :ses-named)
  2626. (push sym ses--in-killing-named-cell-list)))))
  2627. ;;Relocate variables and formulas
  2628. (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
  2629. (ses-relocate-all row 0 (- count) 0)
  2630. (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
  2631. 0 (1- ses--numcols))
  2632. (when (> ses--header-row row)
  2633. (if (<= ses--header-row (+ row count))
  2634. ;;Deleting the header row
  2635. (ses-set-parameter 'ses--header-row 0)
  2636. (ses-set-parameter 'ses--header-row (- ses--header-row count)))
  2637. (ses-reset-header-string)))
  2638. ;;Reconstruct attributes
  2639. (ses-setup)
  2640. ;;Prepare for undo
  2641. (push '(apply ses-widen) buffer-undo-list)
  2642. (ses-jump-safe ses--curcell))
  2643. (defun ses-insert-column (count &optional col width printer)
  2644. "Insert a new column before COL (default is the current one).
  2645. With prefix, insert COUNT columns before current one.
  2646. If COL is specified, the new column(s) get the specified WIDTH and PRINTER
  2647. \(otherwise they're taken from the current column)."
  2648. (interactive "*p")
  2649. (ses-check-curcell)
  2650. (or (> count 0) (signal 'args-out-of-range nil))
  2651. (or col
  2652. (setq col (cdr (ses-sym-rowcol ses--curcell))
  2653. width (ses-col-width col)
  2654. printer (ses-col-printer col)))
  2655. (ses-begin-change)
  2656. (let ((inhibit-quit t)
  2657. (inhibit-read-only t)
  2658. (widths ses--col-widths)
  2659. (printers ses--col-printers)
  2660. has-skip)
  2661. ;;Create a new set of cell-variables
  2662. (ses-create-cell-variable-range 0 (1- ses--numrows)
  2663. ses--numcols (+ ses--numcols count -1))
  2664. ;;Insert each column.
  2665. (dotimes-with-progress-reporter (x count) "Inserting column..."
  2666. ;;Create a column of empty cells. The `symbol' fields will be set by
  2667. ;;the call to ses-relocate-all.
  2668. (ses-adjust-print-width col (1+ width))
  2669. (ses-set-parameter 'ses--numcols (1+ ses--numcols))
  2670. (dotimes (row ses--numrows)
  2671. (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
  2672. ;;Inserting in the middle of a spill-over
  2673. (setq has-skip t))
  2674. (ses-aset-with-undo ses--cells row
  2675. (ses-vector-insert (aref ses--cells row)
  2676. col (ses-make-cell)))
  2677. ;;Insert empty lines in cell data area (will be replaced by
  2678. ;;ses-relocate-all)
  2679. (ses-goto-data row col)
  2680. (insert ?\n))
  2681. ;; Insert column width and printer.
  2682. (setq widths (ses-vector-insert widths col width)
  2683. printers (ses-vector-insert printers col printer)))
  2684. (ses-set-parameter 'ses--col-widths widths)
  2685. (ses-set-parameter 'ses--col-printers printers)
  2686. (ses-reset-header-string)
  2687. (ses-relocate-all 0 col 0 count)
  2688. (if has-skip
  2689. (ses-reprint-all t)
  2690. (when (or (> (length (ses-call-printer printer)) 0)
  2691. (> (length (ses-call-printer ses--default-printer)) 0))
  2692. ;; Either column printer or global printer inserts some constant text.
  2693. ;; Reprint the new columns to insert that text.
  2694. (dotimes (x ses--numrows)
  2695. (dotimes (y count)
  2696. ;; Always nil here --- this is a blank column.
  2697. (1value (ses-print-cell-new-width x (+ y col))))))
  2698. (ses-setup)))
  2699. (ses-jump-safe ses--curcell))
  2700. (defun ses-delete-column (count)
  2701. "Delete the current column.
  2702. With prefix, deletes COUNT columns starting from the current one."
  2703. (interactive "*p")
  2704. (ses-check-curcell)
  2705. (or (> count 0) (signal 'args-out-of-range nil))
  2706. (let ((inhibit-quit t)
  2707. (inhibit-read-only t)
  2708. (rowcol (ses-sym-rowcol ses--curcell))
  2709. (width 0)
  2710. col origrow has-skip)
  2711. (setq origrow (car rowcol)
  2712. col (cdr rowcol)
  2713. count (min count (- ses--numcols col)))
  2714. (if (= count ses--numcols)
  2715. (error "Can't delete all columns!"))
  2716. ;;Determine width of column(s) being deleted
  2717. (dotimes (x count)
  2718. (setq width (+ width (ses-col-width (+ col x)) 1)))
  2719. (ses-begin-change)
  2720. (ses-set-parameter 'ses--numcols (- ses--numcols count))
  2721. (ses-adjust-print-width col (- width))
  2722. ;; Prepare collecting named cells in the deleted columns, in order
  2723. ;; to clean the symbols out of the named cell hash map, once the
  2724. ;; deletion is complete
  2725. (unless (null ses--in-killing-named-cell-list)
  2726. (warn "Internal error, `ses--in-killing-named-cell-list' should be nil, but is equal to %S"
  2727. ses--in-killing-named-cell-list)
  2728. (setq ses--in-killing-named-cell-list nil))
  2729. (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
  2730. ;;Delete lines from cell data area
  2731. (ses-goto-data row col)
  2732. (ses-delete-line count)
  2733. ;; Collect named cells in the deleted columns within this row
  2734. (dotimes (ncol count)
  2735. (let ((sym (ses-cell-symbol row (+ col ncol))))
  2736. (and (eq (get sym 'ses-cell) :ses-named)
  2737. (push sym ses--in-killing-named-cell-list))))
  2738. ;;Delete cells. Check if deletion area begins or ends with a skip.
  2739. (if (or (eq (ses-cell-value row col) '*skip*)
  2740. (and (< col ses--numcols)
  2741. (eq (ses-cell-value row (+ col count)) '*skip*)))
  2742. (setq has-skip t))
  2743. (ses-aset-with-undo ses--cells row
  2744. (ses-vector-delete (aref ses--cells row) col count)))
  2745. ;;Update globals
  2746. (ses-set-parameter 'ses--col-widths
  2747. (ses-vector-delete ses--col-widths col count))
  2748. (ses-set-parameter 'ses--col-printers
  2749. (ses-vector-delete ses--col-printers col count))
  2750. (ses-reset-header-string)
  2751. ;;Relocate variables and formulas
  2752. (ses-relocate-all 0 col 0 (- count))
  2753. (ses-destroy-cell-variable-range 0 (1- ses--numrows)
  2754. ses--numcols (+ ses--numcols count -1))
  2755. (if has-skip
  2756. (ses-reprint-all t)
  2757. (ses-setup))
  2758. (if (>= col ses--numcols)
  2759. (setq col (1- col)))
  2760. (ses-goto-print origrow col)))
  2761. (defun ses-forward-or-insert (&optional count)
  2762. "Move to next cell in row, or inserts a new cell if already in last one, or
  2763. inserts a new row if at bottom of print area. Repeat COUNT times."
  2764. (interactive "p")
  2765. (ses-check-curcell 'end)
  2766. (setq deactivate-mark t) ; Doesn't combine well with ranges.
  2767. (dotimes (x count)
  2768. (ses-set-curcell)
  2769. (if (not ses--curcell)
  2770. (progn ; At bottom of print area.
  2771. (barf-if-buffer-read-only)
  2772. (ses-insert-row 1))
  2773. (let ((col (cdr (ses-sym-rowcol ses--curcell))))
  2774. (when (/= 32
  2775. (char-before (next-single-property-change (point)
  2776. 'cursor-intangible)))
  2777. ;; We're already in last nonskipped cell on line. Need to create a
  2778. ;; new column.
  2779. (barf-if-buffer-read-only)
  2780. (ses-insert-column (- count x)
  2781. ses--numcols
  2782. (ses-col-width col)
  2783. (ses-col-printer col)))))
  2784. (forward-char)))
  2785. (defun ses-append-row-jump-first-column ()
  2786. "Insert a new row after current one and jump to its first column."
  2787. (interactive "*")
  2788. (ses-check-curcell)
  2789. (ses-begin-change)
  2790. (beginning-of-line 2)
  2791. (ses-set-curcell)
  2792. (ses-insert-row 1))
  2793. (defun ses-set-column-width (col newwidth)
  2794. "Set the width of the current column."
  2795. (interactive
  2796. (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
  2797. (barf-if-buffer-read-only)
  2798. (list col
  2799. (if current-prefix-arg
  2800. (prefix-numeric-value current-prefix-arg)
  2801. (read-from-minibuffer (format "Column %s width (default %d): "
  2802. (ses-column-letter col)
  2803. (ses-col-width col))
  2804. nil ; No initial contents.
  2805. nil ; No override keymap.
  2806. t ; Convert to Lisp object.
  2807. nil ; No history.
  2808. (number-to-string
  2809. (ses-col-width col))))))) ; Default value.
  2810. (if (< newwidth 1)
  2811. (error "Invalid column width"))
  2812. (ses-begin-change)
  2813. (ses-reset-header-string)
  2814. (save-excursion
  2815. (let ((inhibit-quit t))
  2816. (ses-adjust-print-width col (- newwidth (ses-col-width col)))
  2817. (ses-set-parameter 'ses--col-widths newwidth col))
  2818. (dotimes (row ses--numrows)
  2819. (ses-print-cell-new-width row col))))
  2820. ;;----------------------------------------------------------------------------
  2821. ;; Cut and paste, import and export
  2822. ;;----------------------------------------------------------------------------
  2823. (defun ses--advice-copy-region-as-kill (crak-fun beg end &rest args)
  2824. ;; FIXME: Why doesn't it make sense to copy read-only or
  2825. ;; intangible attributes? They're removed upon yank!
  2826. "It doesn't make sense to copy read-only or intangible attributes into the
  2827. kill ring. It probably doesn't make sense to copy keymap properties.
  2828. We'll assume copying front-sticky properties doesn't make sense, either.
  2829. This advice also includes some SES-specific code because otherwise it's too
  2830. hard to override how mouse-1 works."
  2831. (when (> beg end)
  2832. (let ((temp beg))
  2833. (setq beg end
  2834. end temp)))
  2835. (if (not (and (derived-mode-p 'ses-mode)
  2836. (eq (get-text-property beg 'read-only) 'ses)
  2837. (eq (get-text-property (1- end) 'read-only) 'ses)))
  2838. (apply crak-fun beg end args) ; Normal copy-region-as-kill.
  2839. (kill-new (ses-copy-region beg end))
  2840. (if transient-mark-mode
  2841. (setq deactivate-mark t))
  2842. nil))
  2843. (advice-add 'copy-region-as-kill :around #'ses--advice-copy-region-as-kill)
  2844. (defun ses-copy-region (beg end)
  2845. "Treat the region as rectangular. Convert the intangible attributes to
  2846. SES attributes recording the contents of the cell as of the time of copying."
  2847. (when (= end ses--data-marker)
  2848. ;;Avoid overflow situation
  2849. (setq end (1- ses--data-marker)))
  2850. (let* ((x (mapconcat #'ses-copy-region-helper
  2851. (extract-rectangle beg (1- end)) "\n")))
  2852. (remove-text-properties 0 (length x)
  2853. '(read-only t
  2854. cursor-intangible t
  2855. keymap t
  2856. front-sticky t)
  2857. x)
  2858. x))
  2859. (defun ses-copy-region-helper (line)
  2860. "Converts one line (of a rectangle being extracted from a spreadsheet) to
  2861. external form by attaching to each print cell a `ses' attribute that records
  2862. the corresponding data cell."
  2863. (or (> (length line) 1)
  2864. (error "Empty range"))
  2865. (let ((inhibit-read-only t)
  2866. (pos 0)
  2867. mycell next sym rowcol)
  2868. (while pos
  2869. (setq sym (ses--cell-at-pos pos line)
  2870. next (next-single-property-change pos 'cursor-intangible line)
  2871. rowcol (ses-sym-rowcol sym)
  2872. mycell (ses-get-cell (car rowcol) (cdr rowcol)))
  2873. (put-text-property pos (or next (length line))
  2874. 'ses
  2875. (list (ses-cell-symbol mycell)
  2876. (ses-cell-formula mycell)
  2877. (ses-cell-printer mycell))
  2878. line)
  2879. (setq pos next)))
  2880. line)
  2881. (defun ses-kill-override (beg end)
  2882. "Generic override for any commands that kill text.
  2883. We clear the killed cells instead of deleting them."
  2884. (interactive "r")
  2885. (ses-check-curcell 'needrange)
  2886. ;; For some reason, the text-read-only error is not caught by `delete-region',
  2887. ;; so we have to use subterfuge.
  2888. (let ((buffer-read-only t))
  2889. (1value (condition-case nil
  2890. (noreturn (funcall (lookup-key (current-global-map)
  2891. (this-command-keys))
  2892. beg end))
  2893. (buffer-read-only nil)))) ; The expected error.
  2894. ;; Because the buffer was marked read-only, the kill command turned itself
  2895. ;; into a copy. Now we clear the cells or signal the error. First we check
  2896. ;; whether the buffer really is read-only.
  2897. (barf-if-buffer-read-only)
  2898. (ses-begin-change)
  2899. (ses-dorange ses--curcell
  2900. (ses-clear-cell row col))
  2901. (ses-jump (car ses--curcell)))
  2902. (defun ses--advice-yank (yank-fun &optional arg &rest args)
  2903. "In SES mode, the yanked text is inserted as cells.
  2904. If the text contains `ses' attributes (meaning it went to the kill-ring from a
  2905. SES buffer), the formulas and print functions are restored for the cells. If
  2906. the text contains tabs, this is an insertion of tab-separated formulas.
  2907. Otherwise the text is inserted as the formula for the current cell.
  2908. When inserting cells, the formulas are usually relocated to keep the same
  2909. relative references to neighboring cells. This is best if the formulas
  2910. generally refer to other cells within the yanked text. You can use the C-u
  2911. prefix to specify insertion without relocation, which is best when the
  2912. formulas refer to cells outside the yanked text.
  2913. When inserting formulas, the text is treated as a string constant if it doesn't
  2914. make sense as a sexp or would otherwise be considered a symbol. Use `sym' to
  2915. explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
  2916. as symbols."
  2917. (if (not (and (derived-mode-p 'ses-mode)
  2918. (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
  2919. (apply yank-fun arg args) ; Normal non-SES yank.
  2920. (ses-check-curcell 'end)
  2921. (push-mark)
  2922. (let ((text (current-kill (cond
  2923. ((listp arg) 0)
  2924. ((eq arg '-) -1)
  2925. (t (1- arg))))))
  2926. (or (ses-yank-cells text arg)
  2927. (ses-yank-tsf text arg)
  2928. (ses-yank-one (ses-yank-resize 1 1)
  2929. text
  2930. 0
  2931. (if (memq (aref text (1- (length text))) '(?\t ?\n))
  2932. ;; Just one cell --- delete final tab or newline.
  2933. (1- (length text)))
  2934. arg)))
  2935. (if (consp arg)
  2936. (exchange-point-and-mark))))
  2937. (advice-add 'yank :around #'ses--advice-yank)
  2938. (defun ses-yank-pop (arg)
  2939. "Replace just-yanked stretch of killed text with a different stretch.
  2940. This command is allowed only immediately after a `yank' or a `yank-pop',
  2941. when the region contains a stretch of reinserted previously-killed text.
  2942. We replace it with a different stretch of killed text.
  2943. Unlike standard `yank-pop', this function uses `undo' to delete the
  2944. previous insertion."
  2945. (interactive "*p")
  2946. (or (eq last-command 'yank)
  2947. ;;Use noreturn here just to avoid a "poor-coverage" warning in its
  2948. ;;macro definition.
  2949. (noreturn (error "Previous command was not a yank")))
  2950. (undo)
  2951. (ses-set-curcell)
  2952. (yank (1+ (or arg 1)))
  2953. (setq this-command 'yank))
  2954. (defun ses-yank-cells (text arg)
  2955. "If the TEXT has a proper set of `ses' attributes, insert the text as
  2956. cells, else return nil. The cells are reprinted--the supplied text is
  2957. ignored because the column widths, default printer, etc. at yank time might
  2958. be different from those at kill-time. ARG is a list to indicate that
  2959. formulas are to be inserted without relocation."
  2960. (let ((first (get-text-property 0 'ses text))
  2961. (last (get-text-property (1- (length text)) 'ses text)))
  2962. (when (and first last) ;;Otherwise not proper set of attributes
  2963. (setq first (ses-sym-rowcol (car first))
  2964. last (ses-sym-rowcol (car last)))
  2965. (let* ((needrows (- (car last) (car first) -1))
  2966. (needcols (- (cdr last) (cdr first) -1))
  2967. (rowcol (ses-yank-resize needrows needcols))
  2968. (rowincr (- (car rowcol) (car first)))
  2969. (colincr (- (cdr rowcol) (cdr first)))
  2970. (pos 0)
  2971. myrow mycol x)
  2972. (dotimes-with-progress-reporter (row needrows) "Yanking..."
  2973. (setq myrow (+ row (car rowcol)))
  2974. (dotimes (col needcols)
  2975. (setq mycol (+ col (cdr rowcol))
  2976. last (get-text-property pos 'ses text)
  2977. pos (next-single-property-change pos 'ses text)
  2978. x (ses-sym-rowcol (car last)))
  2979. (if (not last)
  2980. ;; Newline --- all remaining cells on row are skipped.
  2981. (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
  2982. last (list nil nil nil)
  2983. pos (1- pos)))
  2984. (if (/= (car x) (- myrow rowincr))
  2985. (error "Cell row error"))
  2986. (if (< (- mycol colincr) (cdr x))
  2987. ;; Some columns were skipped.
  2988. (let ((oldcol mycol))
  2989. (while (< (- mycol colincr) (cdr x))
  2990. (ses-clear-cell myrow mycol)
  2991. (setq col (1+ col)
  2992. mycol (1+ mycol)))
  2993. (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
  2994. (when (car last) ; Skip this for *skip* cells.
  2995. (setq x (nth 2 last))
  2996. (unless (equal x (ses-cell-printer myrow mycol))
  2997. (or (not x)
  2998. (stringp x)
  2999. (eq (car-safe x) 'ses-safe-printer)
  3000. (setq x `(ses-safe-printer ,x)))
  3001. (ses-set-cell myrow mycol 'printer x))
  3002. (setq x (cadr last))
  3003. (if (atom arg)
  3004. (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
  3005. (or (atom x)
  3006. (eq (car-safe x) 'ses-safe-formula)
  3007. (setq x `(ses-safe-formula ,x)))
  3008. (ses-cell-set-formula myrow mycol x)))
  3009. (when pos
  3010. (if (get-text-property pos 'ses text)
  3011. (error "Missing newline between rows"))
  3012. (setq pos (next-single-property-change pos 'ses text))))
  3013. t))))
  3014. (defun ses-yank-one (rowcol text from to arg)
  3015. "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
  3016. cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
  3017. (let ((val (condition-case nil
  3018. (read-from-string text from to)
  3019. (error (cons nil from)))))
  3020. (cond
  3021. ((< (cdr val) (or to (length text)))
  3022. ;; Invalid sexp --- leave it as a string.
  3023. (setq val (substring text from to)))
  3024. ((and (car val) (symbolp (car val)))
  3025. (setq val (if (consp arg)
  3026. (list 'quote (car val)) ; Keep symbol.
  3027. (substring text from to)))) ; Treat symbol as text.
  3028. (t
  3029. (setq val (car val))))
  3030. (let ((row (car rowcol))
  3031. (col (cdr rowcol)))
  3032. (or (atom val)
  3033. (setq val `(ses-safe-formula ,val)))
  3034. (ses-cell-set-formula row col val))))
  3035. (defun ses-yank-tsf (text arg)
  3036. "If TEXT contains tabs and/or newlines, treat the tabs as
  3037. column-separators and the newlines as row-separators and insert the text as
  3038. cell formulas--else return nil. Treat plain symbols as strings unless ARG
  3039. is a list. Ignore a final newline."
  3040. (if (or (not (string-match "[\t\n]" text))
  3041. (= (match-end 0) (length text)))
  3042. ;;Not TSF format
  3043. nil
  3044. (if (/= (aref text (1- (length text))) ?\n)
  3045. (setq text (concat text "\n")))
  3046. (let ((pos -1)
  3047. (spots (list -1))
  3048. (cols 0)
  3049. (needrows 0)
  3050. needcols rowcol)
  3051. ;;Find all the tabs and newlines
  3052. (while (setq pos (string-match "[\t\n]" text (1+ pos)))
  3053. (push pos spots)
  3054. (setq cols (1+ cols))
  3055. (when (eq (aref text pos) ?\n)
  3056. (if (not needcols)
  3057. (setq needcols cols)
  3058. (or (= needcols cols)
  3059. (error "Inconsistent row lengths")))
  3060. (setq cols 0
  3061. needrows (1+ needrows))))
  3062. ;;Insert the formulas
  3063. (setq rowcol (ses-yank-resize needrows needcols))
  3064. (dotimes (row needrows)
  3065. (dotimes (col needcols)
  3066. (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
  3067. (+ (cdr rowcol) needcols (- col) -1))
  3068. text (1+ (cadr spots)) (car spots) arg)
  3069. (setq spots (cdr spots))))
  3070. (ses-goto-print (+ (car rowcol) needrows -1)
  3071. (+ (cdr rowcol) needcols -1))
  3072. t)))
  3073. (defun ses-yank-resize (needrows needcols)
  3074. "If this yank will require inserting rows and/or columns, ask for
  3075. confirmation and then insert them. Result is (row,col) for top left of yank
  3076. spot, or error signal if user requests cancel."
  3077. (ses-begin-change)
  3078. (let ((rowcol (if ses--curcell
  3079. (ses-sym-rowcol ses--curcell)
  3080. (cons ses--numrows 0)))
  3081. rowbool colbool)
  3082. (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
  3083. needcols (- (+ (cdr rowcol) needcols) ses--numcols)
  3084. rowbool (> needrows 0)
  3085. colbool (> needcols 0))
  3086. (when (or rowbool colbool)
  3087. ;;Need to insert. Get confirm
  3088. (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
  3089. (if rowbool (format "%d rows" needrows) "")
  3090. (if (and rowbool colbool) " and " "")
  3091. (if colbool (format "%d columns" needcols) "")))
  3092. (error "Canceled"))
  3093. (when rowbool
  3094. (let (ses--curcell)
  3095. (save-excursion
  3096. (ses-goto-print ses--numrows 0)
  3097. (ses-insert-row needrows))))
  3098. (when colbool
  3099. (ses-insert-column needcols
  3100. ses--numcols
  3101. (ses-col-width (1- ses--numcols))
  3102. (ses-col-printer (1- ses--numcols)))))
  3103. rowcol))
  3104. (defun ses-export-tsv (_beg _end)
  3105. "Export values from the current range, with tabs between columns and
  3106. newlines between rows. Result is placed in kill ring."
  3107. (interactive "r")
  3108. (ses-export-tab nil))
  3109. (defun ses-export-tsf (_beg _end)
  3110. "Export formulas from the current range, with tabs between columns and
  3111. newlines between rows. Result is placed in kill ring."
  3112. (interactive "r")
  3113. (ses-export-tab t))
  3114. (defun ses-export-tab (want-formulas)
  3115. "Export the current range with tabs between columns and newlines between rows.
  3116. Result is placed in kill ring. The export is values unless WANT-FORMULAS
  3117. is non-nil. Newlines and tabs in the export text are escaped."
  3118. (ses-check-curcell 'needrange)
  3119. (let ((print-escape-newlines t)
  3120. result item)
  3121. (ses-dorange ses--curcell
  3122. (setq item (if want-formulas
  3123. (ses-cell-formula row col)
  3124. (ses-cell-value row col)))
  3125. (if (eq (car-safe item) 'ses-safe-formula)
  3126. ;;Hide our deferred safety-check marker
  3127. (setq item (cadr item)))
  3128. (if (or (not item) (eq item '*skip*))
  3129. (setq item ""))
  3130. (when (eq (car-safe item) 'quote)
  3131. (push "'" result)
  3132. (setq item (cadr item)))
  3133. (setq item (ses-prin1 item))
  3134. (setq item (replace-regexp-in-string "\t" "\\\\t" item))
  3135. (push item result)
  3136. (cond
  3137. ((< col maxcol)
  3138. (push "\t" result))
  3139. ((< row maxrow)
  3140. (push "\n" result))))
  3141. (setq result (apply #'concat (nreverse result)))
  3142. (kill-new result)))
  3143. ;;----------------------------------------------------------------------------
  3144. ;; Interactive help on symbols
  3145. ;;----------------------------------------------------------------------------
  3146. (defun ses-list-local-printers (&optional local-printer-hashmap)
  3147. "List local printers in a help buffer. Can be called either
  3148. during editing a printer or a formula, or while in the SES
  3149. buffer."
  3150. (interactive
  3151. (list (cond
  3152. ((derived-mode-p 'ses-mode) ses--local-printer-hashmap)
  3153. ((minibufferp) ses--completion-table)
  3154. ((derived-mode-p 'help-mode) nil)
  3155. (t (error "Not in a SES buffer")))))
  3156. (when local-printer-hashmap
  3157. (let ((ses--list-orig-buffer (or ses--list-orig-buffer (current-buffer))))
  3158. (help-setup-xref
  3159. (list (lambda (local-printer-hashmap buffer)
  3160. (let ((ses--list-orig-buffer
  3161. (if (buffer-live-p buffer) buffer)))
  3162. (ses-list-local-printers local-printer-hashmap)))
  3163. local-printer-hashmap ses--list-orig-buffer)
  3164. (called-interactively-p 'interactive))
  3165. (save-excursion
  3166. (with-help-window (help-buffer)
  3167. (if (= 0 (hash-table-count local-printer-hashmap))
  3168. (princ "No local printers defined.")
  3169. (princ "List of local printers definitions:\n")
  3170. (maphash (lambda (key val)
  3171. (princ key)
  3172. (princ " as ")
  3173. (prin1 (ses--locprn-def val))
  3174. (princ "\n"))
  3175. local-printer-hashmap))
  3176. (with-current-buffer standard-output
  3177. (buffer-string)))))))
  3178. (defun ses-list-named-cells (&optional named-cell-hashmap)
  3179. "List named cells in a help buffer. Can be called either
  3180. during editing a printer or a formula, or while in the SES
  3181. buffer."
  3182. (interactive
  3183. (list (cond
  3184. ((derived-mode-p 'ses-mode) ses--named-cell-hashmap)
  3185. ((minibufferp) ses--completion-table)
  3186. ((derived-mode-p 'help-mode) nil)
  3187. (t (error "Not in a SES buffer")))))
  3188. (when named-cell-hashmap
  3189. (let ((ses--list-orig-buffer (or ses--list-orig-buffer (current-buffer))))
  3190. (help-setup-xref
  3191. (list (lambda (named-cell-hashmap buffer)
  3192. (let ((ses--list-orig-buffer
  3193. (if (buffer-live-p buffer) buffer)))
  3194. (ses-list-named-cells named-cell-hashmap)))
  3195. named-cell-hashmap ses--list-orig-buffer)
  3196. (called-interactively-p 'interactive))
  3197. (save-excursion
  3198. (with-help-window (help-buffer)
  3199. (if (= 0 (hash-table-count named-cell-hashmap))
  3200. (princ "No cell was renamed.")
  3201. (princ "List of named cells definitions:\n")
  3202. (maphash (lambda (key val)
  3203. (princ key)
  3204. (princ " for ")
  3205. (prin1 (ses-create-cell-symbol (car val) (cdr val)))
  3206. (princ "\n"))
  3207. named-cell-hashmap))
  3208. (with-current-buffer standard-output
  3209. (buffer-string)))))))
  3210. ;;----------------------------------------------------------------------------
  3211. ;; Other user commands
  3212. ;;----------------------------------------------------------------------------
  3213. (defun ses-unset-header-row ()
  3214. "Select the default header row."
  3215. (interactive)
  3216. (ses-set-header-row 0))
  3217. (defun ses-set-header-row (row)
  3218. "Set the ROW to display in the header-line.
  3219. With a numerical prefix arg, use that row.
  3220. With no prefix arg, use the current row.
  3221. With a \\[universal-argument] prefix arg, prompt the user.
  3222. The top row is row 1. Selecting row 0 displays the default header row."
  3223. (interactive
  3224. (list (if (numberp current-prefix-arg) current-prefix-arg
  3225. (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
  3226. (if current-prefix-arg
  3227. (read-number "Header row: " currow)
  3228. currow)))))
  3229. (if (or (< row 0) (> row ses--numrows))
  3230. (error "Invalid header-row"))
  3231. (ses-begin-change)
  3232. (let ((oldval ses--header-row))
  3233. (let (buffer-undo-list)
  3234. (ses-set-parameter 'ses--header-row row))
  3235. (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
  3236. (ses-reset-header-string))
  3237. (defun ses-mark-row ()
  3238. "Mark the entirety of current row as a range."
  3239. (interactive)
  3240. (ses-check-curcell 'range)
  3241. (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
  3242. (push-mark)
  3243. (ses-goto-print (1+ row) 0)
  3244. (push-mark (point) nil t)
  3245. (ses-goto-print row 0)))
  3246. (defun ses-mark-column ()
  3247. "Mark the entirety of current column as a range."
  3248. (interactive)
  3249. (ses-check-curcell 'range)
  3250. (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
  3251. (row 0))
  3252. (push-mark)
  3253. (ses-goto-print (1- ses--numrows) col)
  3254. (forward-char 1)
  3255. (push-mark (point) nil t)
  3256. (while (eq '*skip* (ses-cell-value row col))
  3257. ;;Skip over initial cells in column that can't be selected
  3258. (setq row (1+ row)))
  3259. (ses-goto-print row col)))
  3260. (defun ses-end-of-line ()
  3261. "Move point to last cell on line."
  3262. (interactive)
  3263. (ses-check-curcell 'end 'range)
  3264. (when ses--curcell ; Otherwise we're at the bottom row, which is empty
  3265. ; anyway.
  3266. (let ((col (1- ses--numcols))
  3267. row rowcol)
  3268. (if (symbolp ses--curcell)
  3269. ;; Single cell.
  3270. (setq row (car (ses-sym-rowcol ses--curcell)))
  3271. ;; Range --- use whichever end of the range the point is at.
  3272. (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
  3273. (car ses--curcell)
  3274. (cdr ses--curcell))))
  3275. ;; If range already includes the last cell in a row, point is actually
  3276. ;; in the following row.
  3277. (if (<= (cdr rowcol) (1- col))
  3278. (setq row (car rowcol))
  3279. (setq row (1+ (car rowcol)))
  3280. (if (= row ses--numrows)
  3281. ;;Already at end - can't go anywhere
  3282. (setq col 0))))
  3283. (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
  3284. (while (eq (ses-cell-value row col) '*skip*)
  3285. ;; Back to beginning of multi-column cell.
  3286. (setq col (1- col)))
  3287. (ses-goto-print row col)))))
  3288. (defun ses-renarrow-buffer ()
  3289. "Narrow the buffer so only the print area is visible.
  3290. Use after \\[widen]."
  3291. (interactive)
  3292. (setq ses--deferred-narrow t))
  3293. (defun ses-sort-column (sorter &optional reverse)
  3294. "Sort the range by a specified column.
  3295. With prefix, sorts in REVERSE order."
  3296. (interactive "*sSort column: \nP")
  3297. (ses-check-curcell 'needrange)
  3298. (let ((min (ses-sym-rowcol (car ses--curcell)))
  3299. (max (ses-sym-rowcol (cdr ses--curcell))))
  3300. (let ((minrow (car min))
  3301. (mincol (cdr min))
  3302. (maxrow (car max))
  3303. (maxcol (cdr max))
  3304. keys extracts end)
  3305. (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
  3306. (or (and sorter (>= sorter mincol) (<= sorter maxcol))
  3307. (error "Invalid sort column"))
  3308. ;;Get key columns and sort them
  3309. (dotimes (x (- maxrow minrow -1))
  3310. (ses-goto-print (+ minrow x) sorter)
  3311. (setq end (next-single-property-change (point) 'cursor-intangible))
  3312. (push (cons (buffer-substring-no-properties (point) end)
  3313. (+ minrow x))
  3314. keys))
  3315. (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
  3316. ;;Extract the lines in reverse sorted order
  3317. (or reverse
  3318. (setq keys (nreverse keys)))
  3319. (dolist (x keys)
  3320. (ses-goto-print (cdr x) (1+ maxcol))
  3321. (setq end (point))
  3322. (ses-goto-print (cdr x) mincol)
  3323. (push (ses-copy-region (point) end) extracts))
  3324. (deactivate-mark)
  3325. ;;Paste the lines sequentially
  3326. (dotimes (x (- maxrow minrow -1))
  3327. (ses-goto-print (+ minrow x) mincol)
  3328. (ses-set-curcell)
  3329. (ses-yank-cells (pop extracts) nil)))))
  3330. (defun ses-sort-column-click (event reverse)
  3331. "Mouse version of `ses-sort-column'."
  3332. (interactive "*e\nP")
  3333. (setq event (event-end event))
  3334. (select-window (posn-window event))
  3335. (setq event (car (posn-col-row event))) ; Click column.
  3336. (let ((col 0))
  3337. (while (and (< col ses--numcols) (> event (ses-col-width col)))
  3338. (setq event (- event (ses-col-width col) 1)
  3339. col (1+ col)))
  3340. (if (>= col ses--numcols)
  3341. (ding)
  3342. (ses-sort-column (ses-column-letter col) reverse))))
  3343. (defun ses-insert-range ()
  3344. "Insert into minibuffer the list of cells currently highlighted in the
  3345. spreadsheet."
  3346. (interactive "*")
  3347. (let (x)
  3348. (with-current-buffer (window-buffer minibuffer-scroll-window)
  3349. (ses-command-hook) ; For ses-coverage.
  3350. (ses-check-curcell 'needrange)
  3351. (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
  3352. ,(cdr ses--curcell))))))
  3353. (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
  3354. (defun ses-insert-ses-range ()
  3355. "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
  3356. highlighted range in the spreadsheet."
  3357. (interactive "*")
  3358. (let (x)
  3359. (with-current-buffer (window-buffer minibuffer-scroll-window)
  3360. (ses-command-hook) ; For ses-coverage.
  3361. (ses-check-curcell 'needrange)
  3362. (setq x (format "(ses-range %S %S)"
  3363. (car ses--curcell)
  3364. (cdr ses--curcell))))
  3365. (insert x)))
  3366. (defun ses-insert-range-click (event)
  3367. "Mouse version of `ses-insert-range'."
  3368. (interactive "*e")
  3369. (mouse-set-point event)
  3370. (ses-insert-range))
  3371. (defun ses-insert-ses-range-click (event)
  3372. "Mouse version of `ses-insert-ses-range'."
  3373. (interactive "*e")
  3374. (mouse-set-point event)
  3375. (ses-insert-ses-range))
  3376. (defun ses-replace-name-in-formula (formula old-name new-name)
  3377. (let ((new-formula formula))
  3378. (cond
  3379. ((eq (car-safe formula) 'quote))
  3380. ((symbolp formula)
  3381. (if (eq formula old-name)
  3382. (setq new-formula new-name)))
  3383. ((consp formula)
  3384. (while formula
  3385. (let ((elt (car-safe formula)))
  3386. (cond
  3387. ((consp elt)
  3388. (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
  3389. ((and (symbolp elt)
  3390. (eq (car-safe formula) old-name))
  3391. (setcar formula new-name))))
  3392. (setq formula (cdr formula)))))
  3393. new-formula))
  3394. (defun ses-rename-cell (new-name &optional cell)
  3395. "Rename current cell."
  3396. (interactive "*SEnter new name: ")
  3397. (or
  3398. (and (local-variable-p new-name)
  3399. (ses-is-cell-sym-p new-name)
  3400. (error "Already a cell name"))
  3401. (and (boundp new-name)
  3402. (null (yes-or-no-p
  3403. (format-message
  3404. "`%S' is already bound outside this buffer, continue? "
  3405. new-name)))
  3406. (error "Already a bound cell name")))
  3407. (let* (curcell
  3408. (sym (if (ses-cell-p cell)
  3409. (ses-cell-symbol cell)
  3410. (setq cell nil
  3411. curcell t)
  3412. (ses-check-curcell)
  3413. ses--curcell))
  3414. (rowcol (ses-sym-rowcol sym))
  3415. (row (car rowcol))
  3416. (col (cdr rowcol))
  3417. new-rowcol old-name old-value)
  3418. (setq cell (or cell (ses-get-cell row col))
  3419. old-name (ses-cell-symbol cell)
  3420. old-value (symbol-value old-name)
  3421. new-rowcol (ses-decode-cell-symbol (symbol-name new-name)))
  3422. ;; when ses-rename-cell is called interactively, then 'sym' is the
  3423. ;; 'cursor-intangible' property of text at cursor position, while
  3424. ;; 'old-name' is the symbol stored in array cell at coordinate
  3425. ;; 'rowcol' corresponding to 'ses-cell' property of symbol
  3426. ;; 'sym'. Both must be the same.
  3427. (unless (eq sym old-name)
  3428. (error "Spreadsheet is broken, both symbols %S and %S refering to cell (%d,%d)" sym old-name row col))
  3429. (if new-rowcol
  3430. ;; the new name is of A1 type, so we test that the coordinate
  3431. ;; inferred from new name
  3432. (if (equal new-rowcol rowcol)
  3433. (put new-name 'ses-cell rowcol)
  3434. (error "Not a valid name for this cell location"))
  3435. (setq ses--named-cell-hashmap
  3436. (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
  3437. (put new-name 'ses-cell :ses-named)
  3438. (puthash new-name rowcol ses--named-cell-hashmap))
  3439. (push `(ses-rename-cell ,old-name ,cell) buffer-undo-list)
  3440. (cl-pushnew rowcol ses--deferred-write :test #'equal)
  3441. ;; Replace name by new name in formula of cells refering to renamed cell.
  3442. (dolist (ref (ses-cell-references cell))
  3443. (let* ((x (ses-sym-rowcol ref))
  3444. (xcell (ses-get-cell (car x) (cdr x))))
  3445. (cl-pushnew x ses--deferred-write :test #'equal)
  3446. (setf (ses-cell-formula xcell)
  3447. (ses-replace-name-in-formula
  3448. (ses-cell-formula xcell)
  3449. old-name
  3450. new-name))))
  3451. ;; Replace name by new name in reference list of cells to which renamed
  3452. ;; cell refers to.
  3453. (dolist (ref (ses-formula-references (ses-cell-formula cell)))
  3454. (let* ((x (ses-sym-rowcol ref))
  3455. (xcell (ses-get-cell (car x) (cdr x))))
  3456. (cl-pushnew x ses--deferred-write :test #'equal)
  3457. (setf (ses-cell-references xcell)
  3458. (cons new-name (delq old-name
  3459. (ses-cell-references xcell))))))
  3460. (set (make-local-variable new-name) (symbol-value sym))
  3461. (setf (ses-cell--symbol cell) new-name)
  3462. ;; set new name to value
  3463. (set new-name old-value)
  3464. ;; Unbind old name
  3465. (if (eq (get old-name 'ses-cell) :ses-named)
  3466. (ses--unbind-cell-name old-name)
  3467. (kill-local-variable old-name))
  3468. (and curcell (setq ses--curcell new-name))
  3469. (save-excursion
  3470. (or curcell (ses-goto-print row col))
  3471. (let* ((pos (point))
  3472. (inhibit-read-only t)
  3473. (end (next-single-property-change pos 'cursor-intangible)))
  3474. (put-text-property pos end 'cursor-intangible new-name)))
  3475. ;; Update the cell name in the mode-line.
  3476. (force-mode-line-update)))
  3477. (defun ses-refresh-local-printer (name _compiled-value) ;FIXME: unused arg?
  3478. "Refresh printout for all cells which use printer NAME.
  3479. NAME should be the name of a locally defined printer.
  3480. Uses the value COMPILED-VALUE for this printer."
  3481. (message "Refreshing cells using printer %S" name)
  3482. (let (new-print)
  3483. (dotimes (row ses--numrows)
  3484. (dotimes (col ses--numcols)
  3485. (let ((cell-printer (ses-cell-printer row col)))
  3486. (when (eq cell-printer name)
  3487. (unless new-print
  3488. (setq new-print t)
  3489. (ses-begin-change))
  3490. (ses-print-cell row col)))))))
  3491. (defun ses-define-local-printer (name definition)
  3492. "Define a local printer with name NAME and definition DEFINITION.
  3493. NAME shall be a symbol. Use TAB to complete over existing local
  3494. printer names.
  3495. DEFINITION shall be either a string formatter, e.g.:
  3496. \"%.2f\" or (\"%.2f\") for left alignment.
  3497. or a lambda expression, e.g. for formatting in ISO format dates
  3498. created with a '(calcFunc-date YEAR MONTH DAY)' formula:
  3499. (lambda (x)
  3500. (cond
  3501. ((null val) \"\")
  3502. ((eq (car-safe x) 'date)
  3503. (let ((calc-format-date '(X YYYY \"-\" MM \"-\" DD)))
  3504. (math-format-date x)))
  3505. (t (ses-center-span val ?# 'ses-prin1))))
  3506. If NAME is already used to name a local printer function, then
  3507. the current definition is proposed as default value, and the
  3508. function is redefined."
  3509. (interactive
  3510. (let (name def already-defined-names)
  3511. (maphash (lambda (key _val) (push (symbol-name key) already-defined-names))
  3512. ses--local-printer-hashmap)
  3513. (setq name (completing-read "Enter printer name: " already-defined-names))
  3514. (when (string= name "")
  3515. (error "Invalid printer name"))
  3516. (setq name (intern name))
  3517. (let* ((cur-printer (gethash name ses--local-printer-hashmap))
  3518. (default (and cur-printer (ses--locprn-def cur-printer))))
  3519. (setq def (ses-read-printer (format "Enter definition of printer %S: " name)
  3520. default)))
  3521. (list name def)))
  3522. (let* ((cur-printer (gethash name ses--local-printer-hashmap))
  3523. (default (and cur-printer (ses--locprn-def cur-printer)))
  3524. create-printer)
  3525. (cond
  3526. ;; cancelled operation => do nothing
  3527. ((eq definition t))
  3528. ;; no change => do nothing
  3529. ((and cur-printer (equal definition default)))
  3530. ;; re-defined printer
  3531. (cur-printer
  3532. (setq create-printer 0)
  3533. (setf (ses--locprn-def cur-printer) definition)
  3534. (ses-refresh-local-printer
  3535. name
  3536. (setf (ses--locprn-compiled cur-printer)
  3537. (ses-local-printer-compile definition))))
  3538. ;; new definition
  3539. (t
  3540. (setq create-printer 1)
  3541. (puthash name
  3542. (setq cur-printer
  3543. (ses-make-local-printer-info definition))
  3544. ses--local-printer-hashmap)))
  3545. (when create-printer
  3546. (let ((printer-def-text
  3547. (concat
  3548. "(ses-local-printer "
  3549. (symbol-name name)
  3550. " "
  3551. (prin1-to-string (ses--locprn-def cur-printer))
  3552. ")")))
  3553. (save-excursion
  3554. (ses-goto-data ses--numrows
  3555. (ses--locprn-number cur-printer))
  3556. (let ((inhibit-read-only t))
  3557. ;; Special undo since it's outside the narrowed buffer.
  3558. (let (buffer-undo-list)
  3559. (if (= create-printer 0)
  3560. (delete-region (point) (line-end-position))
  3561. (insert ?\n)
  3562. (backward-char))
  3563. (insert printer-def-text)
  3564. (when (= create-printer 1)
  3565. (ses-file-format-extend-parameter-list 3)
  3566. (ses-set-parameter 'ses--numlocprn
  3567. (1+ ses--numlocprn))))))))))
  3568. (defsubst ses-define-if-new-local-printer (name def)
  3569. "Same as function `ses-define-if-new-local-printer', except
  3570. that the definition occurs only when the local printer does not
  3571. already exists.
  3572. Function `ses-define-if-new-local-printer' is not interactive; it
  3573. is intended for mode hooks to add local printers automatically."
  3574. (unless (gethash name ses--local-printer-hashmap)
  3575. (ses-define-local-printer name def)))
  3576. ;;----------------------------------------------------------------------------
  3577. ;; Checking formulas for safety
  3578. ;;----------------------------------------------------------------------------
  3579. (defun ses-safe-printer (printer)
  3580. "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
  3581. (if (or (stringp printer)
  3582. (stringp (car-safe printer))
  3583. (not printer)
  3584. (and (symbolp printer) (gethash printer ses--local-printer-hashmap))
  3585. (ses-warn-unsafe printer 'unsafep-function))
  3586. printer
  3587. 'ses-unsafe))
  3588. (defun ses-safe-formula (formula)
  3589. "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
  3590. (if (ses-warn-unsafe formula 'unsafep)
  3591. formula
  3592. `(ses-unsafe ',formula)))
  3593. (defun ses-warn-unsafe (formula checker)
  3594. "Apply CHECKER to FORMULA.
  3595. If result is non-nil, asks user for confirmation about FORMULA,
  3596. which might be unsafe. Returns t if formula is safe or user allows
  3597. execution anyway. Always returns t if `safe-functions' is t."
  3598. (if (eq safe-functions t)
  3599. t
  3600. (setq checker (funcall checker formula))
  3601. (if (not checker)
  3602. t
  3603. (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
  3604. formula checker)))))
  3605. ;;----------------------------------------------------------------------------
  3606. ;; Standard formulas
  3607. ;;----------------------------------------------------------------------------
  3608. (defun ses--clean-! (&rest x)
  3609. "Clean by `delq' list X from any occurrence of nil or `*skip*'."
  3610. (delq nil (delq '*skip* x)))
  3611. (defun ses--clean-_ (x y)
  3612. "Clean list X by replacing by Y any occurrence of nil or `*skip*'.
  3613. This will change X by making `setcar' on its cons cells."
  3614. (let ((ret x) ret-elt)
  3615. (while ret
  3616. (setq ret-elt (car ret))
  3617. (when (memq ret-elt '(nil *skip*))
  3618. (setcar ret y))
  3619. (setq ret (cdr ret))))
  3620. x)
  3621. (defmacro ses-range (from to &rest rest)
  3622. "Expand to a list of cell-symbols for the range going from
  3623. FROM up to TO. The range automatically expands to include any
  3624. new row or column inserted into its middle. The SES library code
  3625. specifically looks for the symbol `ses-range', so don't create an
  3626. alias for this macro!
  3627. By passing in REST some flags one can configure the way the range
  3628. is read and how it is formatted.
  3629. In the sequel we assume that cells A1, B1, A2 B2 have respective values
  3630. 1 2 3 and 4.
  3631. Readout direction is specified by a `>v', `>^', `<v', `<^',
  3632. `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
  3633. of such a flag, a default direction of `^<' is assumed. This
  3634. way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
  3635. while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
  3636. If the range is one row, then `>' can be used as a shorthand to
  3637. `>v' or `>^', and `<' to `<v' or `<^'.
  3638. If the range is one column, then `v' can be used as a shorthand to
  3639. `v>' or `v<', and `^' to `^>' or `v<'.
  3640. A `!' flag will remove all cells whose value is nil or `*skip*'.
  3641. A `_' flag will replace nil or `*skip*' by the value following
  3642. the `_' flag. If the `_' flag is the last argument, then they are
  3643. replaced by integer 0.
  3644. A `*', `*1' or `*2' flag will vectorize the range in the sense of
  3645. Calc. See info node `(Calc) Top'. Flag `*' will output either a
  3646. vector or a matrix depending on the number of rows, `*1' will
  3647. flatten the result to a one row vector, and `*2' will make a
  3648. matrix whatever the number of rows.
  3649. Warning: interaction with Calc is experimental and may produce
  3650. confusing results if you are not aware of Calc data format.
  3651. Use `math-format-value' as a printer for Calc objects."
  3652. (let (result-row
  3653. result
  3654. (prev-row -1)
  3655. (reorient-x nil)
  3656. (reorient-y nil)
  3657. transpose vectorize
  3658. (clean 'list))
  3659. (ses-dorange (cons from to)
  3660. (when (/= prev-row row)
  3661. (push result-row result)
  3662. (setq result-row nil))
  3663. (push (ses-cell-symbol row col) result-row)
  3664. (setq prev-row row))
  3665. (push result-row result)
  3666. (while rest
  3667. (let ((x (pop rest)))
  3668. (pcase x
  3669. (`>v (setq transpose nil reorient-x nil reorient-y nil))
  3670. (`>^ (setq transpose nil reorient-x nil reorient-y t))
  3671. (`<^ (setq transpose nil reorient-x t reorient-y t))
  3672. (`<v (setq transpose nil reorient-x t reorient-y nil))
  3673. (`v> (setq transpose t reorient-x nil reorient-y t))
  3674. (`^> (setq transpose t reorient-x nil reorient-y nil))
  3675. (`^< (setq transpose t reorient-x t reorient-y nil))
  3676. (`v< (setq transpose t reorient-x t reorient-y t))
  3677. ((or `* `*2 `*1) (setq vectorize x))
  3678. (`! (setq clean 'ses--clean-!))
  3679. (`_ (setq clean `(lambda (&rest x)
  3680. (ses--clean-_ x ,(if rest (pop rest) 0)))))
  3681. (_
  3682. (cond
  3683. ; shorthands one row
  3684. ((and (null (cddr result)) (memq x '(> <)))
  3685. (push (intern (concat (symbol-name x) "v")) rest))
  3686. ; shorthands one col
  3687. ((and (null (cdar result)) (memq x '(v ^)))
  3688. (push (intern (concat (symbol-name x) ">")) rest))
  3689. (t (error "Unexpected flag `%S' in ses-range" x)))))))
  3690. (if reorient-y
  3691. (setcdr (last result 2) nil)
  3692. (setq result (cdr (nreverse result))))
  3693. (unless reorient-x
  3694. (setq result (mapcar #'nreverse result)))
  3695. (when transpose
  3696. (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
  3697. (while result
  3698. (setq iter ret)
  3699. (dolist (elt (pop result))
  3700. (setcar iter (cons elt (car iter)))
  3701. (setq iter (cdr iter))))
  3702. (setq result ret)))
  3703. (cl-flet ((vectorize-*1
  3704. (clean result)
  3705. (cons clean (cons (quote 'vec) (apply #'append result))))
  3706. (vectorize-*2
  3707. (clean result)
  3708. (cons clean (cons (quote 'vec)
  3709. (mapcar (lambda (x)
  3710. (cons clean (cons (quote 'vec) x)))
  3711. result)))))
  3712. (pcase vectorize
  3713. (`nil (cons clean (apply #'append result)))
  3714. (`*1 (vectorize-*1 clean result))
  3715. (`*2 (vectorize-*2 clean result))
  3716. (`* (funcall (if (cdr result)
  3717. #'vectorize-*2
  3718. #'vectorize-*1)
  3719. clean result))))))
  3720. (defun ses-delete-blanks (&rest args)
  3721. "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
  3722. (let (result)
  3723. (dolist (cur args)
  3724. (unless (memq cur '(nil *skip*))
  3725. (push cur result)))
  3726. result))
  3727. (defun ses+ (&rest args)
  3728. "Compute the sum of the arguments, ignoring blanks."
  3729. (apply #'+ (apply #'ses-delete-blanks args)))
  3730. (defun ses-average (list)
  3731. "Computes the sum of the numbers in LIST, divided by their length. Blanks
  3732. are ignored. Result is always floating-point, even if all args are integers."
  3733. (setq list (apply #'ses-delete-blanks list))
  3734. (/ (float (apply #'+ list)) (length list)))
  3735. (defmacro ses-select (fromrange test torange)
  3736. "Select cells in FROMRANGE that are `equal' to TEST.
  3737. For each match, return the corresponding cell from TORANGE.
  3738. The ranges are macroexpanded but not evaluated so they should be
  3739. either (ses-range BEG END) or (list ...). The TEST is evaluated."
  3740. (setq fromrange (cdr (macroexpand fromrange))
  3741. torange (cdr (macroexpand torange))
  3742. test (eval test t))
  3743. (or (= (length fromrange) (length torange))
  3744. (error "ses-select: Ranges not same length"))
  3745. (let (result)
  3746. (dolist (x fromrange)
  3747. (if (equal test (symbol-value x))
  3748. (push (car torange) result))
  3749. (setq torange (cdr torange)))
  3750. (cons 'list result)))
  3751. ;;All standard formulas are safe
  3752. (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
  3753. ses-select))
  3754. (put x 'side-effect-free t))
  3755. ;;----------------------------------------------------------------------------
  3756. ;; Standard print functions
  3757. ;;----------------------------------------------------------------------------
  3758. (defun ses-center (value &optional span fill printer)
  3759. "Print VALUE, centered within column.
  3760. FILL is the fill character for centering (default = space).
  3761. SPAN indicates how many additional rightward columns to include
  3762. in width (default = 0).
  3763. PRINTER is the printer to use for printing the value, default is the
  3764. column printer if any, or the spreadsheet the spreadsheet default
  3765. printer otherwise."
  3766. (setq printer (or printer (ses-col-printer ses--col) ses--default-printer))
  3767. (let ((width (ses-col-width ses--col))
  3768. half)
  3769. (or fill (setq fill ?\s))
  3770. (or span (setq span 0))
  3771. (setq value (ses-call-printer printer value))
  3772. (dotimes (x span)
  3773. (setq width (+ width 1 (ses-col-width (+ ses--col span (- x))))))
  3774. ;; Set column width.
  3775. (setq width (- width (string-width value)))
  3776. (if (<= width 0)
  3777. value ; Too large for field, anyway.
  3778. (setq half (make-string (/ width 2) fill))
  3779. (concat half value half
  3780. (if (> (% width 2) 0) (char-to-string fill))))))
  3781. (defun ses-center-span (value &optional fill printer)
  3782. "Print VALUE, centered within the span that starts in the current column
  3783. and continues until the next nonblank column.
  3784. FILL specifies the fill character (default = space)."
  3785. (let ((end (1+ ses--col)))
  3786. (while (and (< end ses--numcols)
  3787. (memq (ses-cell-value ses--row end) '(nil *skip*)))
  3788. (setq end (1+ end)))
  3789. (ses-center value (- end ses--col 1) fill printer)))
  3790. (defun ses-dashfill (value &optional span printer)
  3791. "Print VALUE centered using dashes.
  3792. SPAN indicates how many rightward columns to include in width (default = 0)."
  3793. (ses-center value span ?- printer))
  3794. (defun ses-dashfill-span (value &optional printer)
  3795. "Print VALUE, centered using dashes within the span that starts in the
  3796. current column and continues until the next nonblank column."
  3797. (ses-center-span value ?- printer))
  3798. (defun ses-tildefill-span (value &optional printer)
  3799. "Print VALUE, centered using tildes within the span that starts in the
  3800. current column and continues until the next nonblank column."
  3801. (ses-center-span value ?~ printer))
  3802. (defun ses-prin1 (value)
  3803. "Shorthand for '(prin1-to-string VALUE t)'.
  3804. Useful to handle the default behavior in custom lambda based
  3805. printer functions."
  3806. (prin1-to-string value t))
  3807. (defun ses-unsafe (_value)
  3808. "Substitute for an unsafe formula or printer."
  3809. (error "Unsafe formula or printer"))
  3810. ;;All standard printers are safe, including ses-unsafe!
  3811. (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
  3812. (put x 'side-effect-free t))
  3813. (defun ses-unload-function ()
  3814. "Unload the Simple Emacs Spreadsheet."
  3815. (advice-remove 'yank #'ses--advice-yank)
  3816. (advice-remove 'copy-region-as-kill #'ses--advice-copy-region-as-kill)
  3817. ;; Continue standard unloading.
  3818. nil)
  3819. (provide 'ses)
  3820. ;;; ses.el ends here