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