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