ses.el 126 KB

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