ses.el 148 KB

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