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