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