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