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