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