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