ses.el 129 KB

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