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