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