(fortran-abbrev-start): Only offer help if abbrev-mode is active.
[emacs.git] / lisp / ses.el
blob8e006ace97dce9f2e764fe480db4e08c9438979d
1 ;;;; ses.el -- Simple Emacs Spreadsheet
3 ;; Copyright (C) 2002 Free Software Foundation, Inc.
5 ;; Author: Jonathan Yavner <jyavner@engineer.com>
6 ;; Maintainer: Jonathan Yavner <jyavner@engineer.com>
7 ;; Keywords: spreadsheet
9 ;; This file is part of GNU Emacs.
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.
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.
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.
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.
37 (require 'unsafep)
40 ;;;----------------------------------------------------------------------------
41 ;;;; User-customizable variables
42 ;;;----------------------------------------------------------------------------
44 (defgroup ses nil
45 "Simple Emacs Spreadsheet"
46 :group 'applications
47 :prefix "ses-"
48 :version "21.1")
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")))
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))))
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))
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))
74 (defcustom ses-mode-hook nil
75 "Hook functions to be run upon entering SES mode."
76 :group 'ses
77 :type 'hook)
80 ;;;----------------------------------------------------------------------------
81 ;;;; Global variables and constants
82 ;;;----------------------------------------------------------------------------
84 (defvar ses-read-cell-history nil
85 "List of formulas that have been typed in.")
87 (defvar ses-read-printer-history nil
88 "List of printer functions that have been typed in.")
90 (defvar ses-mode-map nil
91 "Local keymap for Simple Emacs Spreadsheet.")
93 (defvar ses-mode-print-map nil
94 "Local keymap for SES print area.")
96 (defvar ses-mode-edit-map nil
97 "Local keymap for SES minibuffer cell-editing.")
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))
106 (defconst ses-print-data-boundary "\n\014\n"
107 "Marker string denoting the boundary between print area and data area")
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")
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.")
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.")
130 (defconst ses-cell-size 4
131 "A cell consists of a SYMBOL, a FORMULA, a PRINTER-function, and a list of
132 REFERENCES.")
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.")
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.")
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.")
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."))
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)))
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).
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.")
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.")
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.")
192 ;;;----------------------------------------------------------------------------
193 ;;;; Macros
194 ;;;----------------------------------------------------------------------------
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))
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))
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))
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))
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))
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)))
221 (defmacro ses-col-width (col)
222 "Return the width for column COL."
223 `(aref column-widths ,col))
225 (defmacro ses-col-printer (col)
226 "Return the default printer for column COL."
227 `(aref col-printers ,col))
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)))
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)
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"))
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)
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)
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)
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))))
310 (put 'ses-dotimes-msg 'lisp-indent-function 2)
311 (def-edebug-spec ses-dotimes-msg ((symbolp form) form body))
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))))))
338 (put 'ses-dorange 'lisp-indent-function 'defun)
339 (def-edebug-spec ses-dorange (form body))
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)
351 ;;;----------------------------------------------------------------------------
352 ;;;; Utility functions
353 ;;;----------------------------------------------------------------------------
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))
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))
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))))
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)
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))))
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))))))
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)))))
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)))))
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)))))
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))
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))
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)
466 ;;;----------------------------------------------------------------------------
467 ;;;; The cells
468 ;;;----------------------------------------------------------------------------
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
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))))
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)))
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))
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)))
613 ;;;----------------------------------------------------------------------------
614 ;;;; The print area
615 ;;;----------------------------------------------------------------------------
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))))))
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)
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"))))
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) ?#)))
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; otherwise fill with error indicator
724 (setq sig `(error "Too wide" ,text))
725 (if (stringp value)
726 (setq text (substring text 0 maxwidth))
727 (setq text (make-string maxwidth ?#))))))))
728 ;;Substitute question marks for tabs and newlines. Newlines are
729 ;;used as row-separators; tabs could confuse the reimport logic.
730 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
731 (ses-goto-print row col)
732 (setq startpos (point))
733 ;;Install the printed result. This is not interruptible.
734 (let ((inhibit-read-only t)
735 (inhibit-quit t))
736 (delete-char (1+ (length text)))
737 ;;We use concat instead of inserting separate strings in order to
738 ;;reduce the number of cells in the undo list.
739 (setq x (concat text (if (< maxcol numcols) " " "\n")))
740 ;;We use set-text-properties to prevent a wacky print function
741 ;;from inserting rogue properties, and to ensure that the keymap
742 ;;property is inherited (is it a bug that only unpropertied strings
743 ;;actually inherit from surrounding text?)
744 (set-text-properties 0 (length x) nil x)
745 (insert-and-inherit x)
746 (put-text-property startpos (point) 'intangible
747 (ses-cell-symbol cell))
748 (when (and (zerop row) (zerop col))
749 ;;Reconstruct special beginning-of-buffer attributes
750 (put-text-property 1 (point) 'keymap 'ses-mode-print-map)
751 (put-text-property 1 (point) 'read-only 'ses)
752 (put-text-property 1 2 'front-sticky t)))
753 (if (= row (1- header-row))
754 ;;This line is part of the header - force recalc
755 (ses-reset-header-string))
756 ;;If this cell (or a preceding one on the line) previously spilled over
757 ;;and has gotten shorter, redraw following cells on line recursively.
758 (when (and (< maxcol numcols) (eq (ses-cell-value row maxcol) '*skip*))
759 (ses-set-cell row maxcol 'value nil)
760 (ses-print-cell row maxcol))
761 ;;Return to start of cell
762 (goto-char startpos)
763 sig)))
765 (defun ses-call-printer (printer &optional value)
766 "Invokes PRINTER (a string or parenthesized string or function-symbol or
767 lambda of one argument) on VALUE. Result is the the printed cell as a
768 string. The variable `ses-call-printer-return' is set to t if the printer
769 used parenthesis to request left-justification, or the error-signal if the
770 printer signalled one (and \"%s\" is used as the default printer), else nil."
771 (setq ses-call-printer-return nil)
772 (unless value
773 (setq value ""))
774 (condition-case signal
775 (cond
776 ((stringp printer)
777 (format printer value))
778 ((stringp (car-safe printer))
779 (setq ses-call-printer-return t)
780 (format (car printer) value))
782 (setq value (funcall printer value))
783 (if (stringp value)
784 value
785 (or (stringp (car-safe value))
786 (error "Printer should return \"string\" or (\"string\")"))
787 (setq ses-call-printer-return t)
788 (car value))))
789 (error
790 (setq ses-call-printer-return signal)
791 (prin1-to-string value t))))
793 (defun ses-adjust-print-width (col change)
794 "Insert CHANGE spaces in front of column COL, or at end of line if
795 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
796 inhibit-quit to t."
797 (let ((inhibit-read-only t)
798 (blank (if (> change 0) (make-string change ? )))
799 (at-end (= col numcols)))
800 (ses-set-with-undo 'linewidth (+ linewidth change))
801 ;;ses-set-with-undo always returns t for strings.
802 (1value (ses-set-with-undo 'blank-line
803 (concat (make-string linewidth ? ) "\n")))
804 (dotimes (row numrows)
805 (ses-goto-print row col)
806 (when at-end
807 ;;Insert new columns before newline
808 (let ((inhibit-point-motion-hooks t))
809 (backward-char 1)))
810 (if blank
811 (insert blank)
812 (delete-char (- change))))))
814 (defun ses-print-cell-new-width (row col)
815 "Same as ses-print-cell, except if the cell's value is *skip*, the preceding
816 nonskipped cell is reprinted. This function is used when the width of
817 cell (ROW,COL) has changed."
818 (if (not (eq (ses-cell-value row col) '*skip*))
819 (ses-print-cell row col)
820 ;;Cell was skipped over - reprint previous
821 (ses-goto-print row col)
822 (backward-char 1)
823 (let ((rowcol (ses-sym-rowcol (get-text-property (point) 'intangible))))
824 (ses-print-cell (car rowcol) (cdr rowcol)))))
827 ;;;----------------------------------------------------------------------------
828 ;;;; The data area
829 ;;;----------------------------------------------------------------------------
831 (defun ses-goto-data (def &optional col)
832 "Move point to data area for (DEF,COL). If DEF is a row number, COL is the
833 column number for a data cell -- otherwise DEF is one of the symbols
834 column-widths, col-printers, default-printer, numrows, or numcols."
835 (if (< (point-max) (buffer-size))
836 (setq deferred-narrow t))
837 (widen)
838 (let ((inhibit-point-motion-hooks t)) ;In case intangible attrs are wrong
839 (goto-char 1)
840 (if col
841 ;;It's a cell
842 (forward-line (+ numrows 2 (* def (1+ numcols)) col))
843 ;;Convert def-symbol to offset
844 (setq def (plist-get ses-paramlines-plist def))
845 (or def (signal 'args-out-of-range nil))
846 (forward-line (+ (* numrows (+ numcols 2)) def)))))
848 (defun ses-set-parameter (def value &optional elem)
849 "Sets parameter DEF to VALUE (with undo) and writes the value to the data
850 area. See `ses-goto-data' for meaning of DEF. Newlines in the data
851 are escaped. If ELEM is specified, it is the array subscript within DEF to
852 be set to VALUE."
853 (save-excursion
854 ;;We call ses-goto-data early, using the old values of numrows and
855 ;;numcols in case one of them is being changed.
856 (ses-goto-data def)
857 (if elem
858 (ses-aset-with-undo (symbol-value def) elem value)
859 (ses-set-with-undo def value))
860 (let ((inhibit-read-only t)
861 (fmt (plist-get '(column-widths "(ses-column-widths %S)"
862 col-printers "(ses-column-printers %S)"
863 default-printer "(ses-default-printer %S)"
864 header-row "(ses-header-row %S)"
865 file-format " %S ;SES file-format"
866 numrows " %S ;numrows"
867 numcols " %S ;numcols")
868 def)))
869 (delete-region (point) (line-end-position))
870 (insert (format fmt (symbol-value def))))))
872 (defun ses-write-cells ()
873 "`deferred-write' is a list of (ROW,COL) for cells to be written from
874 buffer-local variables to data area. Newlines in the data are escaped."
875 (let* ((inhibit-read-only t)
876 (print-escape-newlines t)
877 rowcol row col cell sym formula printer text)
878 (setq ses-start-time (float-time))
879 (with-temp-message " "
880 (save-excursion
881 (while deferred-write
882 (ses-time-check "Writing... (%d cells left)"
883 '(length deferred-write))
884 (setq rowcol (pop deferred-write)
885 row (car rowcol)
886 col (cdr rowcol)
887 cell (ses-get-cell row col)
888 sym (ses-cell-symbol cell)
889 formula (ses-cell-formula cell)
890 printer (ses-cell-printer cell))
891 (if (eq (car-safe formula) 'ses-safe-formula)
892 (setq formula (cadr formula)))
893 (if (eq (car-safe printer) 'ses-safe-printer)
894 (setq printer (cadr printer)))
895 ;;This is noticably faster than (format "%S %S %S %S %S")
896 (setq text (concat "(ses-cell "
897 (symbol-name sym)
899 (prin1-to-string (symbol-value sym))
901 (prin1-to-string formula)
903 (prin1-to-string printer)
905 (if (atom (ses-cell-references cell))
906 "nil"
907 (concat "("
908 (mapconcat 'symbol-name
909 (ses-cell-references cell)
910 " ")
911 ")"))
912 ")"))
913 (ses-goto-data row col)
914 (delete-region (point) (line-end-position))
915 (insert text)))
916 (message " "))))
919 ;;;----------------------------------------------------------------------------
920 ;;;; Formula relocation
921 ;;;----------------------------------------------------------------------------
923 (defun ses-formula-references (formula &optional result-so-far)
924 "Produce a list of symbols for cells that this formula's value
925 refers to. For recursive calls, RESULT-SO-FAR is the list being constructed,
926 or t to get a wrong-type-argument error when the first reference is found."
927 (if (atom formula)
928 (if (ses-sym-rowcol formula)
929 ;;Entire formula is one symbol
930 (add-to-list 'result-so-far formula)
931 ) ;;Ignore other atoms
932 (dolist (cur formula)
933 (cond
934 ((ses-sym-rowcol cur)
935 ;;Save this reference
936 (add-to-list 'result-so-far cur))
937 ((eq (car-safe cur) 'ses-range)
938 ;;All symbols in range are referenced
939 (dolist (x (cdr (macroexpand cur)))
940 (add-to-list 'result-so-far x)))
941 ((and (consp cur) (not (eq (car cur) 'quote)))
942 ;;Recursive call for subformulas
943 (setq result-so-far (ses-formula-references cur result-so-far)))
945 ;;Ignore other stuff
946 ))))
947 result-so-far)
949 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
950 "Produce a copy of FORMULA where all symbols that refer to cells in row
951 STARTROW or above and col STARTCOL or above are altered by adding ROWINCR
952 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
953 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
954 => (+ A1 B2 C4)
955 If ROWINCR or COLINCR is negative, references to cells being deleted are
956 removed. Example:
957 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
958 => (+ A1 C3)
959 Sets `ses-relocate-return' to 'delete if cell-references were removed."
960 (let (rowcol result)
961 (if (or (atom formula) (eq (car formula) 'quote))
962 (if (setq rowcol (ses-sym-rowcol formula))
963 (ses-relocate-symbol formula rowcol
964 startrow startcol rowincr colincr)
965 formula) ;Pass through as-is
966 (dolist (cur formula)
967 (setq rowcol (ses-sym-rowcol cur))
968 (cond
969 (rowcol
970 (setq cur (ses-relocate-symbol cur rowcol
971 startrow startcol rowincr colincr))
972 (if cur
973 (push cur result)
974 ;;Reference to a deleted cell. Set a flag in ses-relocate-return.
975 ;;don't change the flag if it's already 'range, since range
976 ;;implies 'delete.
977 (unless ses-relocate-return
978 (setq ses-relocate-return 'delete))))
979 ((eq (car-safe cur) 'ses-range)
980 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
981 (if cur
982 (push cur result)))
983 ((or (atom cur) (eq (car cur) 'quote))
984 ;;Constants pass through unchanged
985 (push cur result))
987 ;;Recursively copy and alter subformulas
988 (push (ses-relocate-formula cur startrow startcol
989 rowincr colincr)
990 result))))
991 (nreverse result))))
993 (defun ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
994 "Relocate one symbol SYM, whichs corresponds to ROWCOL (a cons of ROW and
995 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
996 by (ROWINCR,COLINCR)."
997 (let ((row (car rowcol))
998 (col (cdr rowcol)))
999 (if (or (< row startrow) (< col startcol))
1001 (setq row (+ row rowincr)
1002 col (+ col colincr))
1003 (if (and (>= row startrow) (>= col startcol)
1004 (< row numrows) (< col numcols))
1005 ;;Relocate this variable
1006 (ses-create-cell-symbol row col)
1007 ;;Delete reference to a deleted cell
1008 nil))))
1010 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1011 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1012 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1013 new range, or nil if the entire range is deleted. If new rows are being added
1014 just beyond the end of a row range, or new columns just beyond a column range,
1015 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1016 if the range was altered."
1017 (let* ((minorig (cadr range))
1018 (minrowcol (ses-sym-rowcol minorig))
1019 (min (ses-relocate-symbol minorig minrowcol
1020 startrow startcol
1021 rowincr colincr))
1022 (maxorig (nth 2 range))
1023 (maxrowcol (ses-sym-rowcol maxorig))
1024 (max (ses-relocate-symbol maxorig maxrowcol
1025 startrow startcol
1026 rowincr colincr))
1027 field)
1028 (cond
1029 ((and (not min) (not max))
1030 (setq range nil)) ;;The entire range is deleted
1031 ((zerop colincr)
1032 ;;Inserting or deleting rows
1033 (setq field 'car)
1034 (if (not min)
1035 ;;Chopped off beginning of range
1036 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1037 ses-relocate-return 'range))
1038 (if (not max)
1039 (if (> rowincr 0)
1040 ;;Trying to insert a nonexistent row
1041 (setq max (ses-create-cell-symbol (1- numrows) (cdr minrowcol)))
1042 ;;End of range is being deleted
1043 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1044 ses-relocate-return 'range))
1045 (and (> rowincr 0)
1046 (= (car maxrowcol) (1- startrow))
1047 (= (cdr minrowcol) (cdr maxrowcol))
1048 ;;Insert after ending row of vertical range - include it
1049 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1050 (cdr maxrowcol))))))
1052 ;;Inserting or deleting columns
1053 (setq field 'cdr)
1054 (if (not min)
1055 ;;Chopped off beginning of range
1056 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1057 ses-relocate-return 'range))
1058 (if (not max)
1059 (if (> colincr 0)
1060 ;;Trying to insert a nonexistent column
1061 (setq max (ses-create-cell-symbol (car maxrowcol) (1- numcols)))
1062 ;;End of range is being deleted
1063 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1064 ses-relocate-return 'range))
1065 (and (> colincr 0)
1066 (= (cdr maxrowcol) (1- startcol))
1067 (= (car minrowcol) (car maxrowcol))
1068 ;;Insert after ending column of horizontal range - include it
1069 (setq max (ses-create-cell-symbol (car maxrowcol)
1070 (+ startcol colincr -1)))))))
1071 (when range
1072 (if (/= (- (funcall field maxrowcol)
1073 (funcall field minrowcol))
1074 (- (funcall field (ses-sym-rowcol max))
1075 (funcall field (ses-sym-rowcol min))))
1076 ;;This range has changed size
1077 (setq ses-relocate-return 'range))
1078 (list 'ses-range min max))))
1080 (defun ses-relocate-all (minrow mincol rowincr colincr)
1081 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1082 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1083 to each symbol."
1084 (let (reform)
1085 (let (mycell newval)
1086 (ses-dotimes-msg (row numrows) "Relocating formulas..."
1087 (dotimes (col numcols)
1088 (setq ses-relocate-return nil
1089 mycell (ses-get-cell row col)
1090 newval (ses-relocate-formula (ses-cell-formula mycell)
1091 minrow mincol rowincr colincr))
1092 (ses-set-cell row col 'formula newval)
1093 (if (eq ses-relocate-return 'range)
1094 ;;This cell contains a (ses-range X Y) where a cell has been
1095 ;;inserted or deleted in the middle of the range.
1096 (push (cons row col) reform))
1097 (if ses-relocate-return
1098 ;;This cell referred to a cell that's been deleted or is no
1099 ;;longer part of the range. We can't fix that now because
1100 ;;reference lists cells have been partially updated.
1101 (add-to-list 'deferred-recalc
1102 (ses-create-cell-symbol row col)))
1103 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1104 minrow mincol rowincr colincr))
1105 (ses-set-cell row col 'references newval)
1106 (and (>= row minrow) (>= col mincol)
1107 (ses-set-cell row col 'symbol
1108 (ses-create-cell-symbol row col))))))
1109 ;;Relocate the cell values
1110 (let (oldval myrow mycol xrow xcol)
1111 (cond
1112 ((and (<= rowincr 0) (<= colincr 0))
1113 ;;Deletion of rows and/or columns
1114 (ses-dotimes-msg (row (- numrows minrow)) "Relocating variables..."
1115 (setq myrow (+ row minrow))
1116 (dotimes (col (- numcols mincol))
1117 (setq mycol (+ col mincol)
1118 xrow (- myrow rowincr)
1119 xcol (- mycol colincr))
1120 (if (and (< xrow numrows) (< xcol numcols))
1121 (setq oldval (ses-cell-value xrow xcol))
1122 ;;Cell is off the end of the array
1123 (setq oldval (symbol-value (ses-create-cell-symbol xrow xcol))))
1124 (ses-set-cell myrow mycol 'value oldval))))
1125 ((and (wholenump rowincr) (wholenump colincr))
1126 ;;Insertion of rows and/or columns. Run the loop backwards.
1127 (let ((disty (1- numrows))
1128 (distx (1- numcols))
1129 myrow mycol)
1130 (ses-dotimes-msg (row (- numrows minrow)) "Relocating variables..."
1131 (setq myrow (- disty row))
1132 (dotimes (col (- numcols mincol))
1133 (setq mycol (- distx col)
1134 xrow (- myrow rowincr)
1135 xcol (- mycol colincr))
1136 (if (or (< xrow minrow) (< xcol mincol))
1137 ;;Newly-inserted value
1138 (setq oldval nil)
1139 ;;Transfer old value
1140 (setq oldval (ses-cell-value xrow xcol)))
1141 (ses-set-cell myrow mycol 'value oldval)))
1142 t)) ;Make testcover happy by returning non-nil here
1144 (error "ROWINCR and COLINCR must have the same sign"))))
1145 ;;Reconstruct reference lists for cells that contain ses-ranges that
1146 ;;have changed size.
1147 (when reform
1148 (message "Fixing ses-ranges...")
1149 (let (row col)
1150 (setq ses-start-time (float-time))
1151 (while reform
1152 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1153 (setq row (caar reform)
1154 col (cdar reform)
1155 reform (cdr reform))
1156 (ses-cell-set-formula row col (ses-cell-formula row col))))
1157 (message nil))))
1160 ;;;----------------------------------------------------------------------------
1161 ;;;; Undo control
1162 ;;;----------------------------------------------------------------------------
1164 (defadvice undo-more (around ses-undo-more activate preactivate)
1165 "Define a meaning for conses in buffer-undo-list whose car is a symbol
1166 other than t or nil. To undo these, apply the car--a function--to the
1167 cdr--its arglist."
1168 (let ((ses-count (ad-get-arg 0)))
1169 (catch 'undo
1170 (dolist (ses-x pending-undo-list)
1171 (unless ses-x
1172 ;;End of undo boundary
1173 (setq ses-count (1- ses-count))
1174 (if (<= ses-count 0)
1175 ;;We've seen enough boundaries - stop undoing
1176 (throw 'undo nil)))
1177 (and (consp ses-x) (symbolp (car ses-x)) (fboundp (car ses-x))
1178 ;;Undo using apply
1179 (apply (car ses-x) (cdr ses-x)))))
1180 (if (not (eq major-mode 'ses-mode))
1181 ad-do-it
1182 ;;Here is some extra code for SES mode.
1183 (setq deferred-narrow (or deferred-narrow (< (point-max) (buffer-size))))
1184 (widen)
1185 (condition-case x
1186 ad-do-it
1187 (error
1188 ;;Restore narrow if appropriate
1189 (ses-command-hook)
1190 (signal (car x) (cdr x)))))))
1192 (defun ses-begin-change ()
1193 "For undo, remember current buffer-position before we start changing hidden
1194 stuff."
1195 (let ((inhibit-read-only t))
1196 (insert-and-inherit "X")
1197 (delete-region (1- (point)) (point))))
1199 (defun ses-set-with-undo (sym newval)
1200 "Like set, but undoable. Result is t if value has changed."
1201 ;;We avoid adding redundant entries to the undo list, but this is
1202 ;;unavoidable for strings because equal ignores text properties and there's
1203 ;;no easy way to get the whole property list to see if it's different!
1204 (unless (and (boundp sym)
1205 (equal (symbol-value sym) newval)
1206 (not (stringp newval)))
1207 (push (if (boundp sym)
1208 `(ses-set-with-undo ,sym ,(symbol-value sym))
1209 `(ses-unset-with-undo ,sym))
1210 buffer-undo-list)
1211 (set sym newval)
1214 (defun ses-unset-with-undo (sym)
1215 "Set SYM to be unbound. This is undoable."
1216 (when (1value (boundp sym)) ;;Always bound, except after a programming error
1217 (push `(ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
1218 (makunbound sym)))
1220 (defun ses-aset-with-undo (array idx newval)
1221 "Like aset, but undoable. Result is t if element has changed"
1222 (unless (equal (aref array idx) newval)
1223 (push `(ses-aset-with-undo ,array ,idx ,(aref array idx)) buffer-undo-list)
1224 (aset array idx newval)
1228 ;;;----------------------------------------------------------------------------
1229 ;;;; Startup for major mode
1230 ;;;----------------------------------------------------------------------------
1232 (defun ses-build-mode-map ()
1233 "Set up `ses-mode-map', `ses-mode-print-map', and `ses-mode-edit-map' with
1234 standard keymap bindings for SES."
1235 (message "Building mode map...")
1236 ;;;Define ses-mode-map
1237 (let ((keys '("\C-c\M-\C-l" ses-reconstruct-all
1238 "\C-c\C-l" ses-recalculate-all
1239 "\C-c\C-n" ses-renarrow-buffer
1240 "\C-c\C-c" ses-recalculate-cell
1241 "\C-c\M-\C-s" ses-sort-column
1242 "\C-c\M-\C-h" ses-read-header-row
1243 "\C-c\C-t" ses-truncate-cell
1244 "\C-c\C-j" ses-jump
1245 "\C-c\C-p" ses-read-default-printer
1246 "\M-\C-l" ses-reprint-all
1247 [?\S-\C-l] ses-reprint-all
1248 [header-line mouse-2] ses-sort-column-click))
1249 (newmap (make-sparse-keymap)))
1250 (while keys
1251 (define-key (1value newmap) (car keys) (cadr keys))
1252 (setq keys (cddr keys)))
1253 (setq ses-mode-map (1value newmap)))
1254 ;;;Define ses-mode-print-map
1255 (let ((keys '(;;At least three ways to define shift-tab--and some PC systems
1256 ;;won't generate it at all!
1257 [S-tab] backward-char
1258 [backtab] backward-char
1259 [S-iso-backtab] backward-char
1260 [S-iso-lefttab] backward-char
1261 [tab] ses-forward-or-insert
1262 "\C-i" ses-forward-or-insert ;Needed for ses-coverage.el?
1263 "\M-o" ses-insert-column
1264 "\C-o" ses-insert-row
1265 "\C-m" ses-edit-cell
1266 "\M-k" ses-delete-column
1267 "\M-y" ses-yank-pop
1268 "\C-k" ses-delete-row
1269 "\C-j" ses-append-row-jump-first-column
1270 "\M-h" ses-mark-row
1271 "\M-H" ses-mark-column
1272 "\C-d" ses-clear-cell-forward
1273 "\C-?" ses-clear-cell-backward
1274 "(" ses-read-cell
1275 "\"" ses-read-cell
1276 "'" ses-read-symbol
1277 "=" ses-edit-cell
1278 "j" ses-jump
1279 "p" ses-read-cell-printer
1280 "w" ses-set-column-width
1281 "x" ses-export-keymap
1282 "\M-p" ses-read-column-printer))
1283 (repl '(;;We'll replace these wherever they appear in the keymap
1284 clipboard-kill-region ses-kill-override
1285 end-of-line ses-end-of-line
1286 kill-line ses-delete-row
1287 kill-region ses-kill-override
1288 open-line ses-insert-row))
1289 (numeric "0123456789.-")
1290 (newmap (make-keymap)))
1291 ;;Get rid of printables
1292 (suppress-keymap (1value newmap) t)
1293 ;;These keys insert themselves as the beginning of a numeric value
1294 (dotimes (x (length (1value numeric)))
1295 (define-key (1value newmap)
1296 (substring (1value numeric) x (1+ x))
1297 'ses-read-cell))
1298 ;;Override these global functions wherever they're bound
1299 (while repl
1300 (substitute-key-definition (car repl) (cadr repl)
1301 (1value newmap)
1302 (current-global-map))
1303 (setq repl (cddr repl)))
1304 ;;Apparently substitute-key-definition doesn't catch this?
1305 (define-key (1value newmap) [(menu-bar) edit cut] 'ses-kill-override)
1306 ;;Define our other local keys
1307 (while keys
1308 (define-key (1value newmap) (car keys) (cadr keys))
1309 (setq keys (cddr keys)))
1310 ;;Keymap property wants the map as a function, not a variable
1311 (fset 'ses-mode-print-map (1value newmap))
1312 (setq ses-mode-print-map (1value newmap)))
1313 ;;;Define ses-mode-edit-map
1314 (let ((keys '("\C-c\C-r" ses-insert-range
1315 "\C-c\C-s" ses-insert-ses-range
1316 [S-mouse-3] ses-insert-range-click
1317 [C-S-mouse-3] ses-insert-ses-range-click
1318 "\M-\C-i" lisp-complete-symbol))
1319 (newmap (make-sparse-keymap)))
1320 (1value (set-keymap-parent (1value newmap) (1value minibuffer-local-map)))
1321 (while keys
1322 (define-key (1value newmap) (car keys) (cadr keys))
1323 (setq keys (cddr keys)))
1324 (setq ses-mode-edit-map (1value newmap)))
1325 (message nil))
1327 (defun ses-load ()
1328 "Parse the current buffer and sets up buffer-local variables. Does not
1329 execute cell formulas or print functions."
1330 (widen)
1331 ;;Read our global parameters, which should be a 3-element list
1332 (goto-char (point-max))
1333 (search-backward ";;; Local Variables:\n" nil t)
1334 (backward-list 1)
1335 (let ((params (condition-case nil (read (current-buffer)) (error nil)))
1336 sym)
1337 (or (and (= (safe-length params) 3)
1338 (numberp (car params))
1339 (numberp (cadr params))
1340 (> (cadr params) 0)
1341 (numberp (nth 2 params))
1342 (> (nth 2 params) 0))
1343 (error "Invalid SES file"))
1344 (setq file-format (car params)
1345 numrows (cadr params)
1346 numcols (nth 2 params))
1347 (when (= file-format 1)
1348 (let (buffer-undo-list) ;This is not undoable
1349 (ses-goto-data 'header-row)
1350 (insert "(ses-header-row 0)\n")
1351 (ses-set-parameter 'file-format 2)
1352 (message "Upgrading from SES-1 file format")))
1353 (or (= file-format 2)
1354 (error "This file needs a newer version of the SES library code."))
1355 (ses-create-cell-variable-range 0 (1- numrows) 0 (1- numcols))
1356 ;;Initialize cell array
1357 (setq cells (make-vector numrows nil))
1358 (dotimes (row numrows)
1359 (aset cells row (make-vector numcols nil))))
1360 ;;Skip over print area, which we assume is correct
1361 (goto-char 1)
1362 (forward-line numrows)
1363 (or (looking-at ses-print-data-boundary)
1364 (error "Missing marker between print and data areas"))
1365 (forward-char (length ses-print-data-boundary))
1366 ;;Initialize printer and symbol lists
1367 (mapc 'ses-printer-record ses-standard-printer-functions)
1368 (setq symbolic-formulas nil)
1369 ;;Load cell definitions
1370 (dotimes (row numrows)
1371 (dotimes (col numcols)
1372 (let* ((x (read (current-buffer)))
1373 (rowcol (ses-sym-rowcol (car-safe (cdr-safe x)))))
1374 (or (and (looking-at "\n")
1375 (eq (car-safe x) 'ses-cell)
1376 (eq row (car rowcol))
1377 (eq col (cdr rowcol)))
1378 (error "Cell-def error"))
1379 (eval x)))
1380 (or (looking-at "\n\n")
1381 (error "Missing blank line between rows")))
1382 ;;Load global parameters
1383 (let ((widths (read (current-buffer)))
1384 (n1 (char-after (point)))
1385 (printers (read (current-buffer)))
1386 (n2 (char-after (point)))
1387 (def-printer (read (current-buffer)))
1388 (n3 (char-after (point)))
1389 (head-row (read (current-buffer)))
1390 (n4 (char-after (point))))
1391 (or (and (eq (car-safe widths) 'ses-column-widths)
1392 (= n1 ?\n)
1393 (eq (car-safe printers) 'ses-column-printers)
1394 (= n2 ?\n)
1395 (eq (car-safe def-printer) 'ses-default-printer)
1396 (= n3 ?\n)
1397 (eq (car-safe head-row) 'ses-header-row)
1398 (= n4 ?\n))
1399 (error "Invalid SES global parameters"))
1400 (1value (eval widths))
1401 (1value (eval def-printer))
1402 (1value (eval printers))
1403 (1value (eval head-row)))
1404 ;;Should be back at global-params
1405 (forward-char 1)
1406 (or (looking-at (replace-regexp-in-string "1" "[0-9]+"
1407 ses-initial-global-parameters))
1408 (error "Problem with column-defs or global-params"))
1409 ;;Check for overall newline count in definitions area
1410 (forward-line 3)
1411 (let ((start (point)))
1412 (ses-goto-data 'numrows)
1413 (or (= (point) start)
1414 (error "Extraneous newlines someplace?"))))
1416 (defun ses-setup ()
1417 "Set up for display of only the printed cell values.
1419 Narrows the buffer to show only the print area. Gives it `read-only' and
1420 `intangible' properties. Sets up highlighting for current cell."
1421 (interactive)
1422 (let ((end 1)
1423 (inhibit-read-only t)
1424 (was-modified (buffer-modified-p))
1425 pos sym)
1426 (ses-goto-data 0 0) ;;Include marker between print-area and data-area
1427 (set-text-properties (point) (buffer-size) nil) ;Delete garbage props
1428 (mapc 'delete-overlay (overlays-in 1 (buffer-size)))
1429 ;;The print area is read-only (except for our special commands) and uses a
1430 ;;special keymap.
1431 (put-text-property 1 (1- (point)) 'read-only 'ses)
1432 (put-text-property 1 (1- (point)) 'keymap 'ses-mode-print-map)
1433 ;;For the beginning of the buffer, we want the read-only and keymap
1434 ;;attributes to be inherited from the first character
1435 (put-text-property 1 2 'front-sticky t)
1436 ;;Create intangible properties, which also indicate which cell the text
1437 ;;came from.
1438 (ses-dotimes-msg (row numrows) "Finding cells..."
1439 (dotimes (col numcols)
1440 (setq pos end
1441 sym (ses-cell-symbol row col))
1442 ;;Include skipped cells following this one
1443 (while (and (< col (1- numcols))
1444 (eq (ses-cell-value row (1+ col)) '*skip*))
1445 (setq end (+ end (ses-col-width col) 1)
1446 col (1+ col)))
1447 (setq end (+ end (ses-col-width col) 1))
1448 (put-text-property pos end 'intangible sym)))
1449 ;;Adding these properties did not actually alter the text
1450 (unless was-modified
1451 (set-buffer-modified-p nil)
1452 (buffer-disable-undo)
1453 (buffer-enable-undo)))
1454 ;;Create the underlining overlay. It's impossible for (point) to be 2,
1455 ;;because column A must be at least 1 column wide.
1456 (setq curcell-overlay (make-overlay 2 2))
1457 (overlay-put curcell-overlay 'face 'underline))
1459 (defun ses-cleanup ()
1460 "Cleanup when changing a buffer from SES mode to something else. Delete
1461 overlay, remove special text properties."
1462 (widen)
1463 (let ((inhibit-read-only t)
1464 (was-modified (buffer-modified-p))
1465 end)
1466 ;;Delete read-only, keymap, and intangible properties
1467 (set-text-properties 1 (point-max) nil)
1468 ;;Delete overlay
1469 (mapc 'delete-overlay (overlays-in 1 (point-max)))
1470 (unless was-modified
1471 (set-buffer-modified-p nil))))
1473 ;;;###autoload
1474 (defun ses-mode ()
1475 "Major mode for Simple Emacs Spreadsheet. See \"ses-readme.txt\" for more info.
1477 Key definitions:
1478 \\{ses-mode-map}
1479 These key definitions are active only in the print area (the visible part):
1480 \\{ses-mode-print-map}
1481 These are active only in the minibuffer, when entering or editing a formula:
1482 \\{ses-mode-edit-map}"
1483 (interactive)
1484 (unless (and (boundp 'deferred-narrow)
1485 (eq deferred-narrow 'ses-mode))
1486 (kill-all-local-variables)
1487 (mapc 'make-local-variable ses-localvars)
1488 (setq major-mode 'ses-mode
1489 mode-name "SES"
1490 next-line-add-newlines nil
1491 truncate-lines t
1492 ;;SES deliberately puts lots of trailing whitespace in its buffer
1493 show-trailing-whitespace nil
1494 ;;Cell ranges do not work reasonably without this
1495 transient-mark-mode t)
1496 (unless (and ses-mode-map ses-mode-print-map ses-mode-edit-map)
1497 (ses-build-mode-map))
1498 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1499 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1500 (setq curcell nil
1501 deferred-recalc nil
1502 deferred-write nil
1503 header-hscroll -1 ;Flag for "initial recalc needed"
1504 header-line-format '(:eval (progn
1505 (when (/= (window-hscroll)
1506 header-hscroll)
1507 ;;Reset header-hscroll first, to
1508 ;;avoid recursion problems when
1509 ;;debugging ses-create-header-string
1510 (setq header-hscroll (window-hscroll))
1511 (ses-create-header-string))
1512 header-string)))
1513 (let ((was-empty (zerop (buffer-size)))
1514 (was-modified (buffer-modified-p)))
1515 (save-excursion
1516 (if was-empty
1517 ;;Initialize buffer to contain one cell, for now
1518 (insert ses-initial-file-contents))
1519 (ses-load)
1520 (ses-setup))
1521 (when was-empty
1522 (unless (equal ses-initial-default-printer (1value default-printer))
1523 (1value (ses-read-default-printer ses-initial-default-printer)))
1524 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1525 (1value (ses-set-column-width 0 ses-initial-column-width)))
1526 (ses-set-curcell)
1527 (if (> (car ses-initial-size) (1value numrows))
1528 (1value (ses-insert-row (1- (car ses-initial-size)))))
1529 (if (> (cdr ses-initial-size) (1value numcols))
1530 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1531 (ses-write-cells)
1532 (set-buffer-modified-p was-modified)
1533 (buffer-disable-undo)
1534 (buffer-enable-undo)
1535 (goto-char 1)))
1536 (use-local-map ses-mode-map)
1537 ;;Set the deferred narrowing flag (we can't narrow until after
1538 ;;after-find-file completes). If .ses is on the auto-load alist and the
1539 ;;file has "mode: ses", our ses-mode function will be called twice! Use
1540 ;;a special flag to detect this (will be reset by ses-command-hook).
1541 ;;For find-alternate-file, post-command-hook doesn't get run for some
1542 ;;reason, so use an idle timer to make sure.
1543 (setq deferred-narrow 'ses-mode)
1544 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1545 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1546 (run-hooks 'ses-mode-hook)))
1548 (put 'ses-mode 'mode-class 'special)
1550 (defun ses-command-hook ()
1551 "Invoked from `post-command-hook'. If point has moved to a different cell,
1552 moves the underlining overlay. Performs any recalculations or cell-data
1553 writes that have been deferred. If buffer-narrowing has been deferred,
1554 narrows the buffer now."
1555 (condition-case err
1556 (when (eq major-mode 'ses-mode) ;Otherwise, not our buffer anymore
1557 (when deferred-recalc
1558 ;;We reset the deferred list before starting on the recalc -- in case
1559 ;;of error, we don't want to retry the recalc after every keystroke!
1560 (let ((old deferred-recalc))
1561 (setq deferred-recalc nil)
1562 (ses-update-cells old)))
1563 (if deferred-write
1564 ;;We don't reset the deferred list before starting -- the most
1565 ;;likely error is keyboard-quit, and we do want to keep trying
1566 ;;these writes after a quit.
1567 (ses-write-cells))
1568 (when deferred-narrow
1569 ;;We're not allowed to narrow the buffer until after-find-file has
1570 ;;read the local variables at the end of the file. Now it's safe to
1571 ;;do the narrowing.
1572 (save-excursion
1573 (goto-char 1)
1574 (forward-line numrows)
1575 (narrow-to-region 1 (point)))
1576 (setq deferred-narrow nil))
1577 ;;Update the modeline
1578 (let ((oldcell curcell))
1579 (ses-set-curcell)
1580 (unless (eq curcell oldcell)
1581 (cond
1582 ((not curcell)
1583 (setq mode-line-process nil))
1584 ((atom curcell)
1585 (setq mode-line-process (list " cell " (symbol-name curcell))))
1587 (setq mode-line-process (list " range "
1588 (symbol-name (car curcell))
1590 (symbol-name (cdr curcell))))))
1591 (force-mode-line-update)))
1592 ;;Use underline overlay for single-cells only, turn off otherwise
1593 (if (listp curcell)
1594 (move-overlay curcell-overlay 2 2)
1595 (let ((next (next-single-property-change (point) 'intangible)))
1596 (move-overlay curcell-overlay (point) (1- next))))
1597 (when (not (pos-visible-in-window-p))
1598 ;;Scrolling will happen later
1599 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1600 (setq curcell t)))
1601 ;;Prevent errors in this post-command-hook from silently erasing the hook!
1602 (error
1603 (unless executing-kbd-macro
1604 (ding))
1605 (message (error-message-string err))))
1606 nil) ;Make coverage-tester happy
1608 (defun ses-header-string-left-offset ()
1609 "Number of characters in left fringe and left scrollbar (if any)."
1610 (let ((left-fringe (round (or (frame-parameter nil 'left-fringe) 0)
1611 (frame-char-width)))
1612 (left-scrollbar (if (not (eq (frame-parameter nil
1613 'vertical-scroll-bars)
1614 'left))
1616 (let ((x (frame-parameter nil 'scroll-bar-width)))
1617 ;;Non-toolkil bar is always 14 pixels?
1618 (unless x (setq x 14))
1619 ;;Always round up
1620 (ceiling x (frame-char-width))))))
1621 (+ left-fringe left-scrollbar)))
1623 (defun ses-create-header-string ()
1624 "Sets up `header-string' as the buffer's header line, based on the
1625 current set of columns and window-scroll position."
1626 (let* ((left-offset (ses-header-string-left-offset))
1627 (totwidth (- left-offset (window-hscroll)))
1628 result width result x)
1629 ;;Leave room for the left-side fringe and scrollbar
1630 (push (make-string left-offset ? ) result)
1631 (dotimes (col numcols)
1632 (setq width (ses-col-width col)
1633 totwidth (+ totwidth width 1))
1634 (if (= totwidth (+ left-offset 1))
1635 ;;Scrolled so intercolumn space is leftmost
1636 (push " " result))
1637 (when (> totwidth (+ left-offset 1))
1638 (if (> header-row 0)
1639 (save-excursion
1640 (ses-goto-print (1- header-row) col)
1641 (setq x (buffer-substring-no-properties (point)
1642 (+ (point) width)))
1643 (if (>= width (- totwidth left-offset))
1644 (setq x (substring x (- width totwidth left-offset -1))))
1645 (push (propertize x 'face ses-box-prop) result))
1646 (setq x (ses-column-letter col))
1647 (push (propertize x 'face ses-box-prop) result)
1648 (push (propertize (make-string (- width (length x)) ?.)
1649 'display `((space :align-to ,(1- totwidth)))
1650 'face ses-box-prop)
1651 result))
1652 ;;Allow the following space to be squished to make room for the 3-D box
1653 ;;Coverage test ignores properties, thinks this is always a space!
1654 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
1655 result)))
1656 (if (> header-row 0)
1657 (push (propertize (format " [row %d]" header-row)
1658 'display '((height (- 1))))
1659 result))
1660 (setq header-string (apply 'concat (nreverse result)))))
1663 ;;;----------------------------------------------------------------------------
1664 ;;;; Redisplay and recalculation
1665 ;;;----------------------------------------------------------------------------
1667 (defun ses-jump (sym)
1668 "Move point to cell SYM."
1669 (interactive "SJump to cell: ")
1670 (let ((rowcol (ses-sym-rowcol sym)))
1671 (or rowcol (error "Invalid cell name"))
1672 (if (eq (symbol-value sym) '*skip*)
1673 (error "Cell is covered by preceding cell"))
1674 (ses-goto-print (car rowcol) (cdr rowcol))))
1676 (defun ses-jump-safe (cell)
1677 "Like `ses-jump', but no error if invalid cell."
1678 (condition-case nil
1679 (ses-jump cell)
1680 (error)))
1682 (defun ses-reprint-all (&optional nonarrow)
1683 "Recreate the display area. Calls all printer functions. Narrows to
1684 print area if NONARROW is nil."
1685 (interactive "*P")
1686 (widen)
1687 (unless nonarrow
1688 (setq deferred-narrow t))
1689 (let ((startcell (get-text-property (point) 'intangible))
1690 (inhibit-read-only t))
1691 (ses-begin-change)
1692 (goto-char 1)
1693 (search-forward ses-print-data-boundary)
1694 (backward-char (length ses-print-data-boundary))
1695 (delete-region 1 (point))
1696 ;;Insert all blank lines before printing anything, so ses-print-cell can
1697 ;;find the data area when inserting or deleting *skip* values for cells
1698 (dotimes (row numrows)
1699 (insert-and-inherit blank-line))
1700 (ses-dotimes-msg (row numrows) "Reprinting..."
1701 (if (eq (ses-cell-value row 0) '*skip*)
1702 ;;Column deletion left a dangling skip
1703 (ses-set-cell row 0 'value nil))
1704 (dotimes (col numcols)
1705 (ses-print-cell row col))
1706 (beginning-of-line 2))
1707 (ses-jump-safe startcell)))
1709 (defun ses-recalculate-cell ()
1710 "Recalculate and reprint the current cell or range.
1712 For an individual cell, shows the error if the formula or printer
1713 signals one, or otherwise shows the cell's complete value. For a range, the
1714 cells are recalculated in \"natural\" order, so cells that other cells refer
1715 to are recalculated first."
1716 (interactive "*")
1717 (ses-check-curcell 'range)
1718 (ses-begin-change)
1719 (let (sig)
1720 (setq ses-start-time (float-time))
1721 (if (atom curcell)
1722 (setq sig (ses-sym-rowcol curcell)
1723 sig (ses-calculate-cell (car sig) (cdr sig) t))
1724 ;;First, recalculate all cells that don't refer to other cells and
1725 ;;produce a list of cells with references.
1726 (ses-dorange curcell
1727 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
1728 (condition-case nil
1729 (progn
1730 ;;The t causes an error if the cell has references.
1731 ;;If no references, the t will be the result value.
1732 (1value (ses-formula-references (ses-cell-formula row col) t))
1733 (setq sig (ses-calculate-cell row col t)))
1734 (wrong-type-argument
1735 ;;The formula contains a reference
1736 (add-to-list 'deferred-recalc (ses-cell-symbol row col))))))
1737 ;;Do the update now, so we can force recalculation
1738 (let ((x deferred-recalc))
1739 (setq deferred-recalc nil)
1740 (condition-case hold
1741 (ses-update-cells x t)
1742 (error (setq sig hold))))
1743 (cond
1744 (sig
1745 (message (error-message-string sig)))
1746 ((consp curcell)
1747 (message " "))
1749 (princ (symbol-value curcell))))))
1751 (defun ses-recalculate-all ()
1752 "Recalculate and reprint all cells."
1753 (interactive "*")
1754 (let ((startcell (get-text-property (point) 'intangible))
1755 (curcell (cons 'A1 (ses-cell-symbol (1- numrows) (1- numcols)))))
1756 (ses-recalculate-cell)
1757 (ses-jump-safe startcell)))
1759 (defun ses-truncate-cell ()
1760 "Reprint current cell, but without spillover into any following blank
1761 cells."
1762 (interactive "*")
1763 (ses-check-curcell)
1764 (let* ((rowcol (ses-sym-rowcol curcell))
1765 (row (car rowcol))
1766 (col (cdr rowcol)))
1767 (when (and (< col (1- numcols)) ;;Last column can't spill over, anyway
1768 (eq (ses-cell-value row (1+ col)) '*skip*))
1769 ;;This cell has spill-over. We'll momentarily pretend the following
1770 ;;cell has a `t' in it.
1771 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
1772 (ses-print-cell row col)))
1773 ;;Now remove the *skip*. ses-print-cell is always nil here
1774 (ses-set-cell row (1+ col) 'value nil)
1775 (1value (ses-print-cell row (1+ col))))))
1777 (defun ses-reconstruct-all ()
1778 "Reconstruct buffer based on cell data stored in Emacs variables."
1779 (interactive "*")
1780 (ses-begin-change)
1781 ;;Reconstruct reference lists.
1782 (let (refs x yrow ycol)
1783 ;;Delete old reference lists
1784 (ses-dotimes-msg (row numrows) "Deleting references..."
1785 (dotimes (col numcols)
1786 (ses-set-cell row col 'references nil)))
1787 ;;Create new reference lists
1788 (ses-dotimes-msg (row numrows) "Computing references..."
1789 (dotimes (col numcols)
1790 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
1791 (setq x (ses-sym-rowcol ref)
1792 yrow (car x)
1793 ycol (cdr x))
1794 (ses-set-cell yrow ycol 'references
1795 (cons (ses-cell-symbol row col)
1796 (ses-cell-references yrow ycol)))))))
1797 ;;Delete everything and reconstruct basic data area
1798 (if (< (point-max) (buffer-size))
1799 (setq deferred-narrow t))
1800 (widen)
1801 (let ((inhibit-read-only t))
1802 (goto-char (point-max))
1803 (if (search-backward ";;; Local Variables:\n" nil t)
1804 (delete-region 1 (point))
1805 ;;Buffer is quite screwed up - can't even save the user-specified locals
1806 (delete-region 1 (point-max))
1807 (insert ses-initial-file-trailer)
1808 (goto-char 1))
1809 ;;Create a blank display area
1810 (dotimes (row numrows)
1811 (insert blank-line))
1812 (insert ses-print-data-boundary)
1813 ;;Placeholders for cell data
1814 (insert (make-string (* numrows (1+ numcols)) ?\n))
1815 ;;Placeholders for col-widths, col-printers, default-printer, header-row
1816 (insert "\n\n\n\n")
1817 (insert ses-initial-global-parameters))
1818 (ses-set-parameter 'column-widths column-widths)
1819 (ses-set-parameter 'col-printers col-printers)
1820 (ses-set-parameter 'default-printer default-printer)
1821 (ses-set-parameter 'header-row header-row)
1822 (ses-set-parameter 'numrows numrows)
1823 (ses-set-parameter 'numcols numcols)
1824 ;;Keep our old narrowing
1825 (ses-setup)
1826 (ses-recalculate-all)
1827 (goto-char 1))
1830 ;;;----------------------------------------------------------------------------
1831 ;;;; Input of cell formulas
1832 ;;;----------------------------------------------------------------------------
1834 (defun ses-edit-cell (row col newval)
1835 "Display current cell contents in minibuffer, for editing. Returns nil if
1836 cell formula was unsafe and user declined confirmation."
1837 (interactive
1838 (progn
1839 (barf-if-buffer-read-only)
1840 (ses-check-curcell)
1841 (let* ((rowcol (ses-sym-rowcol curcell))
1842 (row (car rowcol))
1843 (col (cdr rowcol))
1844 (formula (ses-cell-formula row col))
1845 initial)
1846 (if (eq (car-safe formula) 'ses-safe-formula)
1847 (setq formula (cadr formula)))
1848 (if (eq (car-safe formula) 'quote)
1849 (setq initial (format "'%S" (cadr formula)))
1850 (setq initial (prin1-to-string formula)))
1851 (if (stringp formula)
1852 ;;Position cursor inside close-quote
1853 (setq initial (cons initial (length initial))))
1854 (list row col
1855 (read-from-minibuffer (format "Cell %s: " curcell)
1856 initial
1857 ses-mode-edit-map
1858 t ;Convert to Lisp object
1859 'ses-read-cell-history)))))
1860 (when (ses-warn-unsafe newval 'unsafep)
1861 (ses-begin-change)
1862 (ses-cell-set-formula row col newval)
1865 (defun ses-read-cell (row col newval)
1866 "Self-insert for initial character of cell function."
1867 (interactive
1868 (let ((initial (this-command-keys))
1869 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol curcell))))
1870 (barf-if-buffer-read-only)
1871 (if (string= initial "\"")
1872 (setq initial "\"\"") ;Enter a string
1873 (if (string= initial "(")
1874 (setq initial "()"))) ;Enter a formula list
1875 (list (car rowcol)
1876 (cdr rowcol)
1877 (read-from-minibuffer (format "Cell %s: " curcell)
1878 (cons initial 2)
1879 ses-mode-edit-map
1880 t ;Convert to Lisp object
1881 'ses-read-cell-history))))
1882 (when (ses-edit-cell row col newval)
1883 (ses-command-hook) ;Update cell widths before movement
1884 (dolist (x ses-after-entry-functions)
1885 (funcall x 1))))
1887 (defun ses-read-symbol (row col symb)
1888 "Self-insert for a symbol as a cell formula. The set of all symbols that
1889 have been used as formulas in this spreadsheet is available for completions."
1890 (interactive
1891 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol curcell)))
1892 newval)
1893 (barf-if-buffer-read-only)
1894 (setq newval (completing-read (format "Cell %s ': " curcell)
1895 symbolic-formulas))
1896 (list (car rowcol)
1897 (cdr rowcol)
1898 (if (string= newval "")
1899 nil ;Don't create zero-length symbols!
1900 (list 'quote (intern newval))))))
1901 (when (ses-edit-cell row col symb)
1902 (ses-command-hook) ;Update cell widths before movement
1903 (dolist (x ses-after-entry-functions)
1904 (funcall x 1))))
1906 (defun ses-clear-cell-forward (count)
1907 "Delete formula and printer for current cell and then move to next cell.
1908 With prefix, deletes several cells."
1909 (interactive "*p")
1910 (if (< count 0)
1911 (1value (ses-clear-cell-backward (- count)))
1912 (ses-check-curcell)
1913 (ses-begin-change)
1914 (dotimes (x count)
1915 (ses-set-curcell)
1916 (let ((rowcol (ses-sym-rowcol curcell)))
1917 (or rowcol (signal 'end-of-buffer nil))
1918 (ses-clear-cell (car rowcol) (cdr rowcol)))
1919 (forward-char 1))))
1921 (defun ses-clear-cell-backward (count)
1922 "Move to previous cell and then delete it. With prefix, deletes several
1923 cells."
1924 (interactive "*p")
1925 (if (< count 0)
1926 (1value (ses-clear-cell-forward (- count)))
1927 (ses-check-curcell 'end)
1928 (ses-begin-change)
1929 (dotimes (x count)
1930 (backward-char 1) ;Will signal 'beginning-of-buffer if appropriate
1931 (ses-set-curcell)
1932 (let ((rowcol (ses-sym-rowcol curcell)))
1933 (ses-clear-cell (car rowcol) (cdr rowcol))))))
1936 ;;;----------------------------------------------------------------------------
1937 ;;;; Input of cell-printer functions
1938 ;;;----------------------------------------------------------------------------
1940 (defun ses-read-printer (prompt default)
1941 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
1942 PROMPT should end with \": \". Result is t if operation was cancelled."
1943 (barf-if-buffer-read-only)
1944 (if (eq default t)
1945 (setq default "")
1946 (setq prompt (format "%s [currently %S]: "
1947 (substring prompt 0 -2)
1948 default)))
1949 (let ((new (read-from-minibuffer prompt
1950 nil ;Initial contents
1951 ses-mode-edit-map
1952 t ;Evaluate the result
1953 'ses-read-printer-history
1954 (prin1-to-string default))))
1955 (if (equal new default)
1956 ;;User changed mind, decided not to change printer
1957 (setq new t)
1958 (ses-printer-validate new)
1959 (or (not new)
1960 (stringp new)
1961 (stringp (car-safe new))
1962 (ses-warn-unsafe new 'unsafep-function)
1963 (setq new t)))
1964 new))
1966 (defun ses-read-cell-printer (newval)
1967 "Set the printer function for the current cell or range.
1969 A printer function is either a string (a format control-string with one
1970 %-sequence -- result from format will be right-justified), or a list of one
1971 string (result from format will be left-justified), or a lambda-expression of
1972 one argument, or a symbol that names a function of one argument. In the
1973 latter two cases, the function's result should be either a string (will be
1974 right-justified) or a list of one string (will be left-justified)."
1975 (interactive
1976 (let ((default t)
1977 prompt)
1978 (ses-check-curcell 'range)
1979 ;;Default is none if not all cells in range have same printer
1980 (catch 'ses-read-cell-printer
1981 (ses-dorange curcell
1982 (setq x (ses-cell-printer row col))
1983 (if (eq (car-safe x) 'ses-safe-printer)
1984 (setq x (cadr x)))
1985 (if (eq default t)
1986 (setq default x)
1987 (unless (equal default x)
1988 ;;Range contains differing printer functions
1989 (setq default t)
1990 (throw 'ses-read-cell-printer t)))))
1991 (list (ses-read-printer (format "Cell %S printer: " curcell) default))))
1992 (unless (eq newval t)
1993 (ses-begin-change)
1994 (ses-dorange curcell
1995 (ses-set-cell row col 'printer newval)
1996 (ses-print-cell row col))))
1998 (defun ses-read-column-printer (col newval)
1999 "Set the printer function for the current column. See
2000 `ses-read-cell-printer' for input forms."
2001 (interactive
2002 (let ((col (cdr (ses-sym-rowcol curcell))))
2003 (ses-check-curcell)
2004 (list col (ses-read-printer (format "Column %s printer: "
2005 (ses-column-letter col))
2006 (ses-col-printer col)))))
2008 (unless (eq newval t)
2009 (ses-begin-change)
2010 (ses-set-parameter 'col-printers newval col)
2011 (save-excursion
2012 (dotimes (row numrows)
2013 (ses-print-cell row col)))))
2015 (defun ses-read-default-printer (newval)
2016 "Set the default printer function for cells that have no other. See
2017 `ses-read-cell-printer' for input forms."
2018 (interactive
2019 (list (ses-read-printer "Default printer: " default-printer)))
2020 (unless (eq newval t)
2021 (ses-begin-change)
2022 (ses-set-parameter 'default-printer newval)
2023 (ses-reprint-all t)))
2026 ;;;----------------------------------------------------------------------------
2027 ;;;; Spreadsheet size adjustments
2028 ;;;----------------------------------------------------------------------------
2030 (defun ses-insert-row (count)
2031 "Insert a new row before the current one. With prefix, insert COUNT rows
2032 before current one."
2033 (interactive "*p")
2034 (ses-check-curcell 'end)
2035 (or (> count 0) (signal 'args-out-of-range nil))
2036 (ses-begin-change)
2037 (let ((inhibit-quit t)
2038 (inhibit-read-only t)
2039 (row (or (car (ses-sym-rowcol curcell)) numrows))
2040 newrow)
2041 ;;Create a new set of cell-variables
2042 (ses-create-cell-variable-range numrows (+ numrows count -1)
2043 0 (1- numcols))
2044 (ses-set-parameter 'numrows (+ numrows count))
2045 ;;Insert each row
2046 (ses-goto-print row 0)
2047 (ses-dotimes-msg (x count) "Inserting row..."
2048 ;;Create a row of empty cells. The `symbol' fields will be set by
2049 ;;the call to ses-relocate-all.
2050 (setq newrow (make-vector numcols nil))
2051 (dotimes (col numcols)
2052 (aset newrow col (make-vector ses-cell-size nil)))
2053 (setq cells (ses-vector-insert cells row newrow))
2054 (push `(ses-vector-delete cells ,row 1) buffer-undo-list)
2055 (insert blank-line))
2056 ;;Insert empty lines in cell data area (will be replaced by
2057 ;;ses-relocate-all)
2058 (ses-goto-data row 0)
2059 (insert (make-string (* (1+ numcols) count) ?\n))
2060 (ses-relocate-all row 0 count 0)
2061 ;;If any cell printers insert constant text, insert that text
2062 ;;into the line.
2063 (let ((cols (mapconcat #'ses-call-printer col-printers nil))
2064 (global (ses-call-printer default-printer)))
2065 (if (or (> (length cols) 0) (> (length global) 0))
2066 (dotimes (x count)
2067 (dotimes (col numcols)
2068 ;;These cells are always nil, only constant formatting printed
2069 (1value (ses-print-cell (+ x row) col))))))
2070 (when (> header-row row)
2071 ;;Inserting before header
2072 (ses-set-parameter 'header-row (+ header-row count))
2073 (ses-reset-header-string)))
2074 ;;Reconstruct text attributes
2075 (ses-setup)
2076 ;;Return to current cell
2077 (if curcell
2078 (ses-jump-safe curcell)
2079 (ses-goto-print (1- numrows) 0)))
2081 (defun ses-delete-row (count)
2082 "Delete the current row. With prefix, Deletes COUNT rows starting from the
2083 current one."
2084 (interactive "*p")
2085 (ses-check-curcell)
2086 (or (> count 0) (signal 'args-out-of-range nil))
2087 (let ((inhibit-quit t)
2088 (inhibit-read-only t)
2089 (row (car (ses-sym-rowcol curcell)))
2090 pos)
2091 (setq count (min count (- numrows row)))
2092 (ses-begin-change)
2093 (ses-set-parameter 'numrows (- numrows count))
2094 ;;Delete lines from print area
2095 (ses-goto-print row 0)
2096 (ses-delete-line count)
2097 ;;Delete lines from cell data area
2098 (ses-goto-data row 0)
2099 (ses-delete-line (* count (1+ numcols)))
2100 ;;Relocate variables and formulas
2101 (ses-set-with-undo 'cells (ses-vector-delete cells row count))
2102 (ses-relocate-all row 0 (- count) 0)
2103 (ses-destroy-cell-variable-range numrows (+ numrows count -1)
2104 0 (1- numcols))
2105 (when (> header-row row)
2106 (if (<= header-row (+ row count))
2107 ;;Deleting the header row
2108 (ses-set-parameter 'header-row 0)
2109 (ses-set-parameter 'header-row (- header-row count)))
2110 (ses-reset-header-string)))
2111 ;;Reconstruct attributes
2112 (ses-setup)
2113 (ses-jump-safe curcell))
2115 (defun ses-insert-column (count &optional col width printer)
2116 "Insert a new column before COL (default is the current one). With prefix,
2117 insert COUNT columns before current one. If COL is specified, the new
2118 column(s) get the specified WIDTH and PRINTER (otherwise they're taken from
2119 the current column)."
2120 (interactive "*p")
2121 (ses-check-curcell)
2122 (or (> count 0) (signal 'args-out-of-range nil))
2123 (or col
2124 (setq col (cdr (ses-sym-rowcol curcell))
2125 width (ses-col-width col)
2126 printer (ses-col-printer col)))
2127 (ses-begin-change)
2128 (let ((inhibit-quit t)
2129 (inhibit-read-only t)
2130 (widths column-widths)
2131 (printers col-printers)
2132 has-skip)
2133 ;;Create a new set of cell-variables
2134 (ses-create-cell-variable-range 0 (1- numrows)
2135 numcols (+ numcols count -1))
2136 ;;Insert each column.
2137 (ses-dotimes-msg (x count) "Inserting column..."
2138 ;;Create a column of empty cells. The `symbol' fields will be set by
2139 ;;the call to ses-relocate-all.
2140 (ses-adjust-print-width col (1+ width))
2141 (ses-set-parameter 'numcols (1+ numcols))
2142 (dotimes (row numrows)
2143 (and (< (1+ col) numcols) (eq (ses-cell-value row col) '*skip*)
2144 ;;Inserting in the middle of a spill-over
2145 (setq has-skip t))
2146 (ses-aset-with-undo cells row
2147 (ses-vector-insert (aref cells row)
2149 (make-vector ses-cell-size nil)))
2150 ;;Insert empty lines in cell data area (will be replaced by
2151 ;;ses-relocate-all)
2152 (ses-goto-data row col)
2153 (insert ?\n))
2154 ;;Insert column width and printer
2155 (setq widths (ses-vector-insert widths col width)
2156 printers (ses-vector-insert printers col printer)))
2157 (ses-set-parameter 'column-widths widths)
2158 (ses-set-parameter 'col-printers printers)
2159 (ses-reset-header-string)
2160 (ses-relocate-all 0 col 0 count)
2161 (if has-skip
2162 (ses-reprint-all t)
2163 (when (or (> (length (ses-call-printer printer)) 0)
2164 (> (length (ses-call-printer default-printer)) 0))
2165 ;;Either column printer or global printer inserts some constant text
2166 ;;Reprint the new columns to insert that text.
2167 (dotimes (x numrows)
2168 (dotimes (y count)
2169 ;Always nil here - this is a blank column
2170 (1value (ses-print-cell-new-width x (+ y col))))))
2171 (ses-setup)))
2172 (ses-jump-safe curcell))
2174 (defun ses-delete-column (count)
2175 "Delete the current column. With prefix, Deletes COUNT columns starting
2176 from the current one."
2177 (interactive "*p")
2178 (ses-check-curcell)
2179 (or (> count 0) (signal 'args-out-of-range nil))
2180 (let ((inhibit-quit t)
2181 (inhibit-read-only t)
2182 (rowcol (ses-sym-rowcol curcell))
2183 (width 0)
2184 new col origrow has-skip)
2185 (setq origrow (car rowcol)
2186 col (cdr rowcol)
2187 count (min count (- numcols col)))
2188 (if (= count numcols)
2189 (error "Can't delete all columns!"))
2190 ;;Determine width of column(s) being deleted
2191 (dotimes (x count)
2192 (setq width (+ width (ses-col-width (+ col x)) 1)))
2193 (ses-begin-change)
2194 (ses-set-parameter 'numcols (- numcols count))
2195 (ses-adjust-print-width col (- width))
2196 (ses-dotimes-msg (row numrows) "Deleting column..."
2197 ;;Delete lines from cell data area
2198 (ses-goto-data row col)
2199 (ses-delete-line count)
2200 ;;Delete cells. Check if deletion area begins or ends with a skip.
2201 (if (or (eq (ses-cell-value row col) '*skip*)
2202 (and (< col numcols)
2203 (eq (ses-cell-value row (+ col count)) '*skip*)))
2204 (setq has-skip t))
2205 (ses-aset-with-undo cells row
2206 (ses-vector-delete (aref cells row) col count)))
2207 ;;Update globals
2208 (ses-set-parameter 'column-widths
2209 (ses-vector-delete column-widths col count))
2210 (ses-set-parameter 'col-printers
2211 (ses-vector-delete col-printers col count))
2212 (ses-reset-header-string)
2213 ;;Relocate variables and formulas
2214 (ses-relocate-all 0 col 0 (- count))
2215 (ses-destroy-cell-variable-range 0 (1- numrows)
2216 numcols (+ numcols count -1))
2217 (if has-skip
2218 (ses-reprint-all t)
2219 (ses-setup))
2220 (if (>= col numcols)
2221 (setq col (1- col)))
2222 (ses-goto-print origrow col)))
2224 (defun ses-forward-or-insert (&optional count)
2225 "Move to next cell in row, or inserts a new cell if already in last one, or
2226 inserts a new row if at bottom of print area. Repeat COUNT times."
2227 (interactive "p")
2228 (ses-check-curcell 'end)
2229 (setq deactivate-mark t) ;Doesn't combine well with ranges
2230 (dotimes (x count)
2231 (ses-set-curcell)
2232 (if (not curcell)
2233 (progn ;At bottom of print area
2234 (barf-if-buffer-read-only)
2235 (ses-insert-row 1))
2236 (let ((col (cdr (ses-sym-rowcol curcell))))
2237 (when (/= 32
2238 (char-before (next-single-property-change (point)
2239 'intangible)))
2240 ;;We're already in last nonskipped cell on line. Need to create a
2241 ;;new column.
2242 (barf-if-buffer-read-only)
2243 (ses-insert-column (- count x)
2244 numcols
2245 (ses-col-width col)
2246 (ses-col-printer col)))))
2247 (forward-char)))
2249 (defun ses-append-row-jump-first-column ()
2250 "Insert a new row after current one and jumps to its first column."
2251 (interactive "*")
2252 (ses-check-curcell)
2253 (ses-begin-change)
2254 (beginning-of-line 2)
2255 (ses-set-curcell)
2256 (ses-insert-row 1))
2258 (defun ses-set-column-width (col newwidth)
2259 "Set the width of the current column."
2260 (interactive
2261 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol curcell)))))
2262 (barf-if-buffer-read-only)
2263 (list col
2264 (if current-prefix-arg
2265 (prefix-numeric-value current-prefix-arg)
2266 (read-from-minibuffer (format "Column %s width [currently %d]: "
2267 (ses-column-letter col)
2268 (ses-col-width col))
2269 nil ;No initial contents
2270 nil ;No override keymap
2271 t ;Convert to Lisp object
2272 nil ;No history
2273 (number-to-string
2274 (ses-col-width col))))))) ;Default value
2275 (if (< newwidth 1)
2276 (error "Invalid column width"))
2277 (ses-begin-change)
2278 (ses-reset-header-string)
2279 (save-excursion
2280 (let ((inhibit-quit t))
2281 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2282 (ses-set-parameter 'column-widths newwidth col))
2283 (dotimes (row numrows)
2284 (ses-print-cell-new-width row col))))
2287 ;;;----------------------------------------------------------------------------
2288 ;;;; Cut and paste, import and export
2289 ;;;----------------------------------------------------------------------------
2291 (defadvice copy-region-as-kill (around ses-copy-region-as-kill
2292 activate preactivate)
2293 "It doesn't make sense to copy read-only or intangible attributes into the
2294 kill ring. It probably doesn't make sense to copy keymap properties.
2295 We'll assume copying front-sticky properties doesn't make sense, either.
2297 This advice also includes some SES-specific code because otherwise it's too
2298 hard to override how mouse-1 works."
2299 (when (> beg end)
2300 (let ((temp beg))
2301 (setq beg end
2302 end temp)))
2303 (if (not (and (eq major-mode 'ses-mode)
2304 (eq (get-text-property beg 'read-only) 'ses)
2305 (eq (get-text-property (1- end) 'read-only) 'ses)))
2306 ad-do-it ;Normal copy-region-as-kill
2307 (kill-new (ses-copy-region beg end))))
2309 (defun ses-copy-region (beg end)
2310 "Treat the region as rectangular. Convert the intangible attributes to
2311 SES attributes recording the contents of the cell as of the time of copying."
2312 (let* ((inhibit-point-motion-hooks t)
2313 (x (mapconcat 'ses-copy-region-helper
2314 (extract-rectangle beg (1- end)) "\n")))
2315 (remove-text-properties 0 (length x)
2316 '(read-only t
2317 intangible t
2318 keymap t
2319 front-sticky t)
2323 (defun ses-copy-region-helper (line)
2324 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2325 external form by attaching to each print cell a 'ses attribute that records
2326 the corresponding data cell."
2327 (or (> (length line) 1)
2328 (error "Empty range"))
2329 (let ((inhibit-read-only t)
2330 (pos 0)
2331 mycell next sym rowcol)
2332 (while pos
2333 (setq sym (get-text-property pos 'intangible line)
2334 next (next-single-property-change pos 'intangible line)
2335 rowcol (ses-sym-rowcol sym)
2336 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2337 (put-text-property pos (or next (length line))
2338 'ses
2339 (list (ses-cell-symbol mycell)
2340 (ses-cell-formula mycell)
2341 (ses-cell-printer mycell))
2342 line)
2343 (setq pos next)))
2344 line)
2346 (defun ses-kill-override (beg end)
2347 "Generic override for any commands that kill text. We clear the killed
2348 cells instead of deleting them."
2349 (interactive "r")
2350 (ses-check-curcell 'needrange)
2351 ;;For some reason, the text-read-only error is not caught by
2352 ;;`delete-region', so we have to use subterfuge.
2353 (let ((buffer-read-only t))
2354 (1value (condition-case x
2355 (noreturn (funcall (lookup-key (current-global-map)
2356 (this-command-keys))
2357 beg end))
2358 (buffer-read-only nil)))) ;The expected error
2359 ;;Because the buffer was marked read-only, the kill command turned itself
2360 ;;into a copy. Now we clear the cells or signal the error. First we
2361 ;;check whether the buffer really is read-only.
2362 (barf-if-buffer-read-only)
2363 (ses-begin-change)
2364 (ses-dorange curcell
2365 (ses-clear-cell row col))
2366 (ses-jump (car curcell)))
2368 (defadvice yank (around ses-yank activate preactivate)
2369 "In SES mode, the yanked text is inserted as cells.
2371 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2372 SES buffer), the formulas and print functions are restored for the cells. If
2373 the text contains tabs, this is an insertion of tab-separated formulas.
2374 Otherwise the text is inserted as the formula for the current cell.
2376 When inserting cells, the formulas are usually relocated to keep the same
2377 relative references to neighboring cells. This is best if the formulas
2378 generally refer to other cells within the yanked text. You can use the C-u
2379 prefix to specify insertion without relocation, which is best when the
2380 formulas refer to cells outsite the yanked text.
2382 When inserting formulas, the text is treated as a string constant if it doesn't
2383 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2384 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2385 as symbols."
2386 (if (not (and (eq major-mode 'ses-mode)
2387 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2388 ad-do-it ;Normal non-SES yank
2389 (ses-check-curcell 'end)
2390 (push-mark (point))
2391 (let ((text (current-kill (cond
2392 ((listp arg) 0)
2393 ((eq arg '-) -1)
2394 (t (1- arg))))))
2395 (or (ses-yank-cells text arg)
2396 (ses-yank-tsf text arg)
2397 (ses-yank-one (ses-yank-resize 1 1)
2398 text
2400 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2401 ;;Just one cell - delete final tab or newline
2402 (1- (length text)))
2403 arg)))
2404 (if (consp arg)
2405 (exchange-point-and-mark))))
2407 (defun ses-yank-pop (arg)
2408 "Replace just-yanked stretch of killed text with a different stretch.
2409 This command is allowed only immediately after a `yank' or a `yank-pop', when
2410 the region contains a stretch of reinserted previously-killed text. We
2411 replace it with a different stretch of killed text.
2412 Unlike standard `yank-pop', this function uses `undo' to delete the
2413 previous insertion."
2414 (interactive "*p")
2415 (or (eq last-command 'yank)
2416 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2417 ;;macro definition.
2418 (noreturn (error "Previous command was not a yank")))
2419 (undo)
2420 (ses-set-curcell)
2421 (yank (1+ (or arg 1)))
2422 (setq this-command 'yank))
2424 (defun ses-yank-cells (text arg)
2425 "If the TEXT has a proper set of 'ses attributes, inserts the text as
2426 cells, else return nil. The cells are reprinted--the supplied text is
2427 ignored because the column widths, default printer, etc. at yank time might
2428 be different from those at kill-time. ARG is a list to indicate that
2429 formulas are to be inserted without relocation."
2430 (let ((first (get-text-property 0 'ses text))
2431 (last (get-text-property (1- (length text)) 'ses text)))
2432 (when (and first last) ;;Otherwise not proper set of attributes
2433 (setq first (ses-sym-rowcol (car first))
2434 last (ses-sym-rowcol (car last)))
2435 (let* ((needrows (- (car last) (car first) -1))
2436 (needcols (- (cdr last) (cdr first) -1))
2437 (rowcol (ses-yank-resize needrows needcols))
2438 (rowincr (- (car rowcol) (car first)))
2439 (colincr (- (cdr rowcol) (cdr first)))
2440 (pos 0)
2441 myrow mycol x)
2442 (ses-dotimes-msg (row needrows) "Yanking..."
2443 (setq myrow (+ row (car rowcol)))
2444 (dotimes (col needcols)
2445 (setq mycol (+ col (cdr rowcol))
2446 last (get-text-property pos 'ses text)
2447 pos (next-single-property-change pos 'ses text)
2448 x (ses-sym-rowcol (car last)))
2449 (if (not last)
2450 ;;Newline - all remaining cells on row are skipped
2451 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2452 last (list nil nil nil)
2453 pos (1- pos)))
2454 (if (/= (car x) (- myrow rowincr))
2455 (error "Cell row error"))
2456 (if (< (- mycol colincr) (cdr x))
2457 ;;Some columns were skipped
2458 (let ((oldcol mycol))
2459 (while (< (- mycol colincr) (cdr x))
2460 (ses-clear-cell myrow mycol)
2461 (setq col (1+ col)
2462 mycol (1+ mycol)))
2463 (ses-print-cell myrow (1- oldcol)))) ;;This inserts *skip*
2464 (when (car last) ;Skip this for *skip* cells
2465 (setq x (nth 2 last))
2466 (unless (equal x (ses-cell-printer myrow mycol))
2467 (or (not x)
2468 (stringp x)
2469 (eq (car-safe x) 'ses-safe-printer)
2470 (setq x `(ses-safe-printer ,x)))
2471 (ses-set-cell myrow mycol 'printer x))
2472 (setq x (cadr last))
2473 (if (atom arg)
2474 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2475 (or (atom x)
2476 (eq (car-safe x) 'ses-safe-formula)
2477 (setq x `(ses-safe-formula ,x)))
2478 (ses-cell-set-formula myrow mycol x)))
2479 (when pos
2480 (if (get-text-property pos 'ses text)
2481 (error "Missing newline between rows"))
2482 (setq pos (next-single-property-change pos 'ses text))))
2483 t))))
2485 (defun ses-yank-one (rowcol text from to arg)
2486 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2487 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2488 (let ((val (condition-case nil
2489 (read-from-string text from to)
2490 (error (cons nil from)))))
2491 (cond
2492 ((< (cdr val) (or to (length text)))
2493 ;;Invalid sexp - leave it as a string
2494 (setq val (substring text from to)))
2495 ((and (car val) (symbolp (car val)))
2496 (if (consp arg)
2497 (setq val (list 'quote (car val))) ;Keep symbol
2498 (setq val (substring text from to)))) ;Treat symbol as text
2500 (setq val (car val))))
2501 (let ((row (car rowcol))
2502 (col (cdr rowcol)))
2503 (or (atom val)
2504 (setq val `(ses-safe-formula ,val)))
2505 (ses-cell-set-formula row col val))))
2507 (defun ses-yank-tsf (text arg)
2508 "If TEXT contains tabs and/or newlines, treats the tabs as
2509 column-separators and the newlines as row-separators and inserts the text as
2510 cell formulas--else return nil. Treat plain symbols as strings unless ARG
2511 is a list. Ignore a final newline."
2512 (if (or (not (string-match "[\t\n]" text))
2513 (= (match-end 0) (length text)))
2514 ;;Not TSF format
2516 (if (/= (aref text (1- (length text))) ?\n)
2517 (setq text (concat text "\n")))
2518 (let ((pos -1)
2519 (spots (list -1))
2520 (cols 0)
2521 (needrows 0)
2522 needcols rowcol)
2523 ;;Find all the tabs and newlines
2524 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
2525 (push pos spots)
2526 (setq cols (1+ cols))
2527 (when (eq (aref text pos) ?\n)
2528 (if (not needcols)
2529 (setq needcols cols)
2530 (or (= needcols cols)
2531 (error "Inconsistent row lengths")))
2532 (setq cols 0
2533 needrows (1+ needrows))))
2534 ;;Insert the formulas
2535 (setq rowcol (ses-yank-resize needrows needcols))
2536 (dotimes (row needrows)
2537 (dotimes (col needcols)
2538 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
2539 (+ (cdr rowcol) needcols (- col) -1))
2540 text (1+ (cadr spots)) (car spots) arg)
2541 (setq spots (cdr spots))))
2542 (ses-goto-print (+ (car rowcol) needrows -1)
2543 (+ (cdr rowcol) needcols -1))
2544 t)))
2546 (defun ses-yank-resize (needrows needcols)
2547 "If this yank will require inserting rows and/or columns, asks for
2548 confirmation and then inserts them. Result is (row,col) for top left of yank
2549 spot, or error signal if user requests cancel."
2550 (ses-begin-change)
2551 (let ((rowcol (if curcell (ses-sym-rowcol curcell) (cons numrows 0)))
2552 rowbool colbool)
2553 (setq needrows (- (+ (car rowcol) needrows) numrows)
2554 needcols (- (+ (cdr rowcol) needcols) numcols)
2555 rowbool (> needrows 0)
2556 colbool (> needcols 0))
2557 (when (or rowbool colbool)
2558 ;;Need to insert. Get confirm
2559 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue "
2560 (if rowbool (format "%d rows" needrows) "")
2561 (if (and rowbool colbool) " and " "")
2562 (if colbool (format "%d columns" needcols) "")))
2563 (error "Cancelled"))
2564 (when rowbool
2565 (let (curcell)
2566 (save-excursion
2567 (ses-goto-print numrows 0)
2568 (ses-insert-row needrows))))
2569 (when colbool
2570 (ses-insert-column needcols
2571 numcols
2572 (ses-col-width (1- numcols))
2573 (ses-col-printer (1- numcols)))))
2574 rowcol))
2576 (defun ses-export-tsv (beg end)
2577 "Export values from the current range, with tabs between columns and
2578 newlines between rows. Result is placed in kill ring."
2579 (interactive "r")
2580 (ses-export-tab nil))
2582 (defun ses-export-tsf (beg end)
2583 "Export formulas from the current range, with tabs between columns and
2584 newlines between rows. Result is placed in kill ring."
2585 (interactive "r")
2586 (ses-export-tab t))
2588 (defun ses-export-tab (want-formulas)
2589 "Export the current range with tabs between columns and newlines between
2590 rows. Result is placed in kill ring. The export is values unless
2591 WANT-FORMULAS is non-nil. Newlines and tabs in the export text are escaped."
2592 (ses-check-curcell 'needrange)
2593 (let ((print-escape-newlines t)
2594 result item)
2595 (ses-dorange curcell
2596 (setq item (if want-formulas
2597 (ses-cell-formula row col)
2598 (ses-cell-value row col)))
2599 (if (eq (car-safe item) 'ses-safe-formula)
2600 ;;Hide our deferred safety-check marker
2601 (setq item (cadr item)))
2602 (if (or (not item) (eq item '*skip*))
2603 (setq item ""))
2604 (when (eq (car-safe item) 'quote)
2605 (push "'" result)
2606 (setq item (cadr item)))
2607 (setq item (prin1-to-string item t))
2608 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
2609 (push item result)
2610 (cond
2611 ((< col maxcol)
2612 (push "\t" result))
2613 ((< row maxrow)
2614 (push "\n" result))))
2615 (setq result (apply 'concat (nreverse result)))
2616 (kill-new result)))
2619 ;;;----------------------------------------------------------------------------
2620 ;;;; Other user commands
2621 ;;;----------------------------------------------------------------------------
2623 (defun ses-read-header-row (row)
2624 (interactive "NHeader row: ")
2625 (if (or (< row 0) (> row numrows))
2626 (error "Invalid header-row"))
2627 (ses-begin-change)
2628 (ses-set-parameter 'header-row row)
2629 (ses-reset-header-string))
2631 (defun ses-mark-row ()
2632 "Marks the entirety of current row as a range."
2633 (interactive)
2634 (ses-check-curcell 'range)
2635 (let ((row (car (ses-sym-rowcol (or (car-safe curcell) curcell)))))
2636 (push-mark (point))
2637 (ses-goto-print (1+ row) 0)
2638 (push-mark (point) nil t)
2639 (ses-goto-print row 0)))
2641 (defun ses-mark-column ()
2642 "Marks the entirety of current column as a range."
2643 (interactive)
2644 (ses-check-curcell 'range)
2645 (let ((col (cdr (ses-sym-rowcol (or (car-safe curcell) curcell))))
2646 (row 0))
2647 (push-mark (point))
2648 (ses-goto-print (1- numrows) col)
2649 (forward-char 1)
2650 (push-mark (point) nil t)
2651 (while (eq '*skip* (ses-cell-value row col))
2652 ;;Skip over initial cells in column that can't be selected
2653 (setq row (1+ row)))
2654 (ses-goto-print row col)))
2656 (defun ses-end-of-line ()
2657 "Move point to last cell on line."
2658 (interactive)
2659 (ses-check-curcell 'end 'range)
2660 (when curcell ;Otherwise we're at the bottom row, which is empty anyway
2661 (let ((col (1- numcols))
2662 row rowcol)
2663 (if (symbolp curcell)
2664 ;;Single cell
2665 (setq row (car (ses-sym-rowcol curcell)))
2666 ;;Range - use whichever end of the range the point is at
2667 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
2668 (car curcell)
2669 (cdr curcell))))
2670 ;;If range already includes the last cell in a row, point is actually
2671 ;;in the following row
2672 (if (<= (cdr rowcol) (1- col))
2673 (setq row (car rowcol))
2674 (setq row (1+ (car rowcol)))
2675 (if (= row numrows)
2676 ;;Already at end - can't go anywhere
2677 (setq col 0))))
2678 (when (< row numrows) ;Otherwise it's a range that includes last cell
2679 (while (eq (ses-cell-value row col) '*skip*)
2680 ;;Back to beginning of multi-column cell
2681 (setq col (1- col)))
2682 (ses-goto-print row col)))))
2684 (defun ses-renarrow-buffer ()
2685 "Narrow the buffer so only the print area is visible. Use after \\[widen]."
2686 (interactive)
2687 (setq deferred-narrow t))
2689 (defun ses-sort-column (sorter &optional reverse)
2690 "Sorts the range by a specified column. With prefix, sorts in
2691 REVERSE order."
2692 (interactive "*sSort column: \nP")
2693 (ses-check-curcell 'needrange)
2694 (let ((min (ses-sym-rowcol (car curcell)))
2695 (max (ses-sym-rowcol (cdr curcell))))
2696 (let ((minrow (car min))
2697 (mincol (cdr min))
2698 (maxrow (car max))
2699 (maxcol (cdr max))
2700 keys extracts end)
2701 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
2702 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
2703 (error "Invalid sort column"))
2704 ;;Get key columns and sort them
2705 (dotimes (x (- maxrow minrow -1))
2706 (ses-goto-print (+ minrow x) sorter)
2707 (setq end (next-single-property-change (point) 'intangible))
2708 (push (cons (buffer-substring-no-properties (point) end)
2709 (+ minrow x))
2710 keys))
2711 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
2712 ;;Extract the lines in reverse sorted order
2713 (or reverse
2714 (setq keys (nreverse keys)))
2715 (dolist (x keys)
2716 (ses-goto-print (cdr x) (1+ maxcol))
2717 (setq end (point))
2718 (ses-goto-print (cdr x) mincol)
2719 (push (ses-copy-region (point) end) extracts))
2720 (deactivate-mark)
2721 ;;Paste the lines sequentially
2722 (dotimes (x (- maxrow minrow -1))
2723 (ses-goto-print (+ minrow x) mincol)
2724 (ses-set-curcell)
2725 (ses-yank-cells (pop extracts) nil)))))
2727 (defun ses-sort-column-click (event reverse)
2728 (interactive "*e\nP")
2729 (setq event (event-end event))
2730 (select-window (posn-window event))
2731 (setq event (car (posn-col-row event))) ;Click column
2732 (let ((col 0))
2733 (while (and (< col numcols) (> event (ses-col-width col)))
2734 (setq event (- event (ses-col-width col) 1)
2735 col (1+ col)))
2736 (if (>= col numcols)
2737 (ding)
2738 (ses-sort-column (ses-column-letter col) reverse))))
2740 (defun ses-insert-range ()
2741 "Inserts into minibuffer the list of cells currently highlighted in the
2742 spreadsheet."
2743 (interactive "*")
2744 (let (x)
2745 (with-current-buffer (window-buffer minibuffer-scroll-window)
2746 (ses-command-hook) ;For ses-coverage
2747 (ses-check-curcell 'needrange)
2748 (setq x (cdr (macroexpand `(ses-range ,(car curcell) ,(cdr curcell))))))
2749 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
2751 (defun ses-insert-ses-range ()
2752 "Inserts \"(ses-range x y)\" in the minibuffer to represent the currently
2753 highlighted range in the spreadsheet."
2754 (interactive "*")
2755 (let (x)
2756 (with-current-buffer (window-buffer minibuffer-scroll-window)
2757 (ses-command-hook) ;For ses-coverage
2758 (ses-check-curcell 'needrange)
2759 (setq x (format "(ses-range %S %S)" (car curcell) (cdr curcell))))
2760 (insert x)))
2762 (defun ses-insert-range-click (event)
2763 "Mouse version of `ses-insert-range'."
2764 (interactive "*e")
2765 (mouse-set-point event)
2766 (ses-insert-range))
2768 (defun ses-insert-ses-range-click (event)
2769 "Mouse version of `ses-insert-ses-range'."
2770 (interactive "*e")
2771 (mouse-set-point event)
2772 (ses-insert-ses-range))
2775 ;;;----------------------------------------------------------------------------
2776 ;;;; Checking formulas for safety
2777 ;;;----------------------------------------------------------------------------
2779 (defun ses-safe-printer (printer)
2780 "Returns PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
2781 (if (or (stringp printer)
2782 (stringp (car-safe printer))
2783 (not printer)
2784 (ses-warn-unsafe printer 'unsafep-function))
2785 printer
2786 'ses-unsafe))
2788 (defun ses-safe-formula (formula)
2789 "Returns FORMULA if safe, or the substitute formula *unsafe* otherwise."
2790 (if (ses-warn-unsafe formula 'unsafep)
2791 formula
2792 `(ses-unsafe ',formula)))
2794 (defun ses-warn-unsafe (formula checker)
2795 "Applies CHECKER to FORMULA. If result is non-nil, asks user for
2796 confirmation about FORMULA, which might be unsafe. Returns t if formula
2797 is safe or user allows execution anyway. Always returns t if
2798 `safe-functions' is t."
2799 (if (eq safe-functions t)
2801 (setq checker (funcall checker formula))
2802 (if (not checker)
2804 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
2805 formula checker)))))
2808 ;;;----------------------------------------------------------------------------
2809 ;;;; Standard formulas
2810 ;;;----------------------------------------------------------------------------
2812 (defmacro ses-range (from to)
2813 "Expands to a list of cell-symbols for the range. The range automatically
2814 expands to include any new row or column inserted into its middle. The SES
2815 library code specifically looks for the symbol `ses-range', so don't create an
2816 alias for this macro!"
2817 (let (result)
2818 (ses-dorange (cons from to)
2819 (push (ses-cell-symbol row col) result))
2820 (cons 'list result)))
2822 (defun ses-delete-blanks (&rest args)
2823 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
2824 (let (result)
2825 (dolist (cur args)
2826 (and cur (not (eq cur '*skip*))
2827 (push cur result)))
2828 result))
2830 (defun ses+ (&rest args)
2831 "Compute the sum of the arguments, ignoring blanks."
2832 (apply '+ (apply 'ses-delete-blanks args)))
2834 (defun ses-average (list)
2835 "Computes the sum of the numbers in LIST, divided by their length. Blanks
2836 are ignored. Result is always floating-point, even if all args are integers."
2837 (setq list (apply 'ses-delete-blanks list))
2838 (/ (float (apply '+ list)) (length list)))
2840 (defmacro ses-select (fromrange test torange)
2841 "Select cells in FROMRANGE that are `equal' to TEST. For each match, return
2842 the corresponding cell from TORANGE. The ranges are macroexpanded but not
2843 evaluated so they should be either (ses-range BEG END) or (list ...). The
2844 TEST is evaluated."
2845 (setq fromrange (cdr (macroexpand fromrange))
2846 torange (cdr (macroexpand torange))
2847 test (eval test))
2848 (or (= (length fromrange) (length torange))
2849 (error "ses-select: Ranges not same length"))
2850 (let (result)
2851 (dolist (x fromrange)
2852 (if (equal test (symbol-value x))
2853 (push (car torange) result))
2854 (setq torange (cdr torange)))
2855 (cons 'list result)))
2857 ;;All standard formulas are safe
2858 (dolist (x '(ses-range ses-delete-blanks ses+ ses-average ses-select))
2859 (put x 'side-effect-free t))
2862 ;;;----------------------------------------------------------------------------
2863 ;;;; Standard print functions
2864 ;;;----------------------------------------------------------------------------
2866 ;;These functions use the variables 'row' and 'col' that are
2867 ;;dynamically bound by ses-print-cell. We define these varables at
2868 ;;compile-time to make the compiler happy.
2869 (eval-when-compile
2870 (make-local-variable 'row)
2871 (make-local-variable 'col)
2872 ;;Don't use setq -- that gives a "free variable" compiler warning
2873 (set 'row nil)
2874 (set 'col nil))
2876 (defun ses-center (value &optional span fill)
2877 "Print VALUE, centered within column. FILL is the fill character for
2878 centering (default = space). SPAN indicates how many additional rightward
2879 columns to include in width (default = 0)."
2880 (let ((printer (or (ses-col-printer col) default-printer))
2881 (width (ses-col-width col))
2882 half)
2883 (or fill (setq fill ? ))
2884 (or span (setq span 0))
2885 (setq value (ses-call-printer printer value))
2886 (dotimes (x span)
2887 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
2888 (setq width (- width (length value)))
2889 (if (<= width 0)
2890 value ;Too large for field, anyway
2891 (setq half (make-string (/ width 2) fill))
2892 (concat half value half
2893 (if (> (% width 2) 0) (char-to-string fill))))))
2895 (defun ses-center-span (value &optional fill)
2896 "Print VALUE, centered within the span that starts in the current column
2897 and continues until the next nonblank column. FILL specifies the fill
2898 character (default = space)."
2899 (let ((end (1+ col)))
2900 (while (and (< end numcols)
2901 (memq (ses-cell-value row end) '(nil *skip*)))
2902 (setq end (1+ end)))
2903 (ses-center value (- end col 1) fill)))
2905 (defun ses-dashfill (value &optional span)
2906 "Print VALUE centered using dashes. SPAN indicates how many rightward
2907 columns to include in width (default = 0)."
2908 (ses-center value span ?-))
2910 (defun ses-dashfill-span (value)
2911 "Print VALUE, centered using dashes within the span that starts in the
2912 current column and continues until the next nonblank column."
2913 (ses-center-span value ?-))
2915 (defun ses-tildefill-span (value)
2916 "Print VALUE, centered using tildes within the span that starts in the
2917 current column and continues until the next nonblank column."
2918 (ses-center-span value ?~))
2920 (defun ses-unsafe (value)
2921 "Substitute for an unsafe formula or printer"
2922 (error "Unsafe formula or printer"))
2924 ;;All standard printers are safe, including ses-unsafe!
2925 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
2926 (put x 'side-effect-free t))
2928 (provide 'ses)
2930 ;; ses.el ends here.