mail/mailabbrev.el (mail-abbrev-expand-hook): Work for a mail aliasee that holds...
[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
bd93e3e1
JY
1273(defun ses-widen ()
1274 "Turn off narrowing, to be reenabled at end of command loop."
e5c2edf7 1275 (if (buffer-narrowed-p)
bd93e3e1
JY
1276 (setq ses--deferred-narrow t))
1277 (widen))
1278
7ed9159a 1279(defun ses-goto-data (def &optional col)
94be2532
JY
1280 "Move point to data area for (DEF,COL). If DEF is a row
1281number, COL is the column number for a data cell -- otherwise DEF
1282is one of the symbols ses--col-widths, ses--col-printers,
1283ses--default-printer, ses--numrows, or ses--numcols."
bd93e3e1 1284 (ses-widen)
2bb63e81 1285 (let ((inhibit-point-motion-hooks t)) ; In case intangible attrs are wrong.
7ed9159a 1286 (if col
2bb63e81 1287 ;; It's a cell.
ddd1c214
JY
1288 (progn
1289 (goto-char ses--data-marker)
1290 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
2bb63e81 1291 ;; Convert def-symbol to offset.
ddd1c214
JY
1292 (setq def (plist-get ses-paramlines-plist def))
1293 (or def (signal 'args-out-of-range nil))
1294 (goto-char ses--params-marker)
1295 (forward-line def))))
7ed9159a
JY
1296
1297(defun ses-set-parameter (def value &optional elem)
58cf70d3
SM
1298 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1299See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1300If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
7ed9159a 1301 (save-excursion
2bb63e81
VB
1302 ;; We call ses-goto-data early, using the old values of numrows and numcols
1303 ;; in case one of them is being changed.
7ed9159a 1304 (ses-goto-data def)
7ed9159a 1305 (let ((inhibit-read-only t)
c21c3d89 1306 (fmt (plist-get '(ses--col-widths "(ses-column-widths %S)"
94be2532
JY
1307 ses--col-printers "(ses-column-printers %S)"
1308 ses--default-printer "(ses-default-printer %S)"
1309 ses--header-row "(ses-header-row %S)"
1310 ses--file-format " %S ;SES file-format"
1311 ses--numrows " %S ;numrows"
1312 ses--numcols " %S ;numcols")
bd93e3e1
JY
1313 def))
1314 oldval)
1315 (if elem
1316 (progn
1317 (setq oldval (aref (symbol-value def) elem))
1318 (aset (symbol-value def) elem value))
1319 (setq oldval (symbol-value def))
1320 (set def value))
2bb63e81 1321 ;; Special undo since it's outside the narrowed buffer.
bd93e3e1
JY
1322 (let (buffer-undo-list)
1323 (delete-region (point) (line-end-position))
1324 (insert (format fmt (symbol-value def))))
1325 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1326
7ed9159a
JY
1327
1328(defun ses-write-cells ()
58cf70d3
SM
1329 "Write cells in `ses--deferred-write' from local variables to data area.
1330Newlines in the data are escaped."
7ed9159a
JY
1331 (let* ((inhibit-read-only t)
1332 (print-escape-newlines t)
1333 rowcol row col cell sym formula printer text)
1334 (setq ses-start-time (float-time))
1335 (with-temp-message " "
1336 (save-excursion
94be2532 1337 (while ses--deferred-write
7ed9159a 1338 (ses-time-check "Writing... (%d cells left)"
94be2532
JY
1339 '(length ses--deferred-write))
1340 (setq rowcol (pop ses--deferred-write)
7ed9159a
JY
1341 row (car rowcol)
1342 col (cdr rowcol)
1343 cell (ses-get-cell row col)
1344 sym (ses-cell-symbol cell)
1345 formula (ses-cell-formula cell)
1346 printer (ses-cell-printer cell))
1347 (if (eq (car-safe formula) 'ses-safe-formula)
1348 (setq formula (cadr formula)))
1349 (if (eq (car-safe printer) 'ses-safe-printer)
1350 (setq printer (cadr printer)))
4bdf2ad2 1351 ;; This is noticeably faster than (format "%S %S %S %S %S")
7ed9159a
JY
1352 (setq text (concat "(ses-cell "
1353 (symbol-name sym)
1354 " "
1355 (prin1-to-string (symbol-value sym))
1356 " "
1357 (prin1-to-string formula)
1358 " "
1359 (prin1-to-string printer)
1360 " "
1361 (if (atom (ses-cell-references cell))
1362 "nil"
1363 (concat "("
1364 (mapconcat 'symbol-name
1365 (ses-cell-references cell)
1366 " ")
1367 ")"))
1368 ")"))
1369 (ses-goto-data row col)
1370 (delete-region (point) (line-end-position))
1371 (insert text)))
1372 (message " "))))
1373
1374
58cf70d3
SM
1375;;----------------------------------------------------------------------------
1376;; Formula relocation
1377;;----------------------------------------------------------------------------
7ed9159a
JY
1378
1379(defun ses-formula-references (formula &optional result-so-far)
4bdf2ad2 1380 "Produce a list of symbols for cells that this FORMULA's value
90ca8b49
VB
1381refers to. For recursive calls, RESULT-SO-FAR is the list being
1382constructed, or t to get a wrong-type-argument error when the
1383first reference is found."
1384 (if (ses-sym-rowcol formula)
1385 ;;Entire formula is one symbol
1386 (add-to-list 'result-so-far formula)
1387 (if (consp formula)
1388 (cond
1389 ((eq (car formula) 'ses-range)
1390 (dolist (cur
1391 (cdr (funcall 'macroexpand
1392 (list 'ses-range (nth 1 formula)
1393 (nth 2 formula)))))
1394 (add-to-list 'result-so-far cur)))
1395 ((null (eq (car formula) 'quote))
1396 ;;Recursive call for subformulas
1397 (dolist (cur formula)
1398 (setq result-so-far (ses-formula-references cur result-so-far))))
1399 (t
1400 ;;Ignore other stuff
1401 ))
1402 ;; other type of atom are ignored
1403 ))
1404 result-so-far)
7ed9159a 1405
ddd1c214 1406(defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
4bdf2ad2 1407 "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
ddd1c214
JY
1408COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1409by (ROWINCR,COLINCR)."
1410 (let ((row (car rowcol))
1411 (col (cdr rowcol)))
1412 (if (or (< row startrow) (< col startcol))
1413 sym
1414 (setq row (+ row rowincr)
1415 col (+ col colincr))
1416 (if (and (>= row startrow) (>= col startcol)
1417 (< row ses--numrows) (< col ses--numcols))
1418 ;;Relocate this variable
1419 (ses-create-cell-symbol row col)
1420 ;;Delete reference to a deleted cell
1421 nil))))
1422
7ed9159a
JY
1423(defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1424 "Produce a copy of FORMULA where all symbols that refer to cells in row
4bdf2ad2
VB
1425STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
1426and COLINCR. STARTROW and STARTCOL are 0-based. Example:
7ed9159a
JY
1427 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1428 => (+ A1 B2 C4)
1429If ROWINCR or COLINCR is negative, references to cells being deleted are
1430removed. Example:
1431 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1432 => (+ A1 C3)
1433Sets `ses-relocate-return' to 'delete if cell-references were removed."
1434 (let (rowcol result)
1435 (if (or (atom formula) (eq (car formula) 'quote))
4bdf2ad2
VB
1436 (if (and (setq rowcol (ses-sym-rowcol formula))
1437 (string-match "\\`[A-Z]+[0-9]+\\'" (symbol-name formula)))
7ed9159a
JY
1438 (ses-relocate-symbol formula rowcol
1439 startrow startcol rowincr colincr)
2bb63e81 1440 formula) ; Pass through as-is.
7ed9159a
JY
1441 (dolist (cur formula)
1442 (setq rowcol (ses-sym-rowcol cur))
1443 (cond
1444 (rowcol
1445 (setq cur (ses-relocate-symbol cur rowcol
1446 startrow startcol rowincr colincr))
1447 (if cur
1448 (push cur result)
2bb63e81
VB
1449 ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
1450 ;; don't change the flag if it's already 'range, since range implies
1451 ;; 'delete.
7ed9159a
JY
1452 (unless ses-relocate-return
1453 (setq ses-relocate-return 'delete))))
1454 ((eq (car-safe cur) 'ses-range)
1455 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1456 (if cur
1457 (push cur result)))
1458 ((or (atom cur) (eq (car cur) 'quote))
2bb63e81 1459 ;; Constants pass through unchanged.
7ed9159a
JY
1460 (push cur result))
1461 (t
2bb63e81 1462 ;; Recursively copy and alter subformulas.
7ed9159a
JY
1463 (push (ses-relocate-formula cur startrow startcol
1464 rowincr colincr)
1465 result))))
1466 (nreverse result))))
1467
7ed9159a
JY
1468(defun ses-relocate-range (range startrow startcol rowincr colincr)
1469 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1470at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1471new range, or nil if the entire range is deleted. If new rows are being added
1472just beyond the end of a row range, or new columns just beyond a column range,
1473the new rows/columns will be added to the range. Sets `ses-relocate-return'
1474if the range was altered."
1475 (let* ((minorig (cadr range))
1476 (minrowcol (ses-sym-rowcol minorig))
1477 (min (ses-relocate-symbol minorig minrowcol
1478 startrow startcol
1479 rowincr colincr))
1480 (maxorig (nth 2 range))
1481 (maxrowcol (ses-sym-rowcol maxorig))
1482 (max (ses-relocate-symbol maxorig maxrowcol
1483 startrow startcol
1484 rowincr colincr))
1485 field)
1486 (cond
1487 ((and (not min) (not max))
2bb63e81 1488 (setq range nil)) ; The entire range is deleted.
7ed9159a 1489 ((zerop colincr)
2bb63e81 1490 ;; Inserting or deleting rows.
7ed9159a
JY
1491 (setq field 'car)
1492 (if (not min)
2bb63e81 1493 ;; Chopped off beginning of range.
7ed9159a
JY
1494 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1495 ses-relocate-return 'range))
1496 (if (not max)
1497 (if (> rowincr 0)
2bb63e81 1498 ;; Trying to insert a nonexistent row.
94be2532
JY
1499 (setq max (ses-create-cell-symbol (1- ses--numrows)
1500 (cdr minrowcol)))
2bb63e81 1501 ;; End of range is being deleted.
7ed9159a
JY
1502 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1503 ses-relocate-return 'range))
1504 (and (> rowincr 0)
1505 (= (car maxrowcol) (1- startrow))
1506 (= (cdr minrowcol) (cdr maxrowcol))
2bb63e81 1507 ;; Insert after ending row of vertical range --- include it.
7ed9159a
JY
1508 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1509 (cdr maxrowcol))))))
1510 (t
2bb63e81 1511 ;; Inserting or deleting columns.
7ed9159a
JY
1512 (setq field 'cdr)
1513 (if (not min)
2bb63e81 1514 ;; Chopped off beginning of range.
7ed9159a
JY
1515 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1516 ses-relocate-return 'range))
1517 (if (not max)
1518 (if (> colincr 0)
2bb63e81 1519 ;; Trying to insert a nonexistent column.
94be2532
JY
1520 (setq max (ses-create-cell-symbol (car maxrowcol)
1521 (1- ses--numcols)))
2bb63e81 1522 ;; End of range is being deleted.
7ed9159a
JY
1523 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1524 ses-relocate-return 'range))
1525 (and (> colincr 0)
1526 (= (cdr maxrowcol) (1- startcol))
1527 (= (car minrowcol) (car maxrowcol))
2bb63e81 1528 ;; Insert after ending column of horizontal range --- include it.
7ed9159a
JY
1529 (setq max (ses-create-cell-symbol (car maxrowcol)
1530 (+ startcol colincr -1)))))))
1531 (when range
1532 (if (/= (- (funcall field maxrowcol)
1533 (funcall field minrowcol))
1534 (- (funcall field (ses-sym-rowcol max))
1535 (funcall field (ses-sym-rowcol min))))
2bb63e81 1536 ;; This range has changed size.
7ed9159a 1537 (setq ses-relocate-return 'range))
a464a6c7 1538 `(ses-range ,min ,max ,@(cl-cdddr range)))))
7ed9159a
JY
1539
1540(defun ses-relocate-all (minrow mincol rowincr colincr)
1541 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1542the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1543to each symbol."
1544 (let (reform)
4bdf2ad2 1545 (let (mycell newval xrow)
7c018923 1546 (dotimes-with-progress-reporter
90ca8b49 1547 (row ses--numrows) "Relocating formulas..."
94be2532 1548 (dotimes (col ses--numcols)
7ed9159a
JY
1549 (setq ses-relocate-return nil
1550 mycell (ses-get-cell row col)
1551 newval (ses-relocate-formula (ses-cell-formula mycell)
4bdf2ad2
VB
1552 minrow mincol rowincr colincr)
1553 xrow (- row rowincr))
7ed9159a
JY
1554 (ses-set-cell row col 'formula newval)
1555 (if (eq ses-relocate-return 'range)
2bb63e81
VB
1556 ;; This cell contains a (ses-range X Y) where a cell has been
1557 ;; inserted or deleted in the middle of the range.
7ed9159a
JY
1558 (push (cons row col) reform))
1559 (if ses-relocate-return
2bb63e81
VB
1560 ;; This cell referred to a cell that's been deleted or is no
1561 ;; longer part of the range. We can't fix that now because
1562 ;; reference lists cells have been partially updated.
94be2532 1563 (add-to-list 'ses--deferred-recalc
7ed9159a
JY
1564 (ses-create-cell-symbol row col)))
1565 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1566 minrow mincol rowincr colincr))
1567 (ses-set-cell row col 'references newval)
1568 (and (>= row minrow) (>= col mincol)
4bdf2ad2
VB
1569 (let ((sym (ses-cell-symbol row col))
1570 (xcol (- col colincr)))
1571 (if (and
1572 sym
1573 (>= xrow 0)
1574 (>= xcol 0)
1575 (null (eq sym
1576 (ses-create-cell-symbol xrow xcol))))
1577 ;; This is a renamed cell, do not update the cell
1578 ;; name, but just update the coordinate property.
1579 (put sym 'ses-cell (cons row col))
1580 (ses-set-cell row col 'symbol
1581 (setq sym (ses-create-cell-symbol row col)))
1582 (unless (and (boundp sym) (local-variable-p sym))
1583 (set (make-local-variable sym) nil)
1584 (put sym 'ses-cell (cons row col)))))) )))
2bb63e81 1585 ;; Relocate the cell values.
7ed9159a
JY
1586 (let (oldval myrow mycol xrow xcol)
1587 (cond
1588 ((and (<= rowincr 0) (<= colincr 0))
2bb63e81 1589 ;; Deletion of rows and/or columns.
7c018923 1590 (dotimes-with-progress-reporter
2bb63e81 1591 (row (- ses--numrows minrow)) "Relocating variables..."
7ed9159a 1592 (setq myrow (+ row minrow))
94be2532 1593 (dotimes (col (- ses--numcols mincol))
7ed9159a
JY
1594 (setq mycol (+ col mincol)
1595 xrow (- myrow rowincr)
1596 xcol (- mycol colincr))
4bdf2ad2
VB
1597 (let ((sym (ses-cell-symbol myrow mycol))
1598 (xsym (ses-create-cell-symbol xrow xcol)))
1599 ;; Make the value relocation only when if the cell is not
1600 ;; a renamed cell. Otherwise this is not needed.
1601 (and (eq sym xsym)
1602 (ses-set-cell myrow mycol 'value
1603 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1604 (ses-cell-value xrow xcol)
1605 ;;Cell is off the end of the array
1606 (symbol-value xsym))))))))
1607
7ed9159a 1608 ((and (wholenump rowincr) (wholenump colincr))
2bb63e81 1609 ;; Insertion of rows and/or columns. Run the loop backwards.
94be2532
JY
1610 (let ((disty (1- ses--numrows))
1611 (distx (1- ses--numcols))
7ed9159a 1612 myrow mycol)
7c018923
SM
1613 (dotimes-with-progress-reporter
1614 (row (- ses--numrows minrow)) "Relocating variables..."
7ed9159a 1615 (setq myrow (- disty row))
94be2532 1616 (dotimes (col (- ses--numcols mincol))
7ed9159a
JY
1617 (setq mycol (- distx col)
1618 xrow (- myrow rowincr)
1619 xcol (- mycol colincr))
1620 (if (or (< xrow minrow) (< xcol mincol))
2bb63e81 1621 ;; Newly-inserted value.
7ed9159a 1622 (setq oldval nil)
2bb63e81 1623 ;; Transfer old value.
7ed9159a
JY
1624 (setq oldval (ses-cell-value xrow xcol)))
1625 (ses-set-cell myrow mycol 'value oldval)))
2bb63e81 1626 t)) ; Make testcover happy by returning non-nil here.
7ed9159a
JY
1627 (t
1628 (error "ROWINCR and COLINCR must have the same sign"))))
2bb63e81
VB
1629 ;; Reconstruct reference lists for cells that contain ses-ranges that have
1630 ;; changed size.
7ed9159a
JY
1631 (when reform
1632 (message "Fixing ses-ranges...")
1633 (let (row col)
1634 (setq ses-start-time (float-time))
1635 (while reform
1636 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1637 (setq row (caar reform)
1638 col (cdar reform)
1639 reform (cdr reform))
1640 (ses-cell-set-formula row col (ses-cell-formula row col))))
1641 (message nil))))
1642
1643
58cf70d3
SM
1644;;----------------------------------------------------------------------------
1645;; Undo control
1646;;----------------------------------------------------------------------------
7ed9159a 1647
7ed9159a 1648(defun ses-begin-change ()
137e4002 1649 "For undo, remember point before we start changing hidden stuff."
7ed9159a
JY
1650 (let ((inhibit-read-only t))
1651 (insert-and-inherit "X")
1652 (delete-region (1- (point)) (point))))
1653
1654(defun ses-set-with-undo (sym newval)
1655 "Like set, but undoable. Result is t if value has changed."
2bb63e81
VB
1656 ;; We try to avoid adding redundant entries to the undo list, but this is
1657 ;; unavoidable for strings because equal ignores text properties and there's
1658 ;; no easy way to get the whole property list to see if it's different!
7ed9159a
JY
1659 (unless (and (boundp sym)
1660 (equal (symbol-value sym) newval)
1661 (not (stringp newval)))
1662 (push (if (boundp sym)
63f3351c
KS
1663 `(apply ses-set-with-undo ,sym ,(symbol-value sym))
1664 `(apply ses-unset-with-undo ,sym))
7ed9159a
JY
1665 buffer-undo-list)
1666 (set sym newval)
1667 t))
1668
1669(defun ses-unset-with-undo (sym)
1670 "Set SYM to be unbound. This is undoable."
2bb63e81 1671 (when (1value (boundp sym)) ; Always bound, except after a programming error.
63f3351c 1672 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
7ed9159a
JY
1673 (makunbound sym)))
1674
1675(defun ses-aset-with-undo (array idx newval)
4bdf2ad2
VB
1676 "Like `aset', but undoable.
1677Result is t if element has changed."
7ed9159a 1678 (unless (equal (aref array idx) newval)
2bb63e81
VB
1679 (push `(apply ses-aset-with-undo ,array ,idx
1680 ,(aref array idx)) buffer-undo-list)
7ed9159a
JY
1681 (aset array idx newval)
1682 t))
1683
1684
58cf70d3
SM
1685;;----------------------------------------------------------------------------
1686;; Startup for major mode
1687;;----------------------------------------------------------------------------
7ed9159a 1688
7ed9159a 1689(defun ses-load ()
4bdf2ad2
VB
1690 "Parse the current buffer and set up buffer-local variables.
1691Does not execute cell formulas or print functions."
7ed9159a 1692 (widen)
2bb63e81 1693 ;; Read our global parameters, which should be a 3-element list.
7ed9159a 1694 (goto-char (point-max))
58cf70d3 1695 (search-backward ";; Local Variables:\n" nil t)
7ed9159a 1696 (backward-list 1)
ddd1c214 1697 (setq ses--params-marker (point-marker))
58cf70d3 1698 (let ((params (condition-case nil (read (current-buffer)) (error nil))))
7ed9159a
JY
1699 (or (and (= (safe-length params) 3)
1700 (numberp (car params))
1701 (numberp (cadr params))
bd93e3e1 1702 (>= (cadr params) 0)
7ed9159a
JY
1703 (numberp (nth 2 params))
1704 (> (nth 2 params) 0))
1705 (error "Invalid SES file"))
94be2532
JY
1706 (setq ses--file-format (car params)
1707 ses--numrows (cadr params)
1708 ses--numcols (nth 2 params))
1709 (when (= ses--file-format 1)
2bb63e81 1710 (let (buffer-undo-list) ; This is not undoable.
94be2532 1711 (ses-goto-data 'ses--header-row)
7ed9159a 1712 (insert "(ses-header-row 0)\n")
94be2532 1713 (ses-set-parameter 'ses--file-format 2)
7ed9159a 1714 (message "Upgrading from SES-1 file format")))
94be2532 1715 (or (= ses--file-format 2)
e20bb629 1716 (error "This file needs a newer version of the SES library code"))
2bb63e81 1717 ;; Initialize cell array.
94be2532
JY
1718 (setq ses--cells (make-vector ses--numrows nil))
1719 (dotimes (row ses--numrows)
1720 (aset ses--cells row (make-vector ses--numcols nil))))
2bb63e81 1721 ;; Skip over print area, which we assume is correct.
94be2532
JY
1722 (goto-char (point-min))
1723 (forward-line ses--numrows)
7ed9159a
JY
1724 (or (looking-at ses-print-data-boundary)
1725 (error "Missing marker between print and data areas"))
ddd1c214
JY
1726 (forward-char 1)
1727 (setq ses--data-marker (point-marker))
1728 (forward-char (1- (length ses-print-data-boundary)))
2bb63e81 1729 ;; Initialize printer and symbol lists.
7ed9159a 1730 (mapc 'ses-printer-record ses-standard-printer-functions)
94be2532 1731 (setq ses--symbolic-formulas nil)
2bb63e81 1732 ;; Load cell definitions.
94be2532
JY
1733 (dotimes (row ses--numrows)
1734 (dotimes (col ses--numcols)
7ed9159a 1735 (let* ((x (read (current-buffer)))
4bdf2ad2 1736 (sym (car-safe (cdr-safe x))))
7ed9159a
JY
1737 (or (and (looking-at "\n")
1738 (eq (car-safe x) 'ses-cell)
4bdf2ad2 1739 (ses-create-cell-variable sym row col))
7ed9159a
JY
1740 (error "Cell-def error"))
1741 (eval x)))
1742 (or (looking-at "\n\n")
1743 (error "Missing blank line between rows")))
2bb63e81 1744 ;; Load global parameters.
7ed9159a
JY
1745 (let ((widths (read (current-buffer)))
1746 (n1 (char-after (point)))
1747 (printers (read (current-buffer)))
1748 (n2 (char-after (point)))
1749 (def-printer (read (current-buffer)))
1750 (n3 (char-after (point)))
1751 (head-row (read (current-buffer)))
1752 (n4 (char-after (point))))
1753 (or (and (eq (car-safe widths) 'ses-column-widths)
1754 (= n1 ?\n)
1755 (eq (car-safe printers) 'ses-column-printers)
1756 (= n2 ?\n)
1757 (eq (car-safe def-printer) 'ses-default-printer)
1758 (= n3 ?\n)
1759 (eq (car-safe head-row) 'ses-header-row)
1760 (= n4 ?\n))
1761 (error "Invalid SES global parameters"))
1762 (1value (eval widths))
1763 (1value (eval def-printer))
1764 (1value (eval printers))
1765 (1value (eval head-row)))
2bb63e81 1766 ;; Should be back at global-params.
7ed9159a
JY
1767 (forward-char 1)
1768 (or (looking-at (replace-regexp-in-string "1" "[0-9]+"
1769 ses-initial-global-parameters))
1770 (error "Problem with column-defs or global-params"))
2bb63e81 1771 ;; Check for overall newline count in definitions area.
7ed9159a
JY
1772 (forward-line 3)
1773 (let ((start (point)))
94be2532 1774 (ses-goto-data 'ses--numrows)
7ed9159a
JY
1775 (or (= (point) start)
1776 (error "Extraneous newlines someplace?"))))
1777
1778(defun ses-setup ()
1779 "Set up for display of only the printed cell values.
1780
1781Narrows the buffer to show only the print area. Gives it `read-only' and
1782`intangible' properties. Sets up highlighting for current cell."
1783 (interactive)
94be2532 1784 (let ((end (point-min))
7ed9159a 1785 (inhibit-read-only t)
c0c30dd1 1786 (inhibit-point-motion-hooks t)
7ed9159a
JY
1787 (was-modified (buffer-modified-p))
1788 pos sym)
2bb63e81
VB
1789 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1790 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
94be2532 1791 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
2bb63e81
VB
1792 ;; The print area is read-only (except for our special commands) and uses a
1793 ;; special keymap.
94be2532
JY
1794 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1795 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
2bb63e81
VB
1796 ;; For the beginning of the buffer, we want the read-only and keymap
1797 ;; attributes to be inherited from the first character.
94be2532 1798 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
2bb63e81
VB
1799 ;; Create intangible properties, which also indicate which cell the text
1800 ;; came from.
7c018923 1801 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
94be2532 1802 (dotimes (col ses--numcols)
7ed9159a
JY
1803 (setq pos end
1804 sym (ses-cell-symbol row col))
2bb63e81 1805 ;; Include skipped cells following this one.
94be2532 1806 (while (and (< col (1- ses--numcols))
7ed9159a
JY
1807 (eq (ses-cell-value row (1+ col)) '*skip*))
1808 (setq end (+ end (ses-col-width col) 1)
1809 col (1+ col)))
c0c30dd1
JY
1810 (setq end (save-excursion
1811 (goto-char pos)
1812 (move-to-column (+ (current-column) (- end pos)
1813 (ses-col-width col)))
1814 (if (eolp)
1815 (+ end (ses-col-width col) 1)
1816 (forward-char)
1817 (point))))
7ed9159a 1818 (put-text-property pos end 'intangible sym)))
2bb63e81 1819 ;; Adding these properties did not actually alter the text.
7ed9159a 1820 (unless was-modified
58cf70d3 1821 (restore-buffer-modified-p nil)
7ed9159a
JY
1822 (buffer-disable-undo)
1823 (buffer-enable-undo)))
2bb63e81
VB
1824 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1825 ;; because column A must be at least 1 column wide.
94be2532
JY
1826 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1827 (overlay-put ses--curcell-overlay 'face 'underline))
7ed9159a
JY
1828
1829(defun ses-cleanup ()
ae59e888
SM
1830 "Cleanup when changing a buffer from SES mode to something else.
1831Delete overlays, remove special text properties."
7ed9159a
JY
1832 (widen)
1833 (let ((inhibit-read-only t)
2bb63e81
VB
1834 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1835 ;; user "the file is modified, do you really want to make modifications
1836 ;; to this buffer", where the "modifications" refer to the irrelevant
1837 ;; set-text-properties below.
1838 (buffer-file-name nil)
58cf70d3 1839 (was-modified (buffer-modified-p)))
2bb63e81 1840 ;; Delete read-only, keymap, and intangible properties.
94be2532 1841 (set-text-properties (point-min) (point-max) nil)
2bb63e81 1842 ;; Delete overlay.
94be2532 1843 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
7ed9159a 1844 (unless was-modified
ae59e888 1845 (restore-buffer-modified-p nil))))
7ed9159a
JY
1846
1847;;;###autoload
1848(defun ses-mode ()
94be2532 1849 "Major mode for Simple Emacs Spreadsheet.
e27dad25 1850See \"ses-example.ses\" (in `data-directory') for more info.
7ed9159a
JY
1851
1852Key definitions:
1853\\{ses-mode-map}
1854These key definitions are active only in the print area (the visible part):
1855\\{ses-mode-print-map}
1856These are active only in the minibuffer, when entering or editing a formula:
1857\\{ses-mode-edit-map}"
1858 (interactive)
94be2532
JY
1859 (unless (and (boundp 'ses--deferred-narrow)
1860 (eq ses--deferred-narrow 'ses-mode))
7ed9159a 1861 (kill-all-local-variables)
90ca8b49 1862 (ses-set-localvars)
7ed9159a
JY
1863 (setq major-mode 'ses-mode
1864 mode-name "SES"
1865 next-line-add-newlines nil
1866 truncate-lines t
2bb63e81 1867 ;; SES deliberately puts lots of trailing whitespace in its buffer.
7ed9159a 1868 show-trailing-whitespace nil
2bb63e81 1869 ;; Cell ranges do not work reasonably without this.
c0c30dd1 1870 transient-mark-mode t
2bb63e81
VB
1871 ;; Not to use tab characters for safe (tabs may do bad for column
1872 ;; calculation).
c0c30dd1 1873 indent-tabs-mode nil)
7ed9159a
JY
1874 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1875 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
90ca8b49 1876 (setq header-line-format '(:eval (progn
94be2532
JY
1877 (when (/= (window-hscroll)
1878 ses--header-hscroll)
2bb63e81
VB
1879 ;; Reset ses--header-hscroll first,
1880 ;; to avoid recursion problems when
1881 ;; debugging ses-create-header-string
94be2532
JY
1882 (setq ses--header-hscroll
1883 (window-hscroll))
1884 (ses-create-header-string))
1885 ses--header-string)))
7ed9159a
JY
1886 (let ((was-empty (zerop (buffer-size)))
1887 (was-modified (buffer-modified-p)))
1888 (save-excursion
1889 (if was-empty
2bb63e81 1890 ;; Initialize buffer to contain one cell, for now.
7ed9159a
JY
1891 (insert ses-initial-file-contents))
1892 (ses-load)
1893 (ses-setup))
1894 (when was-empty
2bb63e81
VB
1895 (unless (equal ses-initial-default-printer
1896 (1value ses--default-printer))
7ed9159a
JY
1897 (1value (ses-read-default-printer ses-initial-default-printer)))
1898 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1899 (1value (ses-set-column-width 0 ses-initial-column-width)))
1900 (ses-set-curcell)
94be2532 1901 (if (> (car ses-initial-size) (1value ses--numrows))
7ed9159a 1902 (1value (ses-insert-row (1- (car ses-initial-size)))))
94be2532 1903 (if (> (cdr ses-initial-size) (1value ses--numcols))
7ed9159a
JY
1904 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1905 (ses-write-cells)
94be2532 1906 (restore-buffer-modified-p was-modified)
7ed9159a
JY
1907 (buffer-disable-undo)
1908 (buffer-enable-undo)
94be2532 1909 (goto-char (point-min))))
7ed9159a 1910 (use-local-map ses-mode-map)
2bb63e81
VB
1911 ;; Set the deferred narrowing flag (we can't narrow until after
1912 ;; after-find-file completes). If .ses is on the auto-load alist and the
1913 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
1914 ;; special flag to detect this (will be reset by ses-command-hook). For
1915 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
1916 ;; so use an idle timer to make sure.
94be2532 1917 (setq ses--deferred-narrow 'ses-mode)
7ed9159a
JY
1918 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1919 (run-with-idle-timer 0.01 nil 'ses-command-hook)
859540e3 1920 (run-mode-hooks 'ses-mode-hook)))
7ed9159a
JY
1921
1922(put 'ses-mode 'mode-class 'special)
1923
1924(defun ses-command-hook ()
1925 "Invoked from `post-command-hook'. If point has moved to a different cell,
1926moves the underlining overlay. Performs any recalculations or cell-data
1927writes that have been deferred. If buffer-narrowing has been deferred,
1928narrows the buffer now."
1929 (condition-case err
2bb63e81 1930 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
94be2532 1931 (when ses--deferred-recalc
2bb63e81
VB
1932 ;; We reset the deferred list before starting on the recalc --- in
1933 ;; case of error, we don't want to retry the recalc after every
1934 ;; keystroke!
90ca8b49 1935 (ses-initialize-Dijkstra-attempt)
94be2532
JY
1936 (let ((old ses--deferred-recalc))
1937 (setq ses--deferred-recalc nil)
7ed9159a 1938 (ses-update-cells old)))
bd93e3e1 1939 (when ses--deferred-write
2bb63e81
VB
1940 ;; We don't reset the deferred list before starting --- the most
1941 ;; likely error is keyboard-quit, and we do want to keep trying these
1942 ;; writes after a quit.
bd93e3e1
JY
1943 (ses-write-cells)
1944 (push '(apply ses-widen) buffer-undo-list))
94be2532 1945 (when ses--deferred-narrow
2bb63e81
VB
1946 ;; We're not allowed to narrow the buffer until after-find-file has
1947 ;; read the local variables at the end of the file. Now it's safe to
1948 ;; do the narrowing.
ddd1c214 1949 (narrow-to-region (point-min) ses--data-marker)
94be2532 1950 (setq ses--deferred-narrow nil))
37269466 1951 ;; Update the mode line.
94be2532 1952 (let ((oldcell ses--curcell))
7ed9159a 1953 (ses-set-curcell)
94be2532 1954 (unless (eq ses--curcell oldcell)
7ed9159a 1955 (cond
94be2532 1956 ((not ses--curcell)
7ed9159a 1957 (setq mode-line-process nil))
94be2532
JY
1958 ((atom ses--curcell)
1959 (setq mode-line-process (list " cell "
1960 (symbol-name ses--curcell))))
7ed9159a
JY
1961 (t
1962 (setq mode-line-process (list " range "
94be2532 1963 (symbol-name (car ses--curcell))
7ed9159a 1964 "-"
94be2532 1965 (symbol-name (cdr ses--curcell))))))
7ed9159a 1966 (force-mode-line-update)))
2bb63e81 1967 ;; Use underline overlay for single-cells only, turn off otherwise.
94be2532
JY
1968 (if (listp ses--curcell)
1969 (move-overlay ses--curcell-overlay 2 2)
7ed9159a 1970 (let ((next (next-single-property-change (point) 'intangible)))
94be2532 1971 (move-overlay ses--curcell-overlay (point) (1- next))))
7ed9159a 1972 (when (not (pos-visible-in-window-p))
2bb63e81 1973 ;; Scrolling will happen later.
7ed9159a 1974 (run-with-idle-timer 0.01 nil 'ses-command-hook)
94be2532 1975 (setq ses--curcell t)))
2bb63e81 1976 ;; Prevent errors in this post-command-hook from silently erasing the hook!
7ed9159a
JY
1977 (error
1978 (unless executing-kbd-macro
1979 (ding))
8a26c165 1980 (message "%s" (error-message-string err))))
2bb63e81 1981 nil) ; Make coverage-tester happy.
7ed9159a
JY
1982
1983(defun ses-create-header-string ()
58cf70d3
SM
1984 "Set up `ses--header-string' as the buffer's header line.
1985Based on the current set of columns and `window-hscroll' position."
1986 (let ((totwidth (- (window-hscroll)))
1987 result width x)
2bb63e81 1988 ;; Leave room for the left-side fringe and scrollbar.
58cf70d3 1989 (push (propertize " " 'display '((space :align-to 0))) result)
94be2532 1990 (dotimes (col ses--numcols)
7ed9159a
JY
1991 (setq width (ses-col-width col)
1992 totwidth (+ totwidth width 1))
58cf70d3 1993 (if (= totwidth 1)
2bb63e81 1994 ;; Scrolled so intercolumn space is leftmost.
7ed9159a 1995 (push " " result))
58cf70d3 1996 (when (> totwidth 1)
94be2532 1997 (if (> ses--header-row 0)
7ed9159a 1998 (save-excursion
94be2532 1999 (ses-goto-print (1- ses--header-row) col)
7ed9159a
JY
2000 (setq x (buffer-substring-no-properties (point)
2001 (+ (point) width)))
58cf70d3
SM
2002 ;; Strip trailing space.
2003 (if (string-match "[ \t]+\\'" x)
2004 (setq x (substring x 0 (match-beginning 0))))
2005 ;; Cut off excess text.
2006 (if (>= (length x) totwidth)
2007 (setq x (substring x 0 (- totwidth -1)))))
2008 (setq x (ses-column-letter col)))
7ed9159a 2009 (push (propertize x 'face ses-box-prop) result)
58cf70d3 2010 (push (propertize "."
7ed9159a
JY
2011 'display `((space :align-to ,(1- totwidth)))
2012 'face ses-box-prop)
58cf70d3 2013 result)
2bb63e81
VB
2014 ;; Allow the following space to be squished to make room for the 3-D box
2015 ;; Coverage test ignores properties, thinks this is always a space!
7ed9159a
JY
2016 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2017 result)))
94be2532
JY
2018 (if (> ses--header-row 0)
2019 (push (propertize (format " [row %d]" ses--header-row)
7ed9159a
JY
2020 'display '((height (- 1))))
2021 result))
94be2532 2022 (setq ses--header-string (apply 'concat (nreverse result)))))
7ed9159a
JY
2023
2024
58cf70d3
SM
2025;;----------------------------------------------------------------------------
2026;; Redisplay and recalculation
2027;;----------------------------------------------------------------------------
7ed9159a
JY
2028
2029(defun ses-jump (sym)
2030 "Move point to cell SYM."
2031 (interactive "SJump to cell: ")
2032 (let ((rowcol (ses-sym-rowcol sym)))
2033 (or rowcol (error "Invalid cell name"))
2034 (if (eq (symbol-value sym) '*skip*)
2035 (error "Cell is covered by preceding cell"))
2036 (ses-goto-print (car rowcol) (cdr rowcol))))
2037
2038(defun ses-jump-safe (cell)
2039 "Like `ses-jump', but no error if invalid cell."
2040 (condition-case nil
2041 (ses-jump cell)
2042 (error)))
2043
2044(defun ses-reprint-all (&optional nonarrow)
2045 "Recreate the display area. Calls all printer functions. Narrows to
2046print area if NONARROW is nil."
2047 (interactive "*P")
2048 (widen)
2049 (unless nonarrow
94be2532 2050 (setq ses--deferred-narrow t))
7ed9159a
JY
2051 (let ((startcell (get-text-property (point) 'intangible))
2052 (inhibit-read-only t))
2053 (ses-begin-change)
94be2532 2054 (goto-char (point-min))
7ed9159a
JY
2055 (search-forward ses-print-data-boundary)
2056 (backward-char (length ses-print-data-boundary))
94be2532 2057 (delete-region (point-min) (point))
2bb63e81
VB
2058 ;; Insert all blank lines before printing anything, so ses-print-cell can
2059 ;; find the data area when inserting or deleting *skip* values for cells.
94be2532
JY
2060 (dotimes (row ses--numrows)
2061 (insert-and-inherit ses--blank-line))
7c018923 2062 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
7ed9159a 2063 (if (eq (ses-cell-value row 0) '*skip*)
2bb63e81 2064 ;; Column deletion left a dangling skip.
7ed9159a 2065 (ses-set-cell row 0 'value nil))
94be2532 2066 (dotimes (col ses--numcols)
7ed9159a
JY
2067 (ses-print-cell row col))
2068 (beginning-of-line 2))
2069 (ses-jump-safe startcell)))
2070
90ca8b49
VB
2071(defun ses-initialize-Dijkstra-attempt ()
2072 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2073 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2074
7ed9159a
JY
2075(defun ses-recalculate-cell ()
2076 "Recalculate and reprint the current cell or range.
2077
2078For an individual cell, shows the error if the formula or printer
2079signals one, or otherwise shows the cell's complete value. For a range, the
2080cells are recalculated in \"natural\" order, so cells that other cells refer
2081to are recalculated first."
2082 (interactive "*")
2083 (ses-check-curcell 'range)
2084 (ses-begin-change)
90ca8b49
VB
2085 (ses-initialize-Dijkstra-attempt)
2086 (let (sig cur-rowcol)
7ed9159a 2087 (setq ses-start-time (float-time))
94be2532 2088 (if (atom ses--curcell)
90ca8b49
VB
2089 (when
2090 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2091 sig (progn
2092 (ses-cell-property-set :ses-Dijkstra-attempt
2093 (cons ses--Dijkstra-attempt-nb 0)
2094 (car cur-rowcol) (cdr cur-rowcol) )
2095 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2096 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2097 (cdr cur-rowcol)))))
2bb63e81
VB
2098 ;; First, recalculate all cells that don't refer to other cells and
2099 ;; produce a list of cells with references.
94be2532 2100 (ses-dorange ses--curcell
7ed9159a
JY
2101 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
2102 (condition-case nil
2103 (progn
2bb63e81
VB
2104 ;; The t causes an error if the cell has references. If no
2105 ;; references, the t will be the result value.
7ed9159a 2106 (1value (ses-formula-references (ses-cell-formula row col) t))
90ca8b49
VB
2107 (ses-cell-property-set :ses-Dijkstra-attempt
2108 (cons ses--Dijkstra-attempt-nb 0)
2109 row col)
2110 (when (setq sig (ses-calculate-cell row col t))
2111 (nconc sig (list (ses-cell-symbol row col)))))
7ed9159a 2112 (wrong-type-argument
2bb63e81 2113 ;; The formula contains a reference.
94be2532 2114 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
2bb63e81 2115 ;; Do the update now, so we can force recalculation.
94be2532
JY
2116 (let ((x ses--deferred-recalc))
2117 (setq ses--deferred-recalc nil)
7ed9159a
JY
2118 (condition-case hold
2119 (ses-update-cells x t)
2120 (error (setq sig hold))))
2121 (cond
2122 (sig
8a26c165 2123 (message "%s" (error-message-string sig)))
94be2532 2124 ((consp ses--curcell)
7ed9159a
JY
2125 (message " "))
2126 (t
94be2532 2127 (princ (symbol-value ses--curcell))))))
7ed9159a
JY
2128
2129(defun ses-recalculate-all ()
2130 "Recalculate and reprint all cells."
2131 (interactive "*")
94be2532
JY
2132 (let ((startcell (get-text-property (point) 'intangible))
2133 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2134 (1- ses--numcols)))))
7ed9159a
JY
2135 (ses-recalculate-cell)
2136 (ses-jump-safe startcell)))
2137
2138(defun ses-truncate-cell ()
4bdf2ad2 2139 "Reprint current cell, but without spillover into any following blank cells."
7ed9159a
JY
2140 (interactive "*")
2141 (ses-check-curcell)
94be2532 2142 (let* ((rowcol (ses-sym-rowcol ses--curcell))
7ed9159a
JY
2143 (row (car rowcol))
2144 (col (cdr rowcol)))
94be2532 2145 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
7ed9159a 2146 (eq (ses-cell-value row (1+ col)) '*skip*))
2bb63e81
VB
2147 ;; This cell has spill-over. We'll momentarily pretend the following cell
2148 ;; has a `t' in it.
7ed9159a
JY
2149 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
2150 (ses-print-cell row col)))
2bb63e81 2151 ;; Now remove the *skip*. ses-print-cell is always nil here.
7ed9159a
JY
2152 (ses-set-cell row (1+ col) 'value nil)
2153 (1value (ses-print-cell row (1+ col))))))
2154
2155(defun ses-reconstruct-all ()
2156 "Reconstruct buffer based on cell data stored in Emacs variables."
2157 (interactive "*")
2158 (ses-begin-change)
2159 ;;Reconstruct reference lists.
58cf70d3 2160 (let (x yrow ycol)
7ed9159a 2161 ;;Delete old reference lists
7c018923 2162 (dotimes-with-progress-reporter
2bb63e81 2163 (row ses--numrows) "Deleting references..."
94be2532 2164 (dotimes (col ses--numcols)
7ed9159a
JY
2165 (ses-set-cell row col 'references nil)))
2166 ;;Create new reference lists
7c018923 2167 (dotimes-with-progress-reporter
2bb63e81 2168 (row ses--numrows) "Computing references..."
94be2532 2169 (dotimes (col ses--numcols)
7ed9159a
JY
2170 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2171 (setq x (ses-sym-rowcol ref)
2172 yrow (car x)
2173 ycol (cdr x))
2174 (ses-set-cell yrow ycol 'references
2175 (cons (ses-cell-symbol row col)
2176 (ses-cell-references yrow ycol)))))))
2bb63e81 2177 ;; Delete everything and reconstruct basic data area.
bd93e3e1 2178 (ses-widen)
7ed9159a
JY
2179 (let ((inhibit-read-only t))
2180 (goto-char (point-max))
58cf70d3 2181 (if (search-backward ";; Local Variables:\n" nil t)
94be2532 2182 (delete-region (point-min) (point))
2bb63e81
VB
2183 ;; Buffer is quite screwed up --- can't even save the user-specified
2184 ;; locals.
94be2532 2185 (delete-region (point-min) (point-max))
7ed9159a 2186 (insert ses-initial-file-trailer)
94be2532 2187 (goto-char (point-min)))
2bb63e81 2188 ;; Create a blank display area.
94be2532
JY
2189 (dotimes (row ses--numrows)
2190 (insert ses--blank-line))
7ed9159a 2191 (insert ses-print-data-boundary)
ddd1c214
JY
2192 (backward-char (1- (length ses-print-data-boundary)))
2193 (setq ses--data-marker (point-marker))
2194 (forward-char (1- (length ses-print-data-boundary)))
2bb63e81 2195 ;; Placeholders for cell data.
94be2532 2196 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2bb63e81 2197 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
7ed9159a 2198 (insert "\n\n\n\n")
ddd1c214
JY
2199 (insert ses-initial-global-parameters)
2200 (backward-char (1- (length ses-initial-global-parameters)))
2201 (setq ses--params-marker (point-marker))
2202 (forward-char (1- (length ses-initial-global-parameters))))
94be2532
JY
2203 (ses-set-parameter 'ses--col-widths ses--col-widths)
2204 (ses-set-parameter 'ses--col-printers ses--col-printers)
2205 (ses-set-parameter 'ses--default-printer ses--default-printer)
2206 (ses-set-parameter 'ses--header-row ses--header-row)
2207 (ses-set-parameter 'ses--numrows ses--numrows)
2208 (ses-set-parameter 'ses--numcols ses--numcols)
7ed9159a
JY
2209 ;;Keep our old narrowing
2210 (ses-setup)
2211 (ses-recalculate-all)
94be2532 2212 (goto-char (point-min)))
7ed9159a
JY
2213
2214
58cf70d3
SM
2215;;----------------------------------------------------------------------------
2216;; Input of cell formulas
2217;;----------------------------------------------------------------------------
7ed9159a
JY
2218
2219(defun ses-edit-cell (row col newval)
2220 "Display current cell contents in minibuffer, for editing. Returns nil if
2221cell formula was unsafe and user declined confirmation."
2222 (interactive
2223 (progn
2224 (barf-if-buffer-read-only)
2225 (ses-check-curcell)
94be2532 2226 (let* ((rowcol (ses-sym-rowcol ses--curcell))
7ed9159a
JY
2227 (row (car rowcol))
2228 (col (cdr rowcol))
2229 (formula (ses-cell-formula row col))
2230 initial)
2231 (if (eq (car-safe formula) 'ses-safe-formula)
2232 (setq formula (cadr formula)))
2233 (if (eq (car-safe formula) 'quote)
2234 (setq initial (format "'%S" (cadr formula)))
2235 (setq initial (prin1-to-string formula)))
2236 (if (stringp formula)
2bb63e81 2237 ;; Position cursor inside close-quote.
7ed9159a
JY
2238 (setq initial (cons initial (length initial))))
2239 (list row col
94be2532 2240 (read-from-minibuffer (format "Cell %s: " ses--curcell)
7ed9159a
JY
2241 initial
2242 ses-mode-edit-map
2bb63e81 2243 t ; Convert to Lisp object.
7ed9159a
JY
2244 'ses-read-cell-history)))))
2245 (when (ses-warn-unsafe newval 'unsafep)
2246 (ses-begin-change)
2247 (ses-cell-set-formula row col newval)
2248 t))
2249
2250(defun ses-read-cell (row col newval)
2251 "Self-insert for initial character of cell function."
2252 (interactive
1e3b6bec
SM
2253 (let* ((initial (this-command-keys))
2254 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2255 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
7ed9159a 2256 (barf-if-buffer-read-only)
7ed9159a
JY
2257 (list (car rowcol)
2258 (cdr rowcol)
1e3b6bec
SM
2259 (read-from-minibuffer
2260 (format "Cell %s: " ses--curcell)
2261 (cons (if (equal initial "\"") "\"\""
2262 (if (equal initial "(") "()" initial)) 2)
2263 ses-mode-edit-map
2bb63e81 2264 t ; Convert to Lisp object.
1e3b6bec 2265 'ses-read-cell-history
bd93e3e1
JY
2266 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2267 (cadr curval)
2268 curval))))))
7ed9159a 2269 (when (ses-edit-cell row col newval)
2bb63e81 2270 (ses-command-hook) ; Update cell widths before movement.
7ed9159a
JY
2271 (dolist (x ses-after-entry-functions)
2272 (funcall x 1))))
2273
2274(defun ses-read-symbol (row col symb)
2275 "Self-insert for a symbol as a cell formula. The set of all symbols that
2276have been used as formulas in this spreadsheet is available for completions."
2277 (interactive
94be2532 2278 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
7ed9159a
JY
2279 newval)
2280 (barf-if-buffer-read-only)
94be2532
JY
2281 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2282 ses--symbolic-formulas))
7ed9159a
JY
2283 (list (car rowcol)
2284 (cdr rowcol)
2285 (if (string= newval "")
2bb63e81 2286 nil ; Don't create zero-length symbols!
7ed9159a
JY
2287 (list 'quote (intern newval))))))
2288 (when (ses-edit-cell row col symb)
2bb63e81 2289 (ses-command-hook) ; Update cell widths before movement.
7ed9159a
JY
2290 (dolist (x ses-after-entry-functions)
2291 (funcall x 1))))
2292
2293(defun ses-clear-cell-forward (count)
2294 "Delete formula and printer for current cell and then move to next cell.
2295With prefix, deletes several cells."
2296 (interactive "*p")
2297 (if (< count 0)
2298 (1value (ses-clear-cell-backward (- count)))
2299 (ses-check-curcell)
2300 (ses-begin-change)
2301 (dotimes (x count)
2302 (ses-set-curcell)
94be2532 2303 (let ((rowcol (ses-sym-rowcol ses--curcell)))
7ed9159a
JY
2304 (or rowcol (signal 'end-of-buffer nil))
2305 (ses-clear-cell (car rowcol) (cdr rowcol)))
2306 (forward-char 1))))
2307
2308(defun ses-clear-cell-backward (count)
2309 "Move to previous cell and then delete it. With prefix, deletes several
2310cells."
2311 (interactive "*p")
2312 (if (< count 0)
2313 (1value (ses-clear-cell-forward (- count)))
2314 (ses-check-curcell 'end)
2315 (ses-begin-change)
2316 (dotimes (x count)
2bb63e81 2317 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
7ed9159a 2318 (ses-set-curcell)
94be2532 2319 (let ((rowcol (ses-sym-rowcol ses--curcell)))
7ed9159a
JY
2320 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2321
2322
58cf70d3
SM
2323;;----------------------------------------------------------------------------
2324;; Input of cell-printer functions
2325;;----------------------------------------------------------------------------
7ed9159a
JY
2326
2327(defun ses-read-printer (prompt default)
2328 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
4bdf2ad2 2329PROMPT should end with \": \". Result is t if operation was canceled."
7ed9159a
JY
2330 (barf-if-buffer-read-only)
2331 (if (eq default t)
2332 (setq default "")
2333 (setq prompt (format "%s [currently %S]: "
2334 (substring prompt 0 -2)
2335 default)))
2336 (let ((new (read-from-minibuffer prompt
2bb63e81 2337 nil ; Initial contents.
7ed9159a 2338 ses-mode-edit-map
2bb63e81 2339 t ; Evaluate the result.
7ed9159a
JY
2340 'ses-read-printer-history
2341 (prin1-to-string default))))
2342 (if (equal new default)
2bb63e81 2343 ;; User changed mind, decided not to change printer.
7ed9159a
JY
2344 (setq new t)
2345 (ses-printer-validate new)
2346 (or (not new)
2347 (stringp new)
2348 (stringp (car-safe new))
2349 (ses-warn-unsafe new 'unsafep-function)
2350 (setq new t)))
2351 new))
2352
2353(defun ses-read-cell-printer (newval)
2354 "Set the printer function for the current cell or range.
2355
2356A printer function is either a string (a format control-string with one
2357%-sequence -- result from format will be right-justified), or a list of one
2358string (result from format will be left-justified), or a lambda-expression of
2359one argument, or a symbol that names a function of one argument. In the
2360latter two cases, the function's result should be either a string (will be
2361right-justified) or a list of one string (will be left-justified)."
2362 (interactive
2363 (let ((default t)
58cf70d3 2364 x)
7ed9159a
JY
2365 (ses-check-curcell 'range)
2366 ;;Default is none if not all cells in range have same printer
2367 (catch 'ses-read-cell-printer
94be2532 2368 (ses-dorange ses--curcell
7ed9159a
JY
2369 (setq x (ses-cell-printer row col))
2370 (if (eq (car-safe x) 'ses-safe-printer)
2371 (setq x (cadr x)))
2372 (if (eq default t)
2373 (setq default x)
2374 (unless (equal default x)
2375 ;;Range contains differing printer functions
2376 (setq default t)
2377 (throw 'ses-read-cell-printer t)))))
94be2532
JY
2378 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2379 default))))
7ed9159a
JY
2380 (unless (eq newval t)
2381 (ses-begin-change)
94be2532 2382 (ses-dorange ses--curcell
7ed9159a
JY
2383 (ses-set-cell row col 'printer newval)
2384 (ses-print-cell row col))))
2385
2386(defun ses-read-column-printer (col newval)
4bdf2ad2
VB
2387 "Set the printer function for the current column.
2388See `ses-read-cell-printer' for input forms."
7ed9159a 2389 (interactive
94be2532 2390 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
7ed9159a
JY
2391 (ses-check-curcell)
2392 (list col (ses-read-printer (format "Column %s printer: "
2393 (ses-column-letter col))
2394 (ses-col-printer col)))))
2395
2396 (unless (eq newval t)
2397 (ses-begin-change)
94be2532 2398 (ses-set-parameter 'ses--col-printers newval col)
7ed9159a 2399 (save-excursion
94be2532 2400 (dotimes (row ses--numrows)
7ed9159a
JY
2401 (ses-print-cell row col)))))
2402
2403(defun ses-read-default-printer (newval)
4bdf2ad2
VB
2404 "Set the default printer function for cells that have no other.
2405See `ses-read-cell-printer' for input forms."
7ed9159a 2406 (interactive
94be2532 2407 (list (ses-read-printer "Default printer: " ses--default-printer)))
7ed9159a
JY
2408 (unless (eq newval t)
2409 (ses-begin-change)
94be2532 2410 (ses-set-parameter 'ses--default-printer newval)
7ed9159a
JY
2411 (ses-reprint-all t)))
2412
2413
58cf70d3
SM
2414;;----------------------------------------------------------------------------
2415;; Spreadsheet size adjustments
2416;;----------------------------------------------------------------------------
7ed9159a
JY
2417
2418(defun ses-insert-row (count)
4bdf2ad2
VB
2419 "Insert a new row before the current one.
2420With prefix, insert COUNT rows before current one."
7ed9159a
JY
2421 (interactive "*p")
2422 (ses-check-curcell 'end)
2423 (or (> count 0) (signal 'args-out-of-range nil))
2424 (ses-begin-change)
2425 (let ((inhibit-quit t)
2426 (inhibit-read-only t)
94be2532 2427 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
7ed9159a
JY
2428 newrow)
2429 ;;Create a new set of cell-variables
94be2532
JY
2430 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2431 0 (1- ses--numcols))
2432 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
7ed9159a
JY
2433 ;;Insert each row
2434 (ses-goto-print row 0)
7c018923 2435 (dotimes-with-progress-reporter (x count) "Inserting row..."
7ed9159a
JY
2436 ;;Create a row of empty cells. The `symbol' fields will be set by
2437 ;;the call to ses-relocate-all.
94be2532
JY
2438 (setq newrow (make-vector ses--numcols nil))
2439 (dotimes (col ses--numcols)
58cf70d3 2440 (aset newrow col (ses-make-cell)))
94be2532 2441 (setq ses--cells (ses-vector-insert ses--cells row newrow))
63f3351c 2442 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
94be2532 2443 (insert ses--blank-line))
7ed9159a
JY
2444 ;;Insert empty lines in cell data area (will be replaced by
2445 ;;ses-relocate-all)
2446 (ses-goto-data row 0)
94be2532 2447 (insert (make-string (* (1+ ses--numcols) count) ?\n))
7ed9159a
JY
2448 (ses-relocate-all row 0 count 0)
2449 ;;If any cell printers insert constant text, insert that text
2450 ;;into the line.
94be2532
JY
2451 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2452 (global (ses-call-printer ses--default-printer)))
7ed9159a
JY
2453 (if (or (> (length cols) 0) (> (length global) 0))
2454 (dotimes (x count)
94be2532 2455 (dotimes (col ses--numcols)
7ed9159a
JY
2456 ;;These cells are always nil, only constant formatting printed
2457 (1value (ses-print-cell (+ x row) col))))))
94be2532 2458 (when (> ses--header-row row)
7ed9159a 2459 ;;Inserting before header
94be2532 2460 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
7ed9159a
JY
2461 (ses-reset-header-string)))
2462 ;;Reconstruct text attributes
2463 (ses-setup)
bd93e3e1
JY
2464 ;;Prepare for undo
2465 (push '(apply ses-widen) buffer-undo-list)
7ed9159a 2466 ;;Return to current cell
94be2532
JY
2467 (if ses--curcell
2468 (ses-jump-safe ses--curcell)
2469 (ses-goto-print (1- ses--numrows) 0)))
7ed9159a
JY
2470
2471(defun ses-delete-row (count)
4bdf2ad2
VB
2472 "Delete the current row.
2473With prefix, deletes COUNT rows starting from the current one."
7ed9159a
JY
2474 (interactive "*p")
2475 (ses-check-curcell)
2476 (or (> count 0) (signal 'args-out-of-range nil))
2477 (let ((inhibit-quit t)
2478 (inhibit-read-only t)
58cf70d3 2479 (row (car (ses-sym-rowcol ses--curcell))))
94be2532 2480 (setq count (min count (- ses--numrows row)))
7ed9159a 2481 (ses-begin-change)
94be2532 2482 (ses-set-parameter 'ses--numrows (- ses--numrows count))
7ed9159a
JY
2483 ;;Delete lines from print area
2484 (ses-goto-print row 0)
2485 (ses-delete-line count)
2486 ;;Delete lines from cell data area
2487 (ses-goto-data row 0)
94be2532 2488 (ses-delete-line (* count (1+ ses--numcols)))
7ed9159a 2489 ;;Relocate variables and formulas
94be2532 2490 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
7ed9159a 2491 (ses-relocate-all row 0 (- count) 0)
94be2532
JY
2492 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2493 0 (1- ses--numcols))
2494 (when (> ses--header-row row)
2495 (if (<= ses--header-row (+ row count))
7ed9159a 2496 ;;Deleting the header row
94be2532
JY
2497 (ses-set-parameter 'ses--header-row 0)
2498 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
7ed9159a
JY
2499 (ses-reset-header-string)))
2500 ;;Reconstruct attributes
2501 (ses-setup)
bd93e3e1
JY
2502 ;;Prepare for undo
2503 (push '(apply ses-widen) buffer-undo-list)
94be2532 2504 (ses-jump-safe ses--curcell))
7ed9159a
JY
2505
2506(defun ses-insert-column (count &optional col width printer)
58cf70d3
SM
2507 "Insert a new column before COL (default is the current one).
2508With prefix, insert COUNT columns before current one.
2509If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2510\(otherwise they're taken from the current column)."
7ed9159a
JY
2511 (interactive "*p")
2512 (ses-check-curcell)
2513 (or (> count 0) (signal 'args-out-of-range nil))
2514 (or col
94be2532 2515 (setq col (cdr (ses-sym-rowcol ses--curcell))
7ed9159a
JY
2516 width (ses-col-width col)
2517 printer (ses-col-printer col)))
2518 (ses-begin-change)
2519 (let ((inhibit-quit t)
2520 (inhibit-read-only t)
94be2532
JY
2521 (widths ses--col-widths)
2522 (printers ses--col-printers)
7ed9159a
JY
2523 has-skip)
2524 ;;Create a new set of cell-variables
94be2532
JY
2525 (ses-create-cell-variable-range 0 (1- ses--numrows)
2526 ses--numcols (+ ses--numcols count -1))
7ed9159a 2527 ;;Insert each column.
7c018923 2528 (dotimes-with-progress-reporter (x count) "Inserting column..."
7ed9159a
JY
2529 ;;Create a column of empty cells. The `symbol' fields will be set by
2530 ;;the call to ses-relocate-all.
2531 (ses-adjust-print-width col (1+ width))
94be2532
JY
2532 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2533 (dotimes (row ses--numrows)
2534 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
7ed9159a
JY
2535 ;;Inserting in the middle of a spill-over
2536 (setq has-skip t))
94be2532
JY
2537 (ses-aset-with-undo ses--cells row
2538 (ses-vector-insert (aref ses--cells row)
58cf70d3 2539 col (ses-make-cell)))
7ed9159a
JY
2540 ;;Insert empty lines in cell data area (will be replaced by
2541 ;;ses-relocate-all)
2542 (ses-goto-data row col)
2543 (insert ?\n))
2bb63e81 2544 ;; Insert column width and printer.
7ed9159a
JY
2545 (setq widths (ses-vector-insert widths col width)
2546 printers (ses-vector-insert printers col printer)))
94be2532
JY
2547 (ses-set-parameter 'ses--col-widths widths)
2548 (ses-set-parameter 'ses--col-printers printers)
7ed9159a
JY
2549 (ses-reset-header-string)
2550 (ses-relocate-all 0 col 0 count)
2551 (if has-skip
2552 (ses-reprint-all t)
2553 (when (or (> (length (ses-call-printer printer)) 0)
94be2532 2554 (> (length (ses-call-printer ses--default-printer)) 0))
2bb63e81
VB
2555 ;; Either column printer or global printer inserts some constant text.
2556 ;; Reprint the new columns to insert that text.
94be2532 2557 (dotimes (x ses--numrows)
7ed9159a 2558 (dotimes (y count)
2bb63e81 2559 ;; Always nil here --- this is a blank column.
7ed9159a
JY
2560 (1value (ses-print-cell-new-width x (+ y col))))))
2561 (ses-setup)))
94be2532 2562 (ses-jump-safe ses--curcell))
7ed9159a
JY
2563
2564(defun ses-delete-column (count)
4bdf2ad2
VB
2565 "Delete the current column.
2566With prefix, deletes COUNT columns starting from the current one."
7ed9159a
JY
2567 (interactive "*p")
2568 (ses-check-curcell)
2569 (or (> count 0) (signal 'args-out-of-range nil))
2570 (let ((inhibit-quit t)
2571 (inhibit-read-only t)
94be2532 2572 (rowcol (ses-sym-rowcol ses--curcell))
7ed9159a 2573 (width 0)
58cf70d3 2574 col origrow has-skip)
7ed9159a
JY
2575 (setq origrow (car rowcol)
2576 col (cdr rowcol)
94be2532
JY
2577 count (min count (- ses--numcols col)))
2578 (if (= count ses--numcols)
7ed9159a
JY
2579 (error "Can't delete all columns!"))
2580 ;;Determine width of column(s) being deleted
2581 (dotimes (x count)
2582 (setq width (+ width (ses-col-width (+ col x)) 1)))
2583 (ses-begin-change)
94be2532 2584 (ses-set-parameter 'ses--numcols (- ses--numcols count))
7ed9159a 2585 (ses-adjust-print-width col (- width))
7c018923 2586 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
7ed9159a
JY
2587 ;;Delete lines from cell data area
2588 (ses-goto-data row col)
2589 (ses-delete-line count)
2590 ;;Delete cells. Check if deletion area begins or ends with a skip.
2591 (if (or (eq (ses-cell-value row col) '*skip*)
94be2532 2592 (and (< col ses--numcols)
7ed9159a
JY
2593 (eq (ses-cell-value row (+ col count)) '*skip*)))
2594 (setq has-skip t))
94be2532
JY
2595 (ses-aset-with-undo ses--cells row
2596 (ses-vector-delete (aref ses--cells row) col count)))
7ed9159a 2597 ;;Update globals
94be2532
JY
2598 (ses-set-parameter 'ses--col-widths
2599 (ses-vector-delete ses--col-widths col count))
2600 (ses-set-parameter 'ses--col-printers
2601 (ses-vector-delete ses--col-printers col count))
7ed9159a
JY
2602 (ses-reset-header-string)
2603 ;;Relocate variables and formulas
2604 (ses-relocate-all 0 col 0 (- count))
94be2532
JY
2605 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2606 ses--numcols (+ ses--numcols count -1))
7ed9159a
JY
2607 (if has-skip
2608 (ses-reprint-all t)
2609 (ses-setup))
94be2532 2610 (if (>= col ses--numcols)
7ed9159a
JY
2611 (setq col (1- col)))
2612 (ses-goto-print origrow col)))
2613
2614(defun ses-forward-or-insert (&optional count)
2615 "Move to next cell in row, or inserts a new cell if already in last one, or
2616inserts a new row if at bottom of print area. Repeat COUNT times."
2617 (interactive "p")
2618 (ses-check-curcell 'end)
2bb63e81 2619 (setq deactivate-mark t) ; Doesn't combine well with ranges.
7ed9159a
JY
2620 (dotimes (x count)
2621 (ses-set-curcell)
94be2532 2622 (if (not ses--curcell)
2bb63e81 2623 (progn ; At bottom of print area.
7ed9159a
JY
2624 (barf-if-buffer-read-only)
2625 (ses-insert-row 1))
94be2532 2626 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
7ed9159a
JY
2627 (when (/= 32
2628 (char-before (next-single-property-change (point)
2629 'intangible)))
2bb63e81
VB
2630 ;; We're already in last nonskipped cell on line. Need to create a
2631 ;; new column.
7ed9159a
JY
2632 (barf-if-buffer-read-only)
2633 (ses-insert-column (- count x)
94be2532 2634 ses--numcols
7ed9159a
JY
2635 (ses-col-width col)
2636 (ses-col-printer col)))))
2637 (forward-char)))
2638
2639(defun ses-append-row-jump-first-column ()
4bdf2ad2 2640 "Insert a new row after current one and jump to its first column."
7ed9159a
JY
2641 (interactive "*")
2642 (ses-check-curcell)
2643 (ses-begin-change)
2644 (beginning-of-line 2)
2645 (ses-set-curcell)
2646 (ses-insert-row 1))
2647
2648(defun ses-set-column-width (col newwidth)
2649 "Set the width of the current column."
2650 (interactive
94be2532 2651 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
7ed9159a
JY
2652 (barf-if-buffer-read-only)
2653 (list col
2654 (if current-prefix-arg
2655 (prefix-numeric-value current-prefix-arg)
2656 (read-from-minibuffer (format "Column %s width [currently %d]: "
2657 (ses-column-letter col)
2658 (ses-col-width col))
2bb63e81
VB
2659 nil ; No initial contents.
2660 nil ; No override keymap.
2661 t ; Convert to Lisp object.
2662 nil ; No history.
7ed9159a 2663 (number-to-string
2bb63e81 2664 (ses-col-width col))))))) ; Default value.
7ed9159a
JY
2665 (if (< newwidth 1)
2666 (error "Invalid column width"))
2667 (ses-begin-change)
2668 (ses-reset-header-string)
2669 (save-excursion
2670 (let ((inhibit-quit t))
2671 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
94be2532
JY
2672 (ses-set-parameter 'ses--col-widths newwidth col))
2673 (dotimes (row ses--numrows)
7ed9159a
JY
2674 (ses-print-cell-new-width row col))))
2675
2676
58cf70d3
SM
2677;;----------------------------------------------------------------------------
2678;; Cut and paste, import and export
2679;;----------------------------------------------------------------------------
7ed9159a
JY
2680
2681(defadvice copy-region-as-kill (around ses-copy-region-as-kill
2682 activate preactivate)
2683 "It doesn't make sense to copy read-only or intangible attributes into the
2684kill ring. It probably doesn't make sense to copy keymap properties.
2685We'll assume copying front-sticky properties doesn't make sense, either.
2686
2687This advice also includes some SES-specific code because otherwise it's too
2688hard to override how mouse-1 works."
2689 (when (> beg end)
2690 (let ((temp beg))
2691 (setq beg end
2692 end temp)))
2693 (if (not (and (eq major-mode 'ses-mode)
2694 (eq (get-text-property beg 'read-only) 'ses)
2695 (eq (get-text-property (1- end) 'read-only) 'ses)))
2bb63e81 2696 ad-do-it ; Normal copy-region-as-kill.
4c759a32
SM
2697 (kill-new (ses-copy-region beg end))
2698 (if transient-mark-mode
2699 (setq deactivate-mark t))
2700 nil))
7ed9159a
JY
2701
2702(defun ses-copy-region (beg end)
2703 "Treat the region as rectangular. Convert the intangible attributes to
2704SES attributes recording the contents of the cell as of the time of copying."
4eb3897c
JY
2705 (when (= end ses--data-marker)
2706 ;;Avoid overflow situation
2707 (setq end (1- ses--data-marker)))
7ed9159a
JY
2708 (let* ((inhibit-point-motion-hooks t)
2709 (x (mapconcat 'ses-copy-region-helper
2710 (extract-rectangle beg (1- end)) "\n")))
2711 (remove-text-properties 0 (length x)
2712 '(read-only t
2713 intangible t
2714 keymap t
2715 front-sticky t)
2716 x)
2717 x))
2718
2719(defun ses-copy-region-helper (line)
2720 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2721external form by attaching to each print cell a 'ses attribute that records
2722the corresponding data cell."
2723 (or (> (length line) 1)
2724 (error "Empty range"))
2725 (let ((inhibit-read-only t)
2726 (pos 0)
2727 mycell next sym rowcol)
2728 (while pos
2729 (setq sym (get-text-property pos 'intangible line)
2730 next (next-single-property-change pos 'intangible line)
2731 rowcol (ses-sym-rowcol sym)
2732 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2733 (put-text-property pos (or next (length line))
2734 'ses
2735 (list (ses-cell-symbol mycell)
2736 (ses-cell-formula mycell)
2737 (ses-cell-printer mycell))
2738 line)
2739 (setq pos next)))
2740 line)
2741
2742(defun ses-kill-override (beg end)
4bdf2ad2
VB
2743 "Generic override for any commands that kill text.
2744We clear the killed cells instead of deleting them."
7ed9159a
JY
2745 (interactive "r")
2746 (ses-check-curcell 'needrange)
2bb63e81
VB
2747 ;; For some reason, the text-read-only error is not caught by `delete-region',
2748 ;; so we have to use subterfuge.
7ed9159a
JY
2749 (let ((buffer-read-only t))
2750 (1value (condition-case x
2751 (noreturn (funcall (lookup-key (current-global-map)
2752 (this-command-keys))
2753 beg end))
2bb63e81
VB
2754 (buffer-read-only nil)))) ; The expected error.
2755 ;; Because the buffer was marked read-only, the kill command turned itself
2756 ;; into a copy. Now we clear the cells or signal the error. First we check
2757 ;; whether the buffer really is read-only.
7ed9159a
JY
2758 (barf-if-buffer-read-only)
2759 (ses-begin-change)
94be2532 2760 (ses-dorange ses--curcell
7ed9159a 2761 (ses-clear-cell row col))
94be2532 2762 (ses-jump (car ses--curcell)))
7ed9159a
JY
2763
2764(defadvice yank (around ses-yank activate preactivate)
2765 "In SES mode, the yanked text is inserted as cells.
2766
2767If the text contains 'ses attributes (meaning it went to the kill-ring from a
2768SES buffer), the formulas and print functions are restored for the cells. If
2769the text contains tabs, this is an insertion of tab-separated formulas.
2770Otherwise the text is inserted as the formula for the current cell.
2771
2772When inserting cells, the formulas are usually relocated to keep the same
2773relative references to neighboring cells. This is best if the formulas
2774generally refer to other cells within the yanked text. You can use the C-u
2775prefix to specify insertion without relocation, which is best when the
4bdf2ad2 2776formulas refer to cells outside the yanked text.
7ed9159a
JY
2777
2778When inserting formulas, the text is treated as a string constant if it doesn't
2779make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2780explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2781as symbols."
2782 (if (not (and (eq major-mode 'ses-mode)
2783 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2bb63e81 2784 ad-do-it ; Normal non-SES yank.
7ed9159a
JY
2785 (ses-check-curcell 'end)
2786 (push-mark (point))
2787 (let ((text (current-kill (cond
2788 ((listp arg) 0)
2789 ((eq arg '-) -1)
2790 (t (1- arg))))))
2791 (or (ses-yank-cells text arg)
2792 (ses-yank-tsf text arg)
2793 (ses-yank-one (ses-yank-resize 1 1)
2794 text
2795 0
2796 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2bb63e81 2797 ;; Just one cell --- delete final tab or newline.
7ed9159a
JY
2798 (1- (length text)))
2799 arg)))
2800 (if (consp arg)
2801 (exchange-point-and-mark))))
2802
2803(defun ses-yank-pop (arg)
2804 "Replace just-yanked stretch of killed text with a different stretch.
4bdf2ad2
VB
2805This command is allowed only immediately after a `yank' or a `yank-pop',
2806when the region contains a stretch of reinserted previously-killed text.
2807We replace it with a different stretch of killed text.
7ed9159a
JY
2808 Unlike standard `yank-pop', this function uses `undo' to delete the
2809previous insertion."
2810 (interactive "*p")
2811 (or (eq last-command 'yank)
2812 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2813 ;;macro definition.
2814 (noreturn (error "Previous command was not a yank")))
2815 (undo)
2816 (ses-set-curcell)
2817 (yank (1+ (or arg 1)))
2818 (setq this-command 'yank))
2819
2820(defun ses-yank-cells (text arg)
4bdf2ad2 2821 "If the TEXT has a proper set of 'ses attributes, insert the text as
7ed9159a
JY
2822cells, else return nil. The cells are reprinted--the supplied text is
2823ignored because the column widths, default printer, etc. at yank time might
2824be different from those at kill-time. ARG is a list to indicate that
2825formulas are to be inserted without relocation."
2826 (let ((first (get-text-property 0 'ses text))
2827 (last (get-text-property (1- (length text)) 'ses text)))
2828 (when (and first last) ;;Otherwise not proper set of attributes
2829 (setq first (ses-sym-rowcol (car first))
2830 last (ses-sym-rowcol (car last)))
2831 (let* ((needrows (- (car last) (car first) -1))
2832 (needcols (- (cdr last) (cdr first) -1))
2833 (rowcol (ses-yank-resize needrows needcols))
2834 (rowincr (- (car rowcol) (car first)))
2835 (colincr (- (cdr rowcol) (cdr first)))
2836 (pos 0)
2837 myrow mycol x)
7c018923 2838 (dotimes-with-progress-reporter (row needrows) "Yanking..."
7ed9159a
JY
2839 (setq myrow (+ row (car rowcol)))
2840 (dotimes (col needcols)
2841 (setq mycol (+ col (cdr rowcol))
2842 last (get-text-property pos 'ses text)
2843 pos (next-single-property-change pos 'ses text)
2844 x (ses-sym-rowcol (car last)))
2845 (if (not last)
2bb63e81 2846 ;; Newline --- all remaining cells on row are skipped.
7ed9159a
JY
2847 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2848 last (list nil nil nil)
2849 pos (1- pos)))
2850 (if (/= (car x) (- myrow rowincr))
2851 (error "Cell row error"))
2852 (if (< (- mycol colincr) (cdr x))
2bb63e81 2853 ;; Some columns were skipped.
7ed9159a
JY
2854 (let ((oldcol mycol))
2855 (while (< (- mycol colincr) (cdr x))
2856 (ses-clear-cell myrow mycol)
2857 (setq col (1+ col)
2858 mycol (1+ mycol)))
2bb63e81
VB
2859 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
2860 (when (car last) ; Skip this for *skip* cells.
7ed9159a
JY
2861 (setq x (nth 2 last))
2862 (unless (equal x (ses-cell-printer myrow mycol))
2863 (or (not x)
2864 (stringp x)
2865 (eq (car-safe x) 'ses-safe-printer)
2866 (setq x `(ses-safe-printer ,x)))
2867 (ses-set-cell myrow mycol 'printer x))
2868 (setq x (cadr last))
2869 (if (atom arg)
2870 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2871 (or (atom x)
2872 (eq (car-safe x) 'ses-safe-formula)
2873 (setq x `(ses-safe-formula ,x)))
2874 (ses-cell-set-formula myrow mycol x)))
2875 (when pos
2876 (if (get-text-property pos 'ses text)
2877 (error "Missing newline between rows"))
2878 (setq pos (next-single-property-change pos 'ses text))))
2879 t))))
2880
2881(defun ses-yank-one (rowcol text from to arg)
2882 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2883cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2884 (let ((val (condition-case nil
2885 (read-from-string text from to)
2886 (error (cons nil from)))))
2887 (cond
2888 ((< (cdr val) (or to (length text)))
2bb63e81 2889 ;; Invalid sexp --- leave it as a string.
7ed9159a
JY
2890 (setq val (substring text from to)))
2891 ((and (car val) (symbolp (car val)))
2892 (if (consp arg)
2bb63e81
VB
2893 (setq val (list 'quote (car val))) ; Keep symbol.
2894 (setq val (substring text from to)))) ; Treat symbol as text.
7ed9159a
JY
2895 (t
2896 (setq val (car val))))
2897 (let ((row (car rowcol))
2898 (col (cdr rowcol)))
2899 (or (atom val)
2900 (setq val `(ses-safe-formula ,val)))
2901 (ses-cell-set-formula row col val))))
2902
2903(defun ses-yank-tsf (text arg)
4bdf2ad2
VB
2904 "If TEXT contains tabs and/or newlines, treat the tabs as
2905column-separators and the newlines as row-separators and insert the text as
7ed9159a
JY
2906cell formulas--else return nil. Treat plain symbols as strings unless ARG
2907is a list. Ignore a final newline."
2908 (if (or (not (string-match "[\t\n]" text))
2909 (= (match-end 0) (length text)))
2910 ;;Not TSF format
2911 nil
2912 (if (/= (aref text (1- (length text))) ?\n)
2913 (setq text (concat text "\n")))
2914 (let ((pos -1)
2915 (spots (list -1))
2916 (cols 0)
2917 (needrows 0)
2918 needcols rowcol)
2919 ;;Find all the tabs and newlines
2920 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
2921 (push pos spots)
2922 (setq cols (1+ cols))
2923 (when (eq (aref text pos) ?\n)
2924 (if (not needcols)
2925 (setq needcols cols)
2926 (or (= needcols cols)
2927 (error "Inconsistent row lengths")))
2928 (setq cols 0
2929 needrows (1+ needrows))))
2930 ;;Insert the formulas
2931 (setq rowcol (ses-yank-resize needrows needcols))
2932 (dotimes (row needrows)
2933 (dotimes (col needcols)
2934 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
2935 (+ (cdr rowcol) needcols (- col) -1))
2936 text (1+ (cadr spots)) (car spots) arg)
2937 (setq spots (cdr spots))))
2938 (ses-goto-print (+ (car rowcol) needrows -1)
2939 (+ (cdr rowcol) needcols -1))
2940 t)))
2941
2942(defun ses-yank-resize (needrows needcols)
4bdf2ad2
VB
2943 "If this yank will require inserting rows and/or columns, ask for
2944confirmation and then insert them. Result is (row,col) for top left of yank
7ed9159a
JY
2945spot, or error signal if user requests cancel."
2946 (ses-begin-change)
94be2532
JY
2947 (let ((rowcol (if ses--curcell
2948 (ses-sym-rowcol ses--curcell)
2949 (cons ses--numrows 0)))
7ed9159a 2950 rowbool colbool)
94be2532
JY
2951 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
2952 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
7ed9159a
JY
2953 rowbool (> needrows 0)
2954 colbool (> needcols 0))
2955 (when (or rowbool colbool)
2956 ;;Need to insert. Get confirm
ce5a3ac0 2957 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
7ed9159a
JY
2958 (if rowbool (format "%d rows" needrows) "")
2959 (if (and rowbool colbool) " and " "")
2960 (if colbool (format "%d columns" needcols) "")))
2961 (error "Cancelled"))
2962 (when rowbool
94be2532 2963 (let (ses--curcell)
7ed9159a 2964 (save-excursion
94be2532 2965 (ses-goto-print ses--numrows 0)
7ed9159a
JY
2966 (ses-insert-row needrows))))
2967 (when colbool
2968 (ses-insert-column needcols
94be2532
JY
2969 ses--numcols
2970 (ses-col-width (1- ses--numcols))
2971 (ses-col-printer (1- ses--numcols)))))
7ed9159a
JY
2972 rowcol))
2973
2974(defun ses-export-tsv (beg end)
2975 "Export values from the current range, with tabs between columns and
2976newlines between rows. Result is placed in kill ring."
2977 (interactive "r")
2978 (ses-export-tab nil))
2979
2980(defun ses-export-tsf (beg end)
2981 "Export formulas from the current range, with tabs between columns and
2982newlines between rows. Result is placed in kill ring."
2983 (interactive "r")
2984 (ses-export-tab t))
2985
2986(defun ses-export-tab (want-formulas)
4bdf2ad2
VB
2987 "Export the current range with tabs between columns and newlines between rows.
2988Result is placed in kill ring. The export is values unless WANT-FORMULAS
2989is non-nil. Newlines and tabs in the export text are escaped."
7ed9159a
JY
2990 (ses-check-curcell 'needrange)
2991 (let ((print-escape-newlines t)
2992 result item)
94be2532 2993 (ses-dorange ses--curcell
7ed9159a
JY
2994 (setq item (if want-formulas
2995 (ses-cell-formula row col)
2996 (ses-cell-value row col)))
2997 (if (eq (car-safe item) 'ses-safe-formula)
2998 ;;Hide our deferred safety-check marker
2999 (setq item (cadr item)))
3000 (if (or (not item) (eq item '*skip*))
3001 (setq item ""))
3002 (when (eq (car-safe item) 'quote)
3003 (push "'" result)
3004 (setq item (cadr item)))
3005 (setq item (prin1-to-string item t))
3006 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
3007 (push item result)
3008 (cond
3009 ((< col maxcol)
3010 (push "\t" result))
3011 ((< row maxrow)
3012 (push "\n" result))))
3013 (setq result (apply 'concat (nreverse result)))
3014 (kill-new result)))
3015
3016
58cf70d3
SM
3017;;----------------------------------------------------------------------------
3018;; Other user commands
3019;;----------------------------------------------------------------------------
7ed9159a 3020
94be2532
JY
3021(defun ses-unset-header-row ()
3022 "Select the default header row."
3023 (interactive)
3024 (ses-set-header-row 0))
3025
3026(defun ses-set-header-row (row)
3027 "Set the ROW to display in the header-line.
3028With a numerical prefix arg, use that row.
3029With no prefix arg, use the current row.
3030With a \\[universal-argument] prefix arg, prompt the user.
3031The top row is row 1. Selecting row 0 displays the default header row."
3032 (interactive
3033 (list (if (numberp current-prefix-arg) current-prefix-arg
3034 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3035 (if current-prefix-arg
e9c8c8e7 3036 (read-number "Header row: " currow)
94be2532
JY
3037 currow)))))
3038 (if (or (< row 0) (> row ses--numrows))
7ed9159a
JY
3039 (error "Invalid header-row"))
3040 (ses-begin-change)
bd93e3e1
JY
3041 (let ((oldval ses--header-row))
3042 (let (buffer-undo-list)
3043 (ses-set-parameter 'ses--header-row row))
3044 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
7ed9159a
JY
3045 (ses-reset-header-string))
3046
3047(defun ses-mark-row ()
4bdf2ad2 3048 "Mark the entirety of current row as a range."
7ed9159a
JY
3049 (interactive)
3050 (ses-check-curcell 'range)
94be2532 3051 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
7ed9159a
JY
3052 (push-mark (point))
3053 (ses-goto-print (1+ row) 0)
3054 (push-mark (point) nil t)
3055 (ses-goto-print row 0)))
3056
3057(defun ses-mark-column ()
4bdf2ad2 3058 "Mark the entirety of current column as a range."
7ed9159a
JY
3059 (interactive)
3060 (ses-check-curcell 'range)
94be2532 3061 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
7ed9159a
JY
3062 (row 0))
3063 (push-mark (point))
94be2532 3064 (ses-goto-print (1- ses--numrows) col)
7ed9159a
JY
3065 (forward-char 1)
3066 (push-mark (point) nil t)
3067 (while (eq '*skip* (ses-cell-value row col))
3068 ;;Skip over initial cells in column that can't be selected
3069 (setq row (1+ row)))
3070 (ses-goto-print row col)))
3071
3072(defun ses-end-of-line ()
3073 "Move point to last cell on line."
3074 (interactive)
3075 (ses-check-curcell 'end 'range)
2bb63e81
VB
3076 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3077 ; anyway.
94be2532 3078 (let ((col (1- ses--numcols))
7ed9159a 3079 row rowcol)
94be2532 3080 (if (symbolp ses--curcell)
2bb63e81 3081 ;; Single cell.
94be2532 3082 (setq row (car (ses-sym-rowcol ses--curcell)))
2bb63e81 3083 ;; Range --- use whichever end of the range the point is at.
7ed9159a 3084 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
94be2532
JY
3085 (car ses--curcell)
3086 (cdr ses--curcell))))
2bb63e81
VB
3087 ;; If range already includes the last cell in a row, point is actually
3088 ;; in the following row.
7ed9159a
JY
3089 (if (<= (cdr rowcol) (1- col))
3090 (setq row (car rowcol))
3091 (setq row (1+ (car rowcol)))
94be2532 3092 (if (= row ses--numrows)
7ed9159a
JY
3093 ;;Already at end - can't go anywhere
3094 (setq col 0))))
2bb63e81 3095 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
7ed9159a 3096 (while (eq (ses-cell-value row col) '*skip*)
2bb63e81 3097 ;; Back to beginning of multi-column cell.
7ed9159a
JY
3098 (setq col (1- col)))
3099 (ses-goto-print row col)))))
3100
3101(defun ses-renarrow-buffer ()
4bdf2ad2
VB
3102 "Narrow the buffer so only the print area is visible.
3103Use after \\[widen]."
7ed9159a 3104 (interactive)
94be2532 3105 (setq ses--deferred-narrow t))
7ed9159a
JY
3106
3107(defun ses-sort-column (sorter &optional reverse)
4bdf2ad2
VB
3108 "Sort the range by a specified column.
3109With prefix, sorts in REVERSE order."
7ed9159a
JY
3110 (interactive "*sSort column: \nP")
3111 (ses-check-curcell 'needrange)
94be2532
JY
3112 (let ((min (ses-sym-rowcol (car ses--curcell)))
3113 (max (ses-sym-rowcol (cdr ses--curcell))))
7ed9159a
JY
3114 (let ((minrow (car min))
3115 (mincol (cdr min))
3116 (maxrow (car max))
3117 (maxcol (cdr max))
3118 keys extracts end)
3119 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3120 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3121 (error "Invalid sort column"))
3122 ;;Get key columns and sort them
3123 (dotimes (x (- maxrow minrow -1))
3124 (ses-goto-print (+ minrow x) sorter)
3125 (setq end (next-single-property-change (point) 'intangible))
3126 (push (cons (buffer-substring-no-properties (point) end)
3127 (+ minrow x))
3128 keys))
3129 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3130 ;;Extract the lines in reverse sorted order
3131 (or reverse
3132 (setq keys (nreverse keys)))
3133 (dolist (x keys)
3134 (ses-goto-print (cdr x) (1+ maxcol))
3135 (setq end (point))
3136 (ses-goto-print (cdr x) mincol)
3137 (push (ses-copy-region (point) end) extracts))
3138 (deactivate-mark)
3139 ;;Paste the lines sequentially
3140 (dotimes (x (- maxrow minrow -1))
3141 (ses-goto-print (+ minrow x) mincol)
3142 (ses-set-curcell)
3143 (ses-yank-cells (pop extracts) nil)))))
3144
3145(defun ses-sort-column-click (event reverse)
94be2532 3146 "Mouse version of `ses-sort-column'."
7ed9159a
JY
3147 (interactive "*e\nP")
3148 (setq event (event-end event))
3149 (select-window (posn-window event))
2bb63e81 3150 (setq event (car (posn-col-row event))) ; Click column.
7ed9159a 3151 (let ((col 0))
94be2532 3152 (while (and (< col ses--numcols) (> event (ses-col-width col)))
7ed9159a
JY
3153 (setq event (- event (ses-col-width col) 1)
3154 col (1+ col)))
94be2532 3155 (if (>= col ses--numcols)
7ed9159a
JY
3156 (ding)
3157 (ses-sort-column (ses-column-letter col) reverse))))
3158
3159(defun ses-insert-range ()
4bdf2ad2 3160 "Insert into minibuffer the list of cells currently highlighted in the
7ed9159a
JY
3161spreadsheet."
3162 (interactive "*")
3163 (let (x)
3164 (with-current-buffer (window-buffer minibuffer-scroll-window)
2bb63e81 3165 (ses-command-hook) ; For ses-coverage.
7ed9159a 3166 (ses-check-curcell 'needrange)
94be2532
JY
3167 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3168 ,(cdr ses--curcell))))))
7ed9159a
JY
3169 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3170
3171(defun ses-insert-ses-range ()
4bdf2ad2 3172 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
7ed9159a
JY
3173highlighted range in the spreadsheet."
3174 (interactive "*")
3175 (let (x)
3176 (with-current-buffer (window-buffer minibuffer-scroll-window)
2bb63e81 3177 (ses-command-hook) ; For ses-coverage.
7ed9159a 3178 (ses-check-curcell 'needrange)
94be2532
JY
3179 (setq x (format "(ses-range %S %S)"
3180 (car ses--curcell)
3181 (cdr ses--curcell))))
7ed9159a
JY
3182 (insert x)))
3183
3184(defun ses-insert-range-click (event)
3185 "Mouse version of `ses-insert-range'."
3186 (interactive "*e")
3187 (mouse-set-point event)
3188 (ses-insert-range))
3189
3190(defun ses-insert-ses-range-click (event)
3191 "Mouse version of `ses-insert-ses-range'."
3192 (interactive "*e")
3193 (mouse-set-point event)
3194 (ses-insert-ses-range))
3195
4bdf2ad2
VB
3196(defun ses-replace-name-in-formula (formula old-name new-name)
3197 (let ((new-formula formula))
3198 (unless (and (consp formula)
3199 (eq (car-safe formula) 'quote))
3200 (while formula
3201 (let ((elt (car-safe formula)))
3202 (cond
3203 ((consp elt)
3204 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3205 ((and (symbolp elt)
3206 (eq (car-safe formula) old-name))
3207 (setcar formula new-name))))
3208 (setq formula (cdr formula))))
3209 new-formula))
3210
b525fd8a 3211(defun ses-rename-cell (new-name &optional cell)
4bdf2ad2
VB
3212 "Rename current cell."
3213 (interactive "*SEnter new name: ")
b525fd8a
VB
3214 (and (local-variable-p new-name)
3215 (ses-sym-rowcol new-name)
3216 ;; this test is needed because ses-cell property of deleted cells
3217 ;; is not deleted in case of subsequent undo
3218 (memq new-name ses--renamed-cell-symb-list)
3219 (error "Already a cell name"))
3220 (and (boundp new-name)
3221 (null (yes-or-no-p (format "`%S' is already bound outside this buffer, continue? "
3222 new-name)))
3223 (error "Already a bound cell name"))
3224 (let* ((sym (if (ses-cell-p cell)
3225 (ses-cell-symbol cell)
3226 (setq cell nil)
3227 (ses-check-curcell)
3228 ses--curcell))
3229 (rowcol (ses-sym-rowcol sym))
316e68a7 3230 (row (car rowcol))
b525fd8a
VB
3231 (col (cdr rowcol)))
3232 (setq cell (or cell (ses-get-cell row col)))
3233 (push `(ses-rename-cell ,(ses-cell-symbol cell) ,cell) buffer-undo-list)
4bdf2ad2 3234 (put new-name 'ses-cell rowcol)
b525fd8a 3235 ;; replace name by new name in formula of cells refering to renamed cell
316e68a7
VB
3236 (dolist (ref (ses-cell-references cell))
3237 (let* ((x (ses-sym-rowcol ref))
3238 (xcell (ses-get-cell (car x) (cdr x))))
b525fd8a
VB
3239 (ses-cell-formula-aset xcell
3240 (ses-replace-name-in-formula
3241 (ses-cell-formula xcell)
3242 sym
3243 new-name))))
316e68a7
VB
3244 ;; replace name by new name in reference list of cells to which renamed cell refers to
3245 (dolist (ref (ses-formula-references (ses-cell-formula cell)))
3246 (let* ((x (ses-sym-rowcol ref))
b525fd8a
VB
3247 (xcell (ses-get-cell (car x) (cdr x))))
3248 (ses-cell-references-aset xcell
3249 (cons new-name (delq sym
3250 (ses-cell-references xcell))))))
4bdf2ad2 3251 (push new-name ses--renamed-cell-symb-list)
b525fd8a 3252 (set new-name (symbol-value sym))
4bdf2ad2 3253 (aset cell 0 new-name)
b525fd8a
VB
3254 (put sym 'ses-cell nil)
3255 (makunbound sym)
3256 (setq sym new-name)
4bdf2ad2
VB
3257 (let* ((pos (point))
3258 (inhibit-read-only t)
3259 (col (current-column))
3260 (end (save-excursion
3261 (move-to-column (1+ col))
3262 (if (eolp)
3263 (+ pos (ses-col-width col) 1)
3264 (point)))))
b525fd8a
VB
3265 (put-text-property pos end 'intangible new-name))
3266 ;; update mode line
3267 (setq mode-line-process (list " cell "
3268 (symbol-name sym)))
3269 (force-mode-line-update)))
7ed9159a 3270
58cf70d3
SM
3271;;----------------------------------------------------------------------------
3272;; Checking formulas for safety
3273;;----------------------------------------------------------------------------
7ed9159a
JY
3274
3275(defun ses-safe-printer (printer)
4bdf2ad2 3276 "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
7ed9159a
JY
3277 (if (or (stringp printer)
3278 (stringp (car-safe printer))
3279 (not printer)
3280 (ses-warn-unsafe printer 'unsafep-function))
3281 printer
3282 'ses-unsafe))
3283
3284(defun ses-safe-formula (formula)
4bdf2ad2 3285 "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
7ed9159a
JY
3286 (if (ses-warn-unsafe formula 'unsafep)
3287 formula
3288 `(ses-unsafe ',formula)))
3289
3290(defun ses-warn-unsafe (formula checker)
4bdf2ad2
VB
3291 "Apply CHECKER to FORMULA.
3292If result is non-nil, asks user for confirmation about FORMULA,
3293which might be unsafe. Returns t if formula is safe or user allows
3294execution anyway. Always returns t if `safe-functions' is t."
7ed9159a
JY
3295 (if (eq safe-functions t)
3296 t
3297 (setq checker (funcall checker formula))
3298 (if (not checker)
3299 t
3300 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3301 formula checker)))))
3302
3303
58cf70d3
SM
3304;;----------------------------------------------------------------------------
3305;; Standard formulas
3306;;----------------------------------------------------------------------------
7ed9159a 3307
cedc73f2 3308(defun ses--clean-! (&rest x)
4bdf2ad2 3309 "Clean by `delq' list X from any occurrence of `nil' or `*skip*'."
cedc73f2
VB
3310 (delq nil (delq '*skip* x)))
3311
3312(defun ses--clean-_ (x y)
3313 "Clean list X by replacing by Y any occurrence of `nil' or `*skip*'.
3314
4bdf2ad2 3315This will change X by making `setcar' on its cons cells."
cedc73f2
VB
3316 (let ((ret x) ret-elt)
3317 (while ret
3318 (setq ret-elt (car ret))
3319 (when (memq ret-elt '(nil *skip*))
3320 (setcar ret y))
3321 (setq ret (cdr ret))))
3322 x)
3323
3324(defmacro ses-range (from to &rest rest)
4bdf2ad2 3325 "Expand to a list of cell-symbols for the range going from
cedc73f2
VB
3326FROM up to TO. The range automatically expands to include any
3327new row or column inserted into its middle. The SES library code
3328specifically looks for the symbol `ses-range', so don't create an
3329alias for this macro!
3330
3331By passing in REST some flags one can configure the way the range
3332is read and how it is formatted.
3333
3334In the sequel we assume that cells A1, B1, A2 B2 have respective values
4bdf2ad2 33351 2 3 and 4.
cedc73f2
VB
3336
3337Readout direction is specified by a `>v', '`>^', `<v', `<^',
4bdf2ad2
VB
3338`v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3339of such a flag, a default direction of `^<' is assumed. This
cedc73f2
VB
3340way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3341while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3342
3343If the range is one row, then `>' can be used as a shorthand to
3344`>v' or `>^', and `<' to `<v' or `<^'.
3345
3346If the range is one column, then `v' can be used as a shorthand to
3347`v>' or `v<', and `^' to `^>' or `v<'.
3348
3349A `!' flag will remove all cells whose value is nil or `*skip*'.
3350
3351A `_' flag will replace nil or `*skip*' by the value following
4bdf2ad2 3352the `_' flag. If the `_' flag is the last argument, then they are
cedc73f2
VB
3353replaced by integer 0.
3354
3355A `*', `*1' or `*2' flag will vectorize the range in the sense of
4bdf2ad2 3356Calc. See info node `(Calc) Top'. Flag `*' will output either a
cedc73f2
VB
3357vector or a matrix depending on the number of rows, `*1' will
3358flatten the result to a one row vector, and `*2' will make a
3359matrix whatever the number of rows.
3360
4bdf2ad2
VB
3361Warning: interaction with Calc is experimental and may produce
3362confusing results if you are not aware of Calc data format.
3363Use `math-format-value' as a printer for Calc objects."
cedc73f2
VB
3364 (let (result-row
3365 result
3366 (prev-row -1)
3367 (reorient-x nil)
3368 (reorient-y nil)
3369 transpose vectorize
3370 (clean 'list))
7ed9159a 3371 (ses-dorange (cons from to)
cedc73f2
VB
3372 (when (/= prev-row row)
3373 (push result-row result)
3374 (setq result-row nil))
3375 (push (ses-cell-symbol row col) result-row)
3376 (setq prev-row row))
3377 (push result-row result)
3378 (while rest
3379 (let ((x (pop rest)))
a464a6c7
SM
3380 (pcase x
3381 (`>v (setq transpose nil reorient-x nil reorient-y nil))
3382 (`>^ (setq transpose nil reorient-x nil reorient-y t))
3383 (`<^ (setq transpose nil reorient-x t reorient-y t))
3384 (`<v (setq transpose nil reorient-x t reorient-y nil))
3385 (`v> (setq transpose t reorient-x nil reorient-y t))
3386 (`^> (setq transpose t reorient-x nil reorient-y nil))
3387 (`^< (setq transpose t reorient-x t reorient-y nil))
3388 (`v< (setq transpose t reorient-x t reorient-y t))
3389 ((or `* `*2 `*1) (setq vectorize x))
3390 (`! (setq clean 'ses--clean-!))
3391 (`_ (setq clean `(lambda (&rest x)
3392 (ses--clean-_ x ,(if rest (pop rest) 0)))))
3393 (_
cedc73f2
VB
3394 (cond
3395 ; shorthands one row
3396 ((and (null (cddr result)) (memq x '(> <)))
3397 (push (intern (concat (symbol-name x) "v")) rest))
3398 ; shorthands one col
3399 ((and (null (cdar result)) (memq x '(v ^)))
3400 (push (intern (concat (symbol-name x) ">")) rest))
3401 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3402 (if reorient-y
3403 (setcdr (last result 2) nil)
3404 (setq result (cdr (nreverse result))))
3405 (unless reorient-x
3406 (setq result (mapcar 'nreverse result)))
3407 (when transpose
3408 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3409 (while result
3410 (setq iter ret)
3411 (dolist (elt (pop result))
3412 (setcar iter (cons elt (car iter)))
3413 (setq iter (cdr iter))))
3414 (setq result ret)))
3415
d5c6faf9
SM
3416 (cl-flet ((vectorize-*1
3417 (clean result)
3418 (cons clean (cons (quote 'vec) (apply 'append result))))
3419 (vectorize-*2
3420 (clean result)
3421 (cons clean (cons (quote 'vec)
3422 (mapcar (lambda (x)
3423 (cons clean (cons (quote 'vec) x)))
3424 result)))))
a464a6c7
SM
3425 (pcase vectorize
3426 (`nil (cons clean (apply 'append result)))
3427 (`*1 (vectorize-*1 clean result))
3428 (`*2 (vectorize-*2 clean result))
3429 (`* (funcall (if (cdr result)
3430 #'vectorize-*2
3431 #'vectorize-*1)
3432 clean result))))))
7ed9159a
JY
3433
3434(defun ses-delete-blanks (&rest args)
3435 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3436 (let (result)
3437 (dolist (cur args)
58cf70d3
SM
3438 (unless (memq cur '(nil *skip*))
3439 (push cur result)))
7ed9159a
JY
3440 result))
3441
3442(defun ses+ (&rest args)
3443 "Compute the sum of the arguments, ignoring blanks."
3444 (apply '+ (apply 'ses-delete-blanks args)))
3445
3446(defun ses-average (list)
3447 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3448are ignored. Result is always floating-point, even if all args are integers."
3449 (setq list (apply 'ses-delete-blanks list))
3450 (/ (float (apply '+ list)) (length list)))
3451
3452(defmacro ses-select (fromrange test torange)
4bdf2ad2
VB
3453 "Select cells in FROMRANGE that are `equal' to TEST.
3454For each match, return the corresponding cell from TORANGE.
3455The ranges are macroexpanded but not evaluated so they should be
3456either (ses-range BEG END) or (list ...). The TEST is evaluated."
7ed9159a
JY
3457 (setq fromrange (cdr (macroexpand fromrange))
3458 torange (cdr (macroexpand torange))
3459 test (eval test))
3460 (or (= (length fromrange) (length torange))
3461 (error "ses-select: Ranges not same length"))
3462 (let (result)
3463 (dolist (x fromrange)
3464 (if (equal test (symbol-value x))
3465 (push (car torange) result))
3466 (setq torange (cdr torange)))
3467 (cons 'list result)))
3468
3469;;All standard formulas are safe
ddd1c214
JY
3470(dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3471 ses-select))
7ed9159a
JY
3472 (put x 'side-effect-free t))
3473
3474
58cf70d3
SM
3475;;----------------------------------------------------------------------------
3476;; Standard print functions
3477;;----------------------------------------------------------------------------
7ed9159a 3478
2bb63e81
VB
3479;; These functions use the variables 'row' and 'col' that are dynamically bound
3480;; by ses-print-cell. We define these variables at compile-time to make the
3481;; compiler happy.
28e77c46
GM
3482(defvar row)
3483(defvar col)
7ed9159a
JY
3484
3485(defun ses-center (value &optional span fill)
4bdf2ad2
VB
3486 "Print VALUE, centered within column.
3487FILL is the fill character for centering (default = space).
3488SPAN indicates how many additional rightward columns to include
3489in width (default = 0)."
94be2532 3490 (let ((printer (or (ses-col-printer col) ses--default-printer))
7ed9159a
JY
3491 (width (ses-col-width col))
3492 half)
51616cd5 3493 (or fill (setq fill ?\s))
7ed9159a
JY
3494 (or span (setq span 0))
3495 (setq value (ses-call-printer printer value))
3496 (dotimes (x span)
3497 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
2bb63e81 3498 ;; Set column width.
c0c30dd1 3499 (setq width (- width (string-width value)))
7ed9159a 3500 (if (<= width 0)
2bb63e81 3501 value ; Too large for field, anyway.
7ed9159a
JY
3502 (setq half (make-string (/ width 2) fill))
3503 (concat half value half
3504 (if (> (% width 2) 0) (char-to-string fill))))))
3505
3506(defun ses-center-span (value &optional fill)
3507 "Print VALUE, centered within the span that starts in the current column
4bdf2ad2
VB
3508and continues until the next nonblank column.
3509FILL specifies the fill character (default = space)."
7ed9159a 3510 (let ((end (1+ col)))
94be2532 3511 (while (and (< end ses--numcols)
7ed9159a
JY
3512 (memq (ses-cell-value row end) '(nil *skip*)))
3513 (setq end (1+ end)))
3514 (ses-center value (- end col 1) fill)))
3515
3516(defun ses-dashfill (value &optional span)
4bdf2ad2
VB
3517 "Print VALUE centered using dashes.
3518SPAN indicates how many rightward columns to include in width (default = 0)."
7ed9159a
JY
3519 (ses-center value span ?-))
3520
3521(defun ses-dashfill-span (value)
3522 "Print VALUE, centered using dashes within the span that starts in the
3523current column and continues until the next nonblank column."
3524 (ses-center-span value ?-))
3525
3526(defun ses-tildefill-span (value)
3527 "Print VALUE, centered using tildes within the span that starts in the
3528current column and continues until the next nonblank column."
3529 (ses-center-span value ?~))
3530
3531(defun ses-unsafe (value)
4bdf2ad2 3532 "Substitute for an unsafe formula or printer."
7ed9159a
JY
3533 (error "Unsafe formula or printer"))
3534
3535;;All standard printers are safe, including ses-unsafe!
3536(dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3537 (put x 'side-effect-free t))
3538
7981ad6b
JB
3539(defun ses-unload-function ()
3540 "Unload the Simple Emacs Spreadsheet."
3541 (dolist (fun '(copy-region-as-kill yank))
3542 (ad-remove-advice fun 'around (intern (concat "ses-" (symbol-name fun))))
3543 (ad-update fun))
7981ad6b
JB
3544 ;; continue standard unloading
3545 nil)
3546
7ed9159a
JY
3547(provide 'ses)
3548
58cf70d3 3549;;; ses.el ends here