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