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