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