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