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