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