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