Reuse `alist-get' in map.el
[emacs.git] / lisp / ses.el
blobe625e4ed59392cf66adba9e348b37f9ce562228c
1 ;;; ses.el -- Simple Emacs Spreadsheet -*- lexical-binding:t -*-
3 ;; Copyright (C) 2002-2015 Free Software Foundation, Inc.
5 ;; Author: Jonathan Yavner <jyavner@member.fsf.org>
6 ;; Maintainer: Vincent Belaïche <vincentb1@users.sourceforge.net>
7 ;; Keywords: spreadsheet Dijkstra
9 ;; This file is part of GNU Emacs.
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.
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.
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/>.
24 ;;; Commentary:
26 ;;; To-do list:
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.
50 ;;; Cycle detection
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.
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.
66 ;;; Code:
68 (require 'unsafep)
69 (require 'macroexp)
70 (eval-when-compile (require 'cl-lib))
73 ;;----------------------------------------------------------------------------
74 ;; User-customizable variables
75 ;;----------------------------------------------------------------------------
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")
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")))
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))))
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))
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))
110 (defcustom ses-mode-hook nil
111 "Hook functions to be run upon entering SES mode."
112 :group 'ses
113 :type 'hook)
116 ;;----------------------------------------------------------------------------
117 ;; Global variables and constants
118 ;;----------------------------------------------------------------------------
120 (defvar ses-read-cell-history nil
121 "List of formulas that have been typed in.")
123 (defvar ses-read-printer-history nil
124 "List of printer functions that have been typed in.")
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)]))
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.")
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]))
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.")
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))
236 ;;Helptext for ses-mode wants keymap as variable, not function
237 (defconst ses-mode-print-map (symbol-function 'ses-mode-print-map))
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))
246 (defconst ses-print-data-boundary "\n\014\n"
247 "Marker string denoting the boundary between print area and data area.")
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.")
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 .")
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.")
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.")
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.")
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.")
286 ;;----------------------------------------------------------------------------
287 ;; Local variables and constants
288 ;;----------------------------------------------------------------------------
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."))
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)))
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)))))
332 ;;; This variable is documented as being permitted in file-locals:
333 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
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.")
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.")
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).
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.")
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.")
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.")
379 ;;----------------------------------------------------------------------------
380 ;; Macros
381 ;;----------------------------------------------------------------------------
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))
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)
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))))
405 compiled
406 number
407 local-printer-list)
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)
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)))
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)))
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)))
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)))
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)))))))
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)))
456 (defmacro ses-cell-property (property-name row &optional col)
457 "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
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))))
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))))
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)))
482 (defmacro ses-col-width (col)
483 "Return the width for column COL."
484 (declare (debug t))
485 `(aref ses--col-widths ,col))
487 (defmacro ses-col-printer (col)
488 "Return the default printer for column COL."
489 (declare (debug t))
490 `(aref ses--col-printers ,col))
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))))))
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))
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))))
531 (defun ses--local-printer (name def)
532 "Define a local printer with name NAME and definition DEF.
533 Return the printer info."
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))
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"))
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)
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)
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)
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))))))))
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)
620 ;;----------------------------------------------------------------------------
621 ;; Utility functions
622 ;;----------------------------------------------------------------------------
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))
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))
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))))
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)
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))))
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))))))
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))))
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)))))
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)))))))
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)))))
730 (defun ses-create-cell-variable (sym row col)
731 "Create a buffer-local variable `SYM' for cell at position (ROW, COL).
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.
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))))
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))
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))
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))))
779 ;;----------------------------------------------------------------------------
780 ;; The cells
781 ;;----------------------------------------------------------------------------
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.
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))))
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)))))
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))))))))
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.
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
901 * property `:corrupt-property' means that
902 property `:ses-repair-reference' of cell CELL was initially non
903 nil,
905 * property `:missing' is a list of missing references
907 * property `:irrelevant' is a list of non needed references
909 %S" errors)
910 (message "No reference corruption found"))))
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)))
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)))))
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))
986 (and cycle-error
987 (error (error-message-string cycle-error)))
988 formula-error printer-error)))
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))
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)
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)))
1058 ;;----------------------------------------------------------------------------
1059 ;; The print area
1060 ;;----------------------------------------------------------------------------
1062 (defun ses-in-print-area ()
1063 "Return t if point is in print area of spreadsheet."
1064 (<= (point) ses--data-marker))
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))))
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))
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))))
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)
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 (if (eq ses--curcell t)
1121 ;; curcell recalculation was postponed, but user typed ahead.
1122 (ses-set-curcell))
1123 (cond
1124 ((not ses--curcell)
1125 (or (memq 'end args)
1126 (error "Not at cell")))
1127 ((consp ses--curcell)
1128 (or (memq 'range args)
1129 (memq 'needrange args)
1130 (error "Can't use a range")))
1131 ((memq 'needrange args)
1132 (error "Need a range"))))
1134 (defvar ses--row)
1135 (defvar ses--col)
1137 (defun ses-print-cell (row col)
1138 "Format and print the value of cell (ROW,COL) to the print area.
1139 Use the cell's printer function. If the cell's new print form is too wide,
1140 it will spill over into the following cell, but will not run off the end of the
1141 row or overwrite the next non-nil field. Result is nil for normal operation,
1142 or the error signal if the printer function failed and the cell was formatted
1143 with \"%s\". If the cell's value is *skip*, nothing is printed because the
1144 preceding cell has spilled over."
1145 (catch 'ses-print-cell
1146 (let* ((cell (ses-get-cell row col))
1147 (value (ses-cell-value cell))
1148 (printer (ses-cell-printer cell))
1149 (maxcol (1+ col))
1150 text sig startpos x)
1151 ;; Create the string to print.
1152 (cond
1153 ((eq value '*skip*)
1154 ;; Don't print anything.
1155 (throw 'ses-print-cell nil))
1156 ((eq value '*error*)
1157 (setq text (make-string (ses-col-width col) ?#)))
1159 ;; Deferred safety-check on printer.
1160 (if (eq (car-safe printer) 'ses-safe-printer)
1161 (ses-set-cell row col 'printer
1162 (setq printer (ses-safe-printer (cadr printer)))))
1163 ;; Print the value.
1164 (setq text
1165 (let ((ses--row row)
1166 (ses--col col))
1167 (ses-call-printer (or printer
1168 (ses-col-printer col)
1169 ses--default-printer)
1170 value)))
1171 (if (consp ses-call-printer-return)
1172 ;; Printer returned an error.
1173 (setq sig ses-call-printer-return))))
1174 ;; Adjust print width to match column width.
1175 (let ((width (ses-col-width col))
1176 (len (string-width text)))
1177 (cond
1178 ((< len width)
1179 ;; Fill field to length with spaces.
1180 (setq len (make-string (- width len) ?\s)
1181 text (if (or (stringp value)
1182 (eq ses-call-printer-return t))
1183 (concat text len)
1184 (concat len text))))
1185 ((> len width)
1186 ;; Spill over into following cells, if possible.
1187 (let ((maxwidth width))
1188 (while (and (> len maxwidth)
1189 (< maxcol ses--numcols)
1190 (or (not (setq x (ses-cell-value row maxcol)))
1191 (eq x '*skip*)))
1192 (unless x
1193 ;; Set this cell to '*skip* so it won't overwrite our spillover.
1194 (ses-set-cell row maxcol 'value '*skip*))
1195 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
1196 maxcol (1+ maxcol)))
1197 (if (<= len maxwidth)
1198 ;; Fill to complete width of all the fields spanned.
1199 (setq text (concat text (make-string (- maxwidth len) ?\s)))
1200 ;; Not enough room to end of line or next non-nil field. Truncate
1201 ;; if string or decimal; otherwise fill with error indicator.
1202 (setq sig `(error "Too wide" ,text))
1203 (cond
1204 ((stringp value)
1205 (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
1206 ((and (numberp value)
1207 (string-match "\\.[0-9]+" text)
1208 (>= 0 (setq width
1209 (- len maxwidth
1210 (- (match-end 0) (match-beginning 0))))))
1211 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
1212 (setq text (concat (substring text
1214 (- (match-beginning 0) width))
1215 (substring text (match-end 0)))))
1217 (setq text (make-string maxwidth ?#)))))))))
1218 ;; Substitute question marks for tabs and newlines. Newlines are used as
1219 ;; row-separators; tabs could confuse the reimport logic.
1220 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
1221 (ses-goto-print row col)
1222 (setq startpos (point))
1223 ;; Install the printed result. This is not interruptible.
1224 (let ((inhibit-read-only t)
1225 (inhibit-quit t))
1226 (delete-region (point) (progn
1227 (move-to-column (+ (current-column)
1228 (string-width text)))
1229 (1+ (point))))
1230 ;; We use concat instead of inserting separate strings in order to
1231 ;; reduce the number of cells in the undo list.
1232 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
1233 ;; We use set-text-properties to prevent a wacky print function from
1234 ;; inserting rogue properties, and to ensure that the keymap property is
1235 ;; inherited (is it a bug that only unpropertized strings actually
1236 ;; inherit from surrounding text?)
1237 (set-text-properties 0 (length x) nil x)
1238 (insert-and-inherit x)
1239 (put-text-property startpos (point) 'cursor-intangible
1240 (ses-cell-symbol cell))
1241 (when (and (zerop row) (zerop col))
1242 ;; Reconstruct special beginning-of-buffer attributes.
1243 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
1244 (put-text-property (point-min) (point) 'read-only 'ses)
1245 (put-text-property (point-min) (1+ (point-min))
1246 ;; `cursor-intangible' shouldn't be sticky at BOB.
1247 'front-sticky '(read-only keymap))))
1248 (if (= row (1- ses--header-row))
1249 ;; This line is part of the header --- force recalc.
1250 (ses-reset-header-string))
1251 ;; If this cell (or a preceding one on the line) previously spilled over
1252 ;; and has gotten shorter, redraw following cells on line recursively.
1253 (when (and (< maxcol ses--numcols)
1254 (eq (ses-cell-value row maxcol) '*skip*))
1255 (ses-set-cell row maxcol 'value nil)
1256 (ses-print-cell row maxcol))
1257 ;; Return to start of cell.
1258 (goto-char startpos)
1259 sig)))
1261 (defun ses-call-printer (printer &optional value)
1262 "Invoke PRINTER (a string or parenthesized string or function-symbol or
1263 lambda of one argument) on VALUE. Result is the printed cell as a string.
1264 The variable `ses-call-printer-return' is set to t if the printer used
1265 parenthesis to request left-justification, or the error-signal if the
1266 printer signaled one (and \"%s\" is used as the default printer), else nil."
1267 (setq ses-call-printer-return nil)
1268 (condition-case signal
1269 (cond
1270 ((stringp printer)
1271 (if value
1272 (format printer value)
1273 ""))
1274 ((stringp (car-safe printer))
1275 (setq ses-call-printer-return t)
1276 (if value
1277 (format (car printer) value)
1278 ""))
1280 (setq value
1281 (funcall
1282 (or (and (symbolp printer)
1283 (let ((locprn (gethash printer
1284 ses--local-printer-hashmap)))
1285 (and locprn
1286 (ses--locprn-compiled locprn))))
1287 printer)
1288 (or value "")))
1289 (if (stringp value)
1290 value
1291 (or (stringp (car-safe value))
1292 (error "Printer should return \"string\" or (\"string\")"))
1293 (setq ses-call-printer-return t)
1294 (car value))))
1295 (error
1296 (setq ses-call-printer-return signal)
1297 (prin1-to-string value t))))
1299 (defun ses-adjust-print-width (col change)
1300 "Insert CHANGE spaces in front of column COL, or at end of line if
1301 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
1302 `inhibit-quit' to t."
1303 (let ((inhibit-read-only t)
1304 (blank (if (> change 0) (make-string change ?\s)))
1305 (at-end (= col ses--numcols)))
1306 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
1307 ;; ses-set-with-undo always returns t for strings.
1308 (1value (ses-set-with-undo 'ses--blank-line
1309 (concat (make-string ses--linewidth ?\s) "\n")))
1310 (dotimes (row ses--numrows)
1311 (ses-goto-print row col)
1312 (when at-end
1313 ;; Insert new columns before newline.
1314 (backward-char 1))
1315 (if blank
1316 (insert blank)
1317 (delete-char (- change))))))
1319 (defun ses-print-cell-new-width (row col)
1320 "Same as `ses-print-cell', except if the cell's value is *skip*,
1321 the preceding nonskipped cell is reprinted. This function is used
1322 when the width of cell (ROW,COL) has changed."
1323 (if (not (eq (ses-cell-value row col) '*skip*))
1324 (ses-print-cell row col)
1325 ;;Cell was skipped over - reprint previous
1326 (ses-goto-print row col)
1327 (backward-char 1)
1328 (let ((rowcol (ses-sym-rowcol (ses--cell-at-pos (point)))))
1329 (ses-print-cell (car rowcol) (cdr rowcol)))))
1332 ;;----------------------------------------------------------------------------
1333 ;; The data area
1334 ;;----------------------------------------------------------------------------
1336 (defun ses-widen ()
1337 "Turn off narrowing, to be reenabled at end of command loop."
1338 (if (buffer-narrowed-p)
1339 (setq ses--deferred-narrow t))
1340 (widen))
1342 (defun ses-goto-data (def &optional col)
1343 "Move point to data area for (DEF,COL). If DEF is a row
1344 number, COL is the column number for a data cell -- otherwise DEF
1345 is one of the symbols ses--col-widths, ses--col-printers,
1346 ses--default-printer, ses--numrows, or ses--numcols."
1347 (ses-widen)
1348 (if col
1349 ;; It's a cell.
1350 (progn
1351 (goto-char ses--data-marker)
1352 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
1353 ;; Convert def-symbol to offset.
1354 (setq def (plist-get ses-paramlines-plist def))
1355 (or def (signal 'args-out-of-range nil))
1356 (goto-char ses--params-marker)
1357 (forward-line def)))
1359 (defun ses-file-format-extend-parameter-list (new-file-format)
1360 "Extend the global parameters list when file format is updated
1361 from 2 to 3. This happens when local printer function are added
1362 to a sheet that was created with SES version 2. This is not
1363 undoable. Return nil when there was no change, and non nil otherwise."
1364 (save-excursion
1365 (cond
1366 ((and (= ses--file-format 2) (= 3 new-file-format))
1367 (ses-set-parameter 'ses--file-format 3)
1368 (message "Upgrading from SES-2 to SES-3 file format")
1369 (ses-widen)
1370 (goto-char ses--params-marker)
1371 (forward-line (plist-get ses-paramlines-plist 'ses--numlocprn ))
1372 (insert (format (plist-get ses-paramfmt-plist 'ses--numlocprn)
1373 ses--numlocprn)
1374 ?\n)
1375 t) )))
1377 (defun ses-set-parameter (def value &optional elem)
1378 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1379 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1380 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
1381 (save-excursion
1382 ;; We call ses-goto-data early, using the old values of numrows and numcols
1383 ;; in case one of them is being changed.
1384 (ses-goto-data def)
1385 (let ((inhibit-read-only t)
1386 (fmt (plist-get ses-paramfmt-plist
1387 def))
1388 oldval)
1389 (if elem
1390 (progn
1391 (setq oldval (aref (symbol-value def) elem))
1392 (aset (symbol-value def) elem value))
1393 (setq oldval (symbol-value def))
1394 (set def value))
1395 ;; Special undo since it's outside the narrowed buffer.
1396 (let (buffer-undo-list)
1397 (delete-region (point) (line-end-position))
1398 (insert (format fmt (symbol-value def))))
1399 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1402 (defun ses-write-cells ()
1403 "Write cells in `ses--deferred-write' from local variables to data area.
1404 Newlines in the data are escaped."
1405 (let* ((inhibit-read-only t)
1406 (print-escape-newlines t)
1407 rowcol row col cell sym formula printer text)
1408 (setq ses-start-time (float-time))
1409 (with-temp-message " "
1410 (save-excursion
1411 (while ses--deferred-write
1412 (ses--time-check "Writing... (%d cells left)"
1413 (length ses--deferred-write))
1414 (setq rowcol (pop ses--deferred-write)
1415 row (car rowcol)
1416 col (cdr rowcol)
1417 cell (ses-get-cell row col)
1418 sym (ses-cell-symbol cell)
1419 formula (ses-cell-formula cell)
1420 printer (ses-cell-printer cell))
1421 (if (eq (car-safe formula) 'ses-safe-formula)
1422 (setq formula (cadr formula)))
1423 (if (eq (car-safe printer) 'ses-safe-printer)
1424 (setq printer (cadr printer)))
1425 (setq text (prin1-to-string
1426 ;; We could shorten it to (ses-cell SYM VAL) when
1427 ;; the other parameters are nil, but in practice most
1428 ;; cells have non-nil `references', so it's
1429 ;; rather pointless.
1430 `(ses-cell ,sym
1431 ,(symbol-value sym)
1432 ,(unless (equal formula (symbol-value sym))
1433 formula)
1434 ,printer
1435 ,(ses-cell-references cell))))
1436 (ses-goto-data row col)
1437 (delete-region (point) (line-end-position))
1438 (insert text)))
1439 (message " "))))
1442 ;;----------------------------------------------------------------------------
1443 ;; Formula relocation
1444 ;;----------------------------------------------------------------------------
1446 (defun ses-formula-references (formula &optional result-so-far)
1447 "Produce a list of symbols for cells that this FORMULA's value
1448 refers to. For recursive calls, RESULT-SO-FAR is the list being
1449 constructed, or t to get a wrong-type-argument error when the
1450 first reference is found."
1451 (if (ses-sym-rowcol formula)
1452 ;; Entire formula is one symbol.
1453 (cl-pushnew formula result-so-far :test #'equal)
1454 (if (consp formula)
1455 (cond
1456 ((eq (car formula) 'ses-range)
1457 (dolist (cur
1458 (cdr (funcall 'macroexpand
1459 (list 'ses-range (nth 1 formula)
1460 (nth 2 formula)))))
1461 (cl-pushnew cur result-so-far :test #'equal)))
1462 ((null (eq (car formula) 'quote))
1463 ;;Recursive call for subformulas
1464 (dolist (cur formula)
1465 (setq result-so-far (ses-formula-references cur result-so-far))))
1467 ;;Ignore other stuff
1469 ;; other type of atom are ignored
1471 result-so-far)
1473 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1474 "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
1475 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1476 by (ROWINCR,COLINCR)."
1477 (let ((row (car rowcol))
1478 (col (cdr rowcol)))
1479 (if (or (< row startrow) (< col startcol))
1481 (setq row (+ row rowincr)
1482 col (+ col colincr))
1483 (if (and (>= row startrow) (>= col startcol)
1484 (< row ses--numrows) (< col ses--numcols))
1485 ;;Relocate this variable
1486 (ses-create-cell-symbol row col)
1487 ;;Delete reference to a deleted cell
1488 nil))))
1490 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1491 "Produce a copy of FORMULA where all symbols that refer to cells in row
1492 STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
1493 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1494 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1495 => (+ A1 B2 C4)
1496 If ROWINCR or COLINCR is negative, references to cells being deleted are
1497 removed. Example:
1498 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1499 => (+ A1 C3)
1500 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1501 (let (rowcol result)
1502 (if (or (atom formula) (eq (car formula) 'quote))
1503 (if (and (setq rowcol (ses-sym-rowcol formula))
1504 (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name formula)))
1505 (ses-relocate-symbol formula rowcol
1506 startrow startcol rowincr colincr)
1507 formula) ; Pass through as-is.
1508 (dolist (cur formula)
1509 (setq rowcol (ses-sym-rowcol cur))
1510 (cond
1511 (rowcol
1512 (setq cur (ses-relocate-symbol cur rowcol
1513 startrow startcol rowincr colincr))
1514 (if cur
1515 (push cur result)
1516 ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
1517 ;; don't change the flag if it's already 'range, since range implies
1518 ;; 'delete.
1519 (unless ses-relocate-return
1520 (setq ses-relocate-return 'delete))))
1521 ((eq (car-safe cur) 'ses-range)
1522 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1523 (if cur
1524 (push cur result)))
1525 ((or (atom cur) (eq (car cur) 'quote))
1526 ;; Constants pass through unchanged.
1527 (push cur result))
1529 ;; Recursively copy and alter subformulas.
1530 (push (ses-relocate-formula cur startrow startcol
1531 rowincr colincr)
1532 result))))
1533 (nreverse result))))
1535 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1536 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1537 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1538 new range, or nil if the entire range is deleted. If new rows are being added
1539 just beyond the end of a row range, or new columns just beyond a column range,
1540 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1541 if the range was altered."
1542 (let* ((minorig (cadr range))
1543 (minrowcol (ses-sym-rowcol minorig))
1544 (min (ses-relocate-symbol minorig minrowcol
1545 startrow startcol
1546 rowincr colincr))
1547 (maxorig (nth 2 range))
1548 (maxrowcol (ses-sym-rowcol maxorig))
1549 (max (ses-relocate-symbol maxorig maxrowcol
1550 startrow startcol
1551 rowincr colincr))
1552 field)
1553 (cond
1554 ((and (not min) (not max))
1555 (setq range nil)) ; The entire range is deleted.
1556 ((zerop colincr)
1557 ;; Inserting or deleting rows.
1558 (setq field 'car)
1559 (if (not min)
1560 ;; Chopped off beginning of range.
1561 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1562 ses-relocate-return 'range))
1563 (if (not max)
1564 (if (> rowincr 0)
1565 ;; Trying to insert a nonexistent row.
1566 (setq max (ses-create-cell-symbol (1- ses--numrows)
1567 (cdr minrowcol)))
1568 ;; End of range is being deleted.
1569 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1570 ses-relocate-return 'range))
1571 (and (> rowincr 0)
1572 (= (car maxrowcol) (1- startrow))
1573 (= (cdr minrowcol) (cdr maxrowcol))
1574 ;; Insert after ending row of vertical range --- include it.
1575 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1576 (cdr maxrowcol))))))
1578 ;; Inserting or deleting columns.
1579 (setq field 'cdr)
1580 (if (not min)
1581 ;; Chopped off beginning of range.
1582 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1583 ses-relocate-return 'range))
1584 (if (not max)
1585 (if (> colincr 0)
1586 ;; Trying to insert a nonexistent column.
1587 (setq max (ses-create-cell-symbol (car maxrowcol)
1588 (1- ses--numcols)))
1589 ;; End of range is being deleted.
1590 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1591 ses-relocate-return 'range))
1592 (and (> colincr 0)
1593 (= (cdr maxrowcol) (1- startcol))
1594 (= (car minrowcol) (car maxrowcol))
1595 ;; Insert after ending column of horizontal range --- include it.
1596 (setq max (ses-create-cell-symbol (car maxrowcol)
1597 (+ startcol colincr -1)))))))
1598 (when range
1599 (if (/= (- (funcall field maxrowcol)
1600 (funcall field minrowcol))
1601 (- (funcall field (ses-sym-rowcol max))
1602 (funcall field (ses-sym-rowcol min))))
1603 ;; This range has changed size.
1604 (setq ses-relocate-return 'range))
1605 `(ses-range ,min ,max ,@(cl-cdddr range)))))
1607 (defun ses-relocate-all (minrow mincol rowincr colincr)
1608 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1609 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1610 to each symbol."
1611 (let (reform)
1612 (let (mycell newval xrow)
1613 (dotimes-with-progress-reporter
1614 (row ses--numrows) "Relocating formulas..."
1615 (dotimes (col ses--numcols)
1616 (setq ses-relocate-return nil
1617 mycell (ses-get-cell row col)
1618 newval (ses-relocate-formula (ses-cell-formula mycell)
1619 minrow mincol rowincr colincr)
1620 xrow (- row rowincr))
1621 (ses-set-cell row col 'formula newval)
1622 (if (eq ses-relocate-return 'range)
1623 ;; This cell contains a (ses-range X Y) where a cell has been
1624 ;; inserted or deleted in the middle of the range.
1625 (push (cons row col) reform))
1626 (if ses-relocate-return
1627 ;; This cell referred to a cell that's been deleted or is no
1628 ;; longer part of the range. We can't fix that now because
1629 ;; reference lists cells have been partially updated.
1630 (cl-pushnew (ses-create-cell-symbol row col)
1631 ses--deferred-recalc :test #'equal))
1632 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1633 minrow mincol rowincr colincr))
1634 (ses-set-cell row col 'references newval)
1635 (and (>= row minrow) (>= col mincol)
1636 (let ((sym (ses-cell-symbol row col))
1637 (xcol (- col colincr)))
1638 (if (and
1640 (>= xrow 0)
1641 (>= xcol 0)
1642 (null (eq sym
1643 (ses-create-cell-symbol xrow xcol))))
1644 ;; This is a renamed cell, do not update the cell
1645 ;; name, but just update the coordinate property.
1646 (put sym 'ses-cell (cons row col))
1647 (ses-set-cell row col 'symbol
1648 (setq sym (ses-create-cell-symbol row col)))
1649 (unless (and (boundp sym) (local-variable-p sym))
1650 (set (make-local-variable sym) nil)
1651 (put sym 'ses-cell (cons row col)))))) )))
1652 ;; Relocate the cell values.
1653 (let (oldval myrow mycol xrow xcol)
1654 (cond
1655 ((and (<= rowincr 0) (<= colincr 0))
1656 ;; Deletion of rows and/or columns.
1657 (dotimes-with-progress-reporter
1658 (row (- ses--numrows minrow)) "Relocating variables..."
1659 (setq myrow (+ row minrow))
1660 (dotimes (col (- ses--numcols mincol))
1661 (setq mycol (+ col mincol)
1662 xrow (- myrow rowincr)
1663 xcol (- mycol colincr))
1664 (let ((sym (ses-cell-symbol myrow mycol))
1665 (xsym (ses-create-cell-symbol xrow xcol)))
1666 ;; Make the value relocation only when if the cell is not
1667 ;; a renamed cell. Otherwise this is not needed.
1668 (and (eq sym xsym)
1669 (ses-set-cell myrow mycol 'value
1670 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1671 (ses-cell-value xrow xcol)
1672 ;;Cell is off the end of the array
1673 (symbol-value xsym))))))))
1675 ((and (wholenump rowincr) (wholenump colincr))
1676 ;; Insertion of rows and/or columns. Run the loop backwards.
1677 (let ((disty (1- ses--numrows))
1678 (distx (1- ses--numcols))
1679 myrow mycol)
1680 (dotimes-with-progress-reporter
1681 (row (- ses--numrows minrow)) "Relocating variables..."
1682 (setq myrow (- disty row))
1683 (dotimes (col (- ses--numcols mincol))
1684 (setq mycol (- distx col)
1685 xrow (- myrow rowincr)
1686 xcol (- mycol colincr))
1687 (if (or (< xrow minrow) (< xcol mincol))
1688 ;; Newly-inserted value.
1689 (setq oldval nil)
1690 ;; Transfer old value.
1691 (setq oldval (ses-cell-value xrow xcol)))
1692 (ses-set-cell myrow mycol 'value oldval)))
1693 t)) ; Make testcover happy by returning non-nil here.
1695 (error "ROWINCR and COLINCR must have the same sign"))))
1696 ;; Reconstruct reference lists for cells that contain ses-ranges that have
1697 ;; changed size.
1698 (when reform
1699 (message "Fixing ses-ranges...")
1700 (let (row col)
1701 (setq ses-start-time (float-time))
1702 (while reform
1703 (ses--time-check "Fixing ses-ranges... (%d left)" (length reform))
1704 (setq row (caar reform)
1705 col (cdar reform)
1706 reform (cdr reform))
1707 (ses-cell-set-formula row col (ses-cell-formula row col))))
1708 (message nil))))
1711 ;;----------------------------------------------------------------------------
1712 ;; Undo control
1713 ;;----------------------------------------------------------------------------
1715 (defun ses-begin-change ()
1716 "For undo, remember point before we start changing hidden stuff."
1717 (let ((inhibit-read-only t))
1718 (insert-and-inherit "X")
1719 (delete-region (1- (point)) (point))))
1721 (defun ses-setter-with-undo (accessors newval &rest args)
1722 "Set a field/variable and record it so it can be undone.
1723 Result is non-nil if field/variable has changed."
1724 (let ((oldval (apply (car accessors) args)))
1725 (unless (equal-including-properties oldval newval)
1726 (push `(apply ses-setter-with-undo ,accessors ,oldval ,@args)
1727 buffer-undo-list)
1728 (apply (cdr accessors) newval args)
1729 t)))
1731 (defun ses-aset-with-undo (array idx newval)
1732 (ses-setter-with-undo (eval-when-compile
1733 (cons #'aref
1734 (lambda (newval array idx) (aset array idx newval))))
1735 newval array idx))
1737 (defun ses-set-with-undo (sym newval)
1738 (ses-setter-with-undo
1739 (eval-when-compile
1740 (cons (lambda (sym) (if (boundp sym) (symbol-value sym) :ses--unbound))
1741 (lambda (newval sym) (if (eq newval :ses--unbound)
1742 (makunbound sym)
1743 (set sym newval)))))
1744 newval sym))
1746 ;;----------------------------------------------------------------------------
1747 ;; Startup for major mode
1748 ;;----------------------------------------------------------------------------
1750 (defun ses-load ()
1751 "Parse the current buffer and set up buffer-local variables.
1752 Does not execute cell formulas or print functions."
1753 (widen)
1754 ;; Read our global parameters, which should be a 3-element list.
1755 (goto-char (point-max))
1756 (search-backward ";; Local Variables:\n" nil t)
1757 (backward-list 1)
1758 (setq ses--params-marker (point-marker))
1759 (let* ((params (ignore-errors (read (current-buffer))))
1760 (params-len (safe-length params)))
1761 (or (and (>= params-len 3)
1762 (<= params-len 4)
1763 (numberp (car params))
1764 (numberp (cadr params))
1765 (>= (cadr params) 0)
1766 (numberp (nth 2 params))
1767 (> (nth 2 params) 0)
1768 (or (<= params-len 3)
1769 (let ((numlocprn (nth 3 params)))
1770 (and (integerp numlocprn) (>= numlocprn 0)))))
1771 (error "Invalid SES file"))
1772 (setq ses--file-format (car params)
1773 ses--numrows (cadr params)
1774 ses--numcols (nth 2 params)
1775 ses--numlocprn (or (nth 3 params) 0))
1776 (when (= ses--file-format 1)
1777 (let (buffer-undo-list) ; This is not undoable.
1778 (ses-goto-data 'ses--header-row)
1779 (insert "(ses-header-row 0)\n")
1780 (ses-set-parameter 'ses--file-format 3)
1781 (message "Upgrading from SES-1 to SES-2 file format")))
1782 (or (<= ses--file-format 3)
1783 (error "This file needs a newer version of the SES library code"))
1784 ;; Initialize cell array.
1785 (setq ses--cells (make-vector ses--numrows nil))
1786 (dotimes (row ses--numrows)
1787 (aset ses--cells row (make-vector ses--numcols nil)))
1788 ;; initialize local printer map.
1789 (clrhash ses--local-printer-hashmap))
1791 ;; Skip over print area, which we assume is correct.
1792 (goto-char (point-min))
1793 (forward-line ses--numrows)
1794 (or (looking-at-p ses-print-data-boundary)
1795 (error "Missing marker between print and data areas"))
1796 (forward-char 1)
1797 (setq ses--data-marker (point-marker))
1798 (forward-char (1- (length ses-print-data-boundary)))
1799 ;; Initialize printer and symbol lists.
1800 (mapc #'ses-printer-record ses-standard-printer-functions)
1801 (setq ses--symbolic-formulas nil)
1803 ;; Load local printer definitions.
1804 ;; This must be loaded *BEFORE* cells and column printers because the latter
1805 ;; may call them.
1806 (save-excursion
1807 (forward-line (* ses--numrows (1+ ses--numcols)))
1808 (let ((numlocprn ses--numlocprn))
1809 (setq ses--numlocprn 0)
1810 (dotimes (_ numlocprn)
1811 (let ((x (read (current-buffer))))
1812 (or (and (looking-at-p "\n")
1813 (eq (car-safe x) 'ses-local-printer)
1814 (apply #'ses--local-printer (cdr x)))
1815 (error "local printer-def error"))
1816 (setq ses--numlocprn (1+ ses--numlocprn))))))
1817 ;; Load cell definitions.
1818 (dotimes (row ses--numrows)
1819 (dotimes (col ses--numcols)
1820 (let* ((x (read (current-buffer)))
1821 (sym (car-safe (cdr-safe x))))
1822 (or (and (looking-at-p "\n")
1823 (eq (car-safe x) 'ses-cell)
1824 (ses-create-cell-variable sym row col))
1825 (error "Cell-def error"))
1826 (apply #'ses--cell (cdr x))))
1827 (or (looking-at-p "\n\n")
1828 (error "Missing blank line between rows")))
1829 ;; Skip local printer function declaration --- that were already loaded.
1830 (forward-line (+ 2 ses--numlocprn))
1831 ;; Load global parameters.
1832 (let ((widths (read (current-buffer)))
1833 (n1 (char-after (point)))
1834 (printers (read (current-buffer)))
1835 (n2 (char-after (point)))
1836 (def-printer (read (current-buffer)))
1837 (n3 (char-after (point)))
1838 (head-row (read (current-buffer)))
1839 (n4 (char-after (point))))
1840 (or (and (eq (car-safe widths) 'ses-column-widths)
1841 (= n1 ?\n)
1842 (eq (car-safe printers) 'ses-column-printers)
1843 (= n2 ?\n)
1844 (eq (car-safe def-printer) 'ses-default-printer)
1845 (= n3 ?\n)
1846 (eq (car-safe head-row) 'ses-header-row)
1847 (= n4 ?\n))
1848 (error "Invalid SES global parameters"))
1849 (1value (eval widths t))
1850 (1value (eval def-printer t))
1851 (1value (eval printers t))
1852 (1value (eval head-row t)))
1853 ;; Should be back at global-params.
1854 (forward-char 1)
1855 (or (looking-at-p ses-initial-global-parameters-re)
1856 (error "Problem with column-defs or global-params"))
1857 ;; Check for overall newline count in definitions area.
1858 (forward-line 3)
1859 (let ((start (point)))
1860 (ses-goto-data 'ses--numrows)
1861 (or (= (point) start)
1862 (error "Extraneous newlines someplace?"))))
1864 (defun ses-setup ()
1865 "Set up for display of only the printed cell values.
1867 Narrows the buffer to show only the print area. Gives it `read-only' and
1868 `intangible' properties. Sets up highlighting for current cell."
1869 (interactive)
1870 (let ((end (point-min))
1871 pos sym)
1872 (with-silent-modifications
1873 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1874 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1875 (mapc #'delete-overlay (overlays-in (point-min) (point-max)))
1876 ;; The print area is read-only (except for our special commands) and
1877 ;; uses a special keymap.
1878 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1879 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1880 ;; For the beginning of the buffer, we want the read-only and keymap
1881 ;; attributes to be inherited from the first character.
1882 (put-text-property (point-min) (1+ (point-min))
1883 ;; `cursor-intangible' shouldn't be sticky at BOB.
1884 'front-sticky '(read-only keymap))
1885 ;; Create intangible properties, which also indicate which cell the text
1886 ;; came from.
1887 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1888 (dotimes (col ses--numcols)
1889 (setq pos end
1890 sym (ses-cell-symbol row col))
1891 (unless (eq (symbol-value sym) '*skip*)
1892 ;; Include skipped cells following this one.
1893 (while (and (< col (1- ses--numcols))
1894 (eq (ses-cell-value row (1+ col)) '*skip*))
1895 (setq end (+ end (ses-col-width col) 1)
1896 ;; Beware: Modifying the iteration variable of `dotimes'
1897 ;; may or may not affect the iteration!
1898 col (1+ col)))
1899 (setq end (save-excursion
1900 (goto-char pos)
1901 (move-to-column (+ (current-column) (- end pos)
1902 (ses-col-width col)))
1903 (if (eolp)
1904 (+ end (ses-col-width col) 1)
1905 (forward-char)
1906 (point))))
1907 (put-text-property pos end 'cursor-intangible sym))))))
1908 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1909 ;; because column A must be at least 1 column wide.
1910 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1911 (overlay-put ses--curcell-overlay 'face 'underline))
1913 (defun ses-cleanup ()
1914 "Cleanup when changing a buffer from SES mode to something else.
1915 Delete overlays, remove special text properties."
1916 (widen)
1917 (let ((inhibit-read-only t)
1918 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1919 ;; user "the file is modified, do you really want to make modifications
1920 ;; to this buffer", where the "modifications" refer to the irrelevant
1921 ;; set-text-properties below.
1922 (buffer-file-name nil)
1923 (was-modified (buffer-modified-p)))
1924 ;; Delete read-only, keymap, and intangible properties.
1925 (set-text-properties (point-min) (point-max) nil)
1926 ;; Delete overlay.
1927 (mapc #'delete-overlay (overlays-in (point-min) (point-max)))
1928 (unless was-modified
1929 (restore-buffer-modified-p nil))))
1931 ;;;###autoload
1932 (defun ses-mode ()
1933 "Major mode for Simple Emacs Spreadsheet.
1935 When you invoke SES in a new buffer, it is divided into cells
1936 that you can enter data into. You can navigate the cells with
1937 the arrow keys and add more cells with the tab key. The contents
1938 of these cells can be numbers, text, or Lisp expressions. (To
1939 enter text, enclose it in double quotes.)
1941 In an expression, you can use cell coordinates to refer to the
1942 contents of another cell. For example, you can sum a range of
1943 cells with `(+ A1 A2 A3)'. There are specialized functions like
1944 `ses+' (addition for ranges with empty cells), `ses-average' (for
1945 performing calculations on cells), and `ses-range' and `ses-select'
1946 \(for extracting ranges of cells).
1948 Each cell also has a print function that controls how it is
1949 displayed.
1951 Each SES buffer is divided into a print area and a data area.
1952 Normally, you can simply use SES to look at and manipulate the print
1953 area, and let SES manage the data area outside the visible region.
1955 See \"ses-example.ses\" (in `data-directory') for an example
1956 spreadsheet, and the Info node `(ses)Top.'
1958 In the following, note the separate keymaps for cell editing mode
1959 and print mode specifications. Key definitions:
1961 \\{ses-mode-map}
1962 These key definitions are active only in the print area (the visible
1963 part):
1964 \\{ses-mode-print-map}
1965 These are active only in the minibuffer, when entering or editing a
1966 formula:
1967 \\{ses-mode-edit-map}"
1968 (interactive)
1969 (unless (and (boundp 'ses--deferred-narrow)
1970 (eq ses--deferred-narrow 'ses-mode))
1971 (kill-all-local-variables)
1972 (ses-set-localvars)
1973 (setq major-mode 'ses-mode
1974 mode-name "SES"
1975 next-line-add-newlines nil
1976 truncate-lines t
1977 ;; SES deliberately puts lots of trailing whitespace in its buffer.
1978 show-trailing-whitespace nil
1979 ;; Cell ranges do not work reasonably without this.
1980 transient-mark-mode t
1981 ;; Not to use tab characters for safe (tabs may do bad for column
1982 ;; calculation).
1983 indent-tabs-mode nil)
1984 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1985 ;; This makes revert impossible if the buffer is read-only.
1986 ;; (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1987 (setq header-line-format '(:eval (progn
1988 (when (/= (window-hscroll)
1989 ses--header-hscroll)
1990 ;; Reset ses--header-hscroll first,
1991 ;; to avoid recursion problems when
1992 ;; debugging ses-create-header-string
1993 (setq ses--header-hscroll
1994 (window-hscroll))
1995 (ses-create-header-string))
1996 ses--header-string)))
1997 (setq-local mode-line-process '(:eval (ses--mode-line-process)))
1998 (add-hook 'pre-redisplay-functions #'ses--cursor-sensor-highlight
1999 ;; Highlight the cell after moving cursor out of intangible.
2000 'append t)
2001 (cursor-intangible-mode 1)
2002 (let ((was-empty (zerop (buffer-size)))
2003 (was-modified (buffer-modified-p)))
2004 (save-excursion
2005 (if was-empty
2006 ;; Initialize buffer to contain one cell, for now.
2007 (insert ses-initial-file-contents))
2008 (ses-load)
2009 (ses-setup))
2010 (when was-empty
2011 (unless (equal ses-initial-default-printer
2012 (1value ses--default-printer))
2013 (1value (ses-read-default-printer ses-initial-default-printer)))
2014 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
2015 (1value (ses-set-column-width 0 ses-initial-column-width)))
2016 (ses-set-curcell)
2017 (if (> (car ses-initial-size) (1value ses--numrows))
2018 (1value (ses-insert-row (1- (car ses-initial-size)))))
2019 (if (> (cdr ses-initial-size) (1value ses--numcols))
2020 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
2021 (ses-write-cells)
2022 (restore-buffer-modified-p was-modified)
2023 (buffer-disable-undo)
2024 (buffer-enable-undo)
2025 (goto-char (point-min))))
2026 (use-local-map ses-mode-map)
2027 ;; Set the deferred narrowing flag (we can't narrow until after
2028 ;; after-find-file completes). If .ses is on the auto-load alist and the
2029 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
2030 ;; special flag to detect this (will be reset by ses-command-hook). For
2031 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
2032 ;; so use an idle timer to make sure.
2033 (setq ses--deferred-narrow 'ses-mode)
2034 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
2035 (run-with-idle-timer 0.01 nil 'ses-command-hook)
2036 (run-mode-hooks 'ses-mode-hook)))
2038 (put 'ses-mode 'mode-class 'special)
2040 (defun ses-command-hook ()
2041 "Invoked from `post-command-hook'. If point has moved to a different cell,
2042 moves the underlining overlay. Performs any recalculations or cell-data
2043 writes that have been deferred. If buffer-narrowing has been deferred,
2044 narrows the buffer now."
2045 (condition-case err
2046 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
2047 (when ses--deferred-recalc
2048 ;; We reset the deferred list before starting on the recalc --- in
2049 ;; case of error, we don't want to retry the recalc after every
2050 ;; keystroke!
2051 (ses-initialize-Dijkstra-attempt)
2052 (let ((old ses--deferred-recalc))
2053 (setq ses--deferred-recalc nil)
2054 (ses-update-cells old)))
2055 (when ses--deferred-write
2056 ;; We don't reset the deferred list before starting --- the most
2057 ;; likely error is keyboard-quit, and we do want to keep trying these
2058 ;; writes after a quit.
2059 (ses-write-cells)
2060 (push '(apply ses-widen) buffer-undo-list))
2061 (when ses--deferred-narrow
2062 ;; We're not allowed to narrow the buffer until after-find-file has
2063 ;; read the local variables at the end of the file. Now it's safe to
2064 ;; do the narrowing.
2065 (narrow-to-region (point-min) ses--data-marker)
2066 (setq ses--deferred-narrow nil)))
2067 ;; Prevent errors in this post-command-hook from silently erasing the hook!
2068 (error
2069 (unless executing-kbd-macro
2070 (ding))
2071 (message "%s" (error-message-string err))))
2072 nil) ; Make coverage-tester happy.
2074 (defun ses--mode-line-process ()
2075 (let ((cmlp (window-parameter nil 'ses--mode-line-process))
2076 (curcell (ses--curcell (window-point))))
2077 (if (equal curcell (car cmlp))
2078 (cdr cmlp)
2079 (let ((mlp
2080 (cond
2081 ((not curcell) nil)
2082 ((atom curcell) (list " cell " (symbol-name curcell)))
2084 (list " range "
2085 (symbol-name (car curcell))
2087 (symbol-name (cdr curcell)))))))
2088 (set-window-parameter nil 'ses--mode-line-process (cons curcell mlp))
2089 mlp))))
2091 (defun ses--cursor-sensor-highlight (window)
2092 (let ((curcell (ses--curcell))
2093 (ol (window-parameter window 'ses--curcell-overlay)))
2094 (unless ol
2095 (setq ol (make-overlay (point) (point)))
2096 (overlay-put ol 'window window)
2097 (overlay-put ol 'face 'underline)
2098 (set-window-parameter window 'ses--curcell-overlay ol))
2099 ;; Use underline overlay for single-cells only, turn off otherwise.
2100 (if (listp curcell)
2101 (delete-overlay ol)
2102 (let* ((pos (window-point window))
2103 (next (next-single-property-change pos 'cursor-intangible)))
2104 (move-overlay ol pos (1- next))))))
2106 (defun ses-create-header-string ()
2107 "Set up `ses--header-string' as the buffer's header line.
2108 Based on the current set of columns and `window-hscroll' position."
2109 (let ((totwidth (- (window-hscroll)))
2110 result width x)
2111 ;; Leave room for the left-side fringe and scrollbar.
2112 (push (propertize " " 'display '((space :align-to 0))) result)
2113 (dotimes (col ses--numcols)
2114 (setq width (ses-col-width col)
2115 totwidth (+ totwidth width 1))
2116 (if (= totwidth 1)
2117 ;; Scrolled so intercolumn space is leftmost.
2118 (push " " result))
2119 (when (> totwidth 1)
2120 (if (> ses--header-row 0)
2121 (save-excursion
2122 (ses-goto-print (1- ses--header-row) col)
2123 (setq x (buffer-substring-no-properties (point)
2124 (+ (point) width)))
2125 ;; Strip trailing space.
2126 (if (string-match "[ \t]+\\'" x)
2127 (setq x (substring x 0 (match-beginning 0))))
2128 ;; Cut off excess text.
2129 (if (>= (length x) totwidth)
2130 (setq x (substring x 0 (- totwidth -1)))))
2131 (setq x (ses-column-letter col)))
2132 (push (propertize x 'face ses-box-prop) result)
2133 (push (propertize "."
2134 'display `((space :align-to ,(1- totwidth)))
2135 'face ses-box-prop)
2136 result)
2137 ;; Allow the following space to be squished to make room for the 3-D box
2138 ;; Coverage test ignores properties, thinks this is always a space!
2139 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2140 result)))
2141 (if (> ses--header-row 0)
2142 (push (propertize (format " [row %d]" ses--header-row)
2143 'display '((height (- 1))))
2144 result))
2145 (setq ses--header-string (apply #'concat (nreverse result)))))
2148 ;;----------------------------------------------------------------------------
2149 ;; Redisplay and recalculation
2150 ;;----------------------------------------------------------------------------
2152 (defun ses-jump (sym)
2153 "Move point to cell SYM."
2154 (interactive "SJump to cell: ")
2155 (let ((rowcol (ses-sym-rowcol sym)))
2156 (or rowcol (error "Invalid cell name"))
2157 (if (eq (symbol-value sym) '*skip*)
2158 (error "Cell is covered by preceding cell"))
2159 (ses-goto-print (car rowcol) (cdr rowcol))))
2161 (defun ses-jump-safe (cell)
2162 "Like `ses-jump', but no error if invalid cell."
2163 (ignore-errors
2164 (ses-jump cell)))
2166 (defun ses-reprint-all (&optional nonarrow)
2167 "Recreate the display area. Calls all printer functions. Narrows to
2168 print area if NONARROW is nil."
2169 (interactive "*P")
2170 (widen)
2171 (unless nonarrow
2172 (setq ses--deferred-narrow t))
2173 (let ((startcell (ses--cell-at-pos (point)))
2174 (inhibit-read-only t))
2175 (ses-begin-change)
2176 (goto-char (point-min))
2177 (search-forward ses-print-data-boundary)
2178 (backward-char (length ses-print-data-boundary))
2179 (delete-region (point-min) (point))
2180 ;; Insert all blank lines before printing anything, so ses-print-cell can
2181 ;; find the data area when inserting or deleting *skip* values for cells.
2182 (dotimes (_ ses--numrows)
2183 (insert-and-inherit ses--blank-line))
2184 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2185 (if (eq (ses-cell-value row 0) '*skip*)
2186 ;; Column deletion left a dangling skip.
2187 (ses-set-cell row 0 'value nil))
2188 (dotimes (col ses--numcols)
2189 (ses-print-cell row col))
2190 (beginning-of-line 2))
2191 (ses-jump-safe startcell)))
2193 (defun ses-initialize-Dijkstra-attempt ()
2194 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2195 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2197 ;; These functions use the variables 'row' and 'col' that are dynamically bound
2198 ;; by ses-print-cell. We define these variables at compile-time to make the
2199 ;; compiler happy.
2200 ;; (defvar row)
2201 ;; (defvar col)
2202 ;; (defvar maxrow)
2203 ;; (defvar maxcol)
2205 (defun ses-recalculate-cell ()
2206 "Recalculate and reprint the current cell or range.
2208 For an individual cell, shows the error if the formula or printer
2209 signals one, or otherwise shows the cell's complete value. For a range, the
2210 cells are recalculated in \"natural\" order, so cells that other cells refer
2211 to are recalculated first."
2212 (interactive "*")
2213 (ses-check-curcell 'range)
2214 (ses-begin-change)
2215 (ses-initialize-Dijkstra-attempt)
2216 (let (sig cur-rowcol)
2217 (setq ses-start-time (float-time))
2218 (if (atom ses--curcell)
2219 (when
2220 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2221 sig (progn
2222 (setf (ses-cell-property :ses-Dijkstra-attempt
2223 (car cur-rowcol)
2224 (cdr cur-rowcol))
2225 (cons ses--Dijkstra-attempt-nb 0))
2226 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2227 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2228 (cdr cur-rowcol)))))
2229 ;; First, recalculate all cells that don't refer to other cells and
2230 ;; produce a list of cells with references.
2231 (ses-dorange ses--curcell
2232 (ses--time-check "Recalculating... %s" (ses-cell-symbol row col))
2233 (condition-case nil
2234 (progn
2235 ;; The t causes an error if the cell has references. If no
2236 ;; references, the t will be the result value.
2237 (1value (ses-formula-references (ses-cell-formula row col) t))
2238 (setf (ses-cell-property :ses-Dijkstra-attempt row col)
2239 (cons ses--Dijkstra-attempt-nb 0))
2240 (when (setq sig (ses-calculate-cell row col t))
2241 (nconc sig (list (ses-cell-symbol row col)))))
2242 (wrong-type-argument
2243 ;; The formula contains a reference.
2244 (cl-pushnew (ses-cell-symbol row col) ses--deferred-recalc
2245 :test #'equal)))))
2246 ;; Do the update now, so we can force recalculation.
2247 (let ((x ses--deferred-recalc))
2248 (setq ses--deferred-recalc nil)
2249 (condition-case hold
2250 (ses-update-cells x t)
2251 (error (setq sig hold))))
2252 (cond
2253 (sig
2254 (message "%s" (error-message-string sig)))
2255 ((consp ses--curcell)
2256 (message " "))
2258 (princ (symbol-value ses--curcell))))))
2260 (defun ses-recalculate-all ()
2261 "Recalculate and reprint all cells."
2262 (interactive "*")
2263 (let ((startcell (ses--cell-at-pos (point)))
2264 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2265 (1- ses--numcols)))))
2266 (ses-recalculate-cell)
2267 (ses-jump-safe startcell)))
2269 (defun ses-truncate-cell ()
2270 "Reprint current cell, but without spillover into any following blank cells."
2271 (interactive "*")
2272 (ses-check-curcell)
2273 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2274 (row (car rowcol))
2275 (col (cdr rowcol)))
2276 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
2277 (eq (ses-cell-value row (1+ col)) '*skip*))
2278 ;; This cell has spill-over. We'll momentarily pretend the following cell
2279 ;; has a t in it.
2280 (cl-progv
2281 (list (ses-cell-symbol row (1+ col)))
2282 '(t)
2283 (ses-print-cell row col))
2284 ;; Now remove the *skip*. ses-print-cell is always nil here.
2285 (ses-set-cell row (1+ col) 'value nil)
2286 (1value (ses-print-cell row (1+ col))))))
2288 (defun ses-reconstruct-all ()
2289 "Reconstruct buffer based on cell data stored in Emacs variables."
2290 (interactive "*")
2291 (ses-begin-change)
2292 ;;Reconstruct reference lists.
2293 (let (x yrow ycol)
2294 ;;Delete old reference lists
2295 (dotimes-with-progress-reporter
2296 (row ses--numrows) "Deleting references..."
2297 (dotimes (col ses--numcols)
2298 (ses-set-cell row col 'references nil)))
2299 ;;Create new reference lists
2300 (dotimes-with-progress-reporter
2301 (row ses--numrows) "Computing references..."
2302 (dotimes (col ses--numcols)
2303 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2304 (setq x (ses-sym-rowcol ref)
2305 yrow (car x)
2306 ycol (cdr x))
2307 (ses-set-cell yrow ycol 'references
2308 (cons (ses-cell-symbol row col)
2309 (ses-cell-references yrow ycol)))))))
2310 ;; Delete everything and reconstruct basic data area.
2311 (ses-widen)
2312 (let ((inhibit-read-only t))
2313 (goto-char (point-max))
2314 (if (search-backward ";; Local Variables:\n" nil t)
2315 (delete-region (point-min) (point))
2316 ;; Buffer is quite screwed up --- can't even save the user-specified
2317 ;; locals.
2318 (delete-region (point-min) (point-max))
2319 (insert ses-initial-file-trailer)
2320 (goto-char (point-min)))
2321 ;; Create a blank display area.
2322 (dotimes (_ ses--numrows)
2323 (insert ses--blank-line))
2324 (insert ses-print-data-boundary)
2325 (backward-char (1- (length ses-print-data-boundary)))
2326 (setq ses--data-marker (point-marker))
2327 (forward-char (1- (length ses-print-data-boundary)))
2328 ;; Placeholders for cell data.
2329 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2330 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
2331 (insert "\n\n\n\n")
2332 (insert ses-initial-global-parameters)
2333 (backward-char (1- (length ses-initial-global-parameters)))
2334 (setq ses--params-marker (point-marker))
2335 (forward-char (1- (length ses-initial-global-parameters))))
2336 (ses-set-parameter 'ses--col-widths ses--col-widths)
2337 (ses-set-parameter 'ses--col-printers ses--col-printers)
2338 (ses-set-parameter 'ses--default-printer ses--default-printer)
2339 (ses-set-parameter 'ses--header-row ses--header-row)
2340 (ses-set-parameter 'ses--numrows ses--numrows)
2341 (ses-set-parameter 'ses--numcols ses--numcols)
2342 ;;Keep our old narrowing
2343 (ses-setup)
2344 (ses-recalculate-all)
2345 (goto-char (point-min)))
2348 ;;----------------------------------------------------------------------------
2349 ;; Input of cell formulas
2350 ;;----------------------------------------------------------------------------
2352 (defun ses-edit-cell (row col newval)
2353 "Display current cell contents in minibuffer, for editing. Returns nil if
2354 cell formula was unsafe and user declined confirmation."
2355 (interactive
2356 (progn
2357 (barf-if-buffer-read-only)
2358 (ses-check-curcell)
2359 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2360 (row (car rowcol))
2361 (col (cdr rowcol))
2362 (formula (ses-cell-formula row col))
2363 initial)
2364 (if (eq (car-safe formula) 'ses-safe-formula)
2365 (setq formula (cadr formula)))
2366 (if (eq (car-safe formula) 'quote)
2367 (setq initial (format "'%S" (cadr formula)))
2368 (setq initial (prin1-to-string formula)))
2369 (if (stringp formula)
2370 ;; Position cursor inside close-quote.
2371 (setq initial (cons initial (length initial))))
2372 (list row col
2373 (read-from-minibuffer (format "Cell %s: " ses--curcell)
2374 initial
2375 ses-mode-edit-map
2376 t ; Convert to Lisp object.
2377 'ses-read-cell-history)))))
2378 (when (ses-warn-unsafe newval 'unsafep)
2379 (ses-begin-change)
2380 (ses-cell-set-formula row col newval)
2383 (defun ses-read-cell (row col newval)
2384 "Self-insert for initial character of cell function."
2385 (interactive
2386 (let* ((initial (this-command-keys))
2387 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2388 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
2389 (barf-if-buffer-read-only)
2390 (list (car rowcol)
2391 (cdr rowcol)
2392 (if (equal initial "\"")
2393 (progn
2394 (if (not (stringp curval)) (setq curval nil))
2395 (read-string (if curval
2396 (format "String Cell %s (default %s): "
2397 ses--curcell curval)
2398 (format "String Cell %s: " ses--curcell))
2399 nil 'ses-read-string-history curval))
2400 (read-from-minibuffer
2401 (format "Cell %s: " ses--curcell)
2402 (cons (if (equal initial "(") "()" initial) 2)
2403 ses-mode-edit-map
2404 t ; Convert to Lisp object.
2405 'ses-read-cell-history
2406 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2407 (cadr curval)
2408 curval)))))))
2409 (when (ses-edit-cell row col newval)
2410 (ses-command-hook) ; Update cell widths before movement.
2411 (dolist (x ses-after-entry-functions)
2412 (funcall x 1))))
2414 (defun ses-read-symbol (row col symb)
2415 "Self-insert for a symbol as a cell formula. The set of all symbols that
2416 have been used as formulas in this spreadsheet is available for completions."
2417 (interactive
2418 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2419 newval)
2420 (barf-if-buffer-read-only)
2421 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2422 ses--symbolic-formulas))
2423 (list (car rowcol)
2424 (cdr rowcol)
2425 (if (string= newval "")
2426 nil ; Don't create zero-length symbols!
2427 (list 'quote (intern newval))))))
2428 (when (ses-edit-cell row col symb)
2429 (ses-command-hook) ; Update cell widths before movement.
2430 (dolist (x ses-after-entry-functions)
2431 (funcall x 1))))
2433 (defun ses-clear-cell-forward (count)
2434 "Delete formula and printer for current cell and then move to next cell.
2435 With prefix, deletes several cells."
2436 (interactive "*p")
2437 (if (< count 0)
2438 (1value (ses-clear-cell-backward (- count)))
2439 (ses-check-curcell)
2440 (ses-begin-change)
2441 (dotimes (_ count)
2442 (ses-set-curcell)
2443 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2444 (or rowcol (signal 'end-of-buffer nil))
2445 (ses-clear-cell (car rowcol) (cdr rowcol)))
2446 (forward-char 1))))
2448 (defun ses-clear-cell-backward (count)
2449 "Move to previous cell and then delete it. With prefix, deletes several
2450 cells."
2451 (interactive "*p")
2452 (if (< count 0)
2453 (1value (ses-clear-cell-forward (- count)))
2454 (ses-check-curcell 'end)
2455 (ses-begin-change)
2456 (dotimes (_ count)
2457 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
2458 (ses-set-curcell)
2459 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2460 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2463 ;;----------------------------------------------------------------------------
2464 ;; Input of cell-printer functions
2465 ;;----------------------------------------------------------------------------
2467 (defun ses-read-printer (prompt default)
2468 "Common code for functions `ses-read-cell-printer', `ses-read-column-printer',
2469 `ses-read-default-printer' and `ses-define-local-printer'.
2470 PROMPT should end with \": \". Result is t if operation was
2471 canceled."
2472 (barf-if-buffer-read-only)
2473 (if (eq default t)
2474 (setq default "")
2475 (setq prompt (format "%s (default %S): "
2476 (substring prompt 0 -2)
2477 default)))
2478 (let ((new (read-from-minibuffer prompt
2479 nil ; Initial contents.
2480 ses-mode-edit-map
2481 t ; Evaluate the result.
2482 'ses-read-printer-history
2483 (prin1-to-string default))))
2484 (if (equal new default)
2485 ;; User changed mind, decided not to change printer.
2486 (setq new t)
2487 (ses-printer-validate new)
2488 (or (not new)
2489 (stringp new)
2490 (stringp (car-safe new))
2491 (and (symbolp new) (gethash new ses--local-printer-hashmap))
2492 (ses-warn-unsafe new 'unsafep-function)
2493 (setq new t)))
2494 new))
2496 (defun ses-read-cell-printer (newval)
2497 "Set the printer function for the current cell or range.
2499 A printer function is either a string (a format control-string with one
2500 %-sequence -- result from format will be right-justified), or a list of one
2501 string (result from format will be left-justified), or a lambda-expression of
2502 one argument, or a symbol that names a function of one argument. In the
2503 latter two cases, the function's result should be either a string (will be
2504 right-justified) or a list of one string (will be left-justified)."
2505 (interactive
2506 (let ((default t))
2507 (ses-check-curcell 'range)
2508 ;;Default is none if not all cells in range have same printer
2509 (catch 'ses-read-cell-printer
2510 (ses-dorange ses--curcell
2511 (let ((x (ses-cell-printer row col)))
2512 (if (eq (car-safe x) 'ses-safe-printer)
2513 (setq x (cadr x)))
2514 (if (eq default t)
2515 (setq default x)
2516 (unless (equal default x)
2517 ;;Range contains differing printer functions
2518 (setq default t)
2519 (throw 'ses-read-cell-printer t))))))
2520 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2521 default))))
2522 (unless (eq newval t)
2523 (ses-begin-change)
2524 (ses-dorange ses--curcell
2525 (ses-set-cell row col 'printer newval)
2526 (ses-print-cell row col))))
2528 (defun ses-read-column-printer (col newval)
2529 "Set the printer function for the current column.
2530 See `ses-read-cell-printer' for input forms."
2531 (interactive
2532 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2533 (ses-check-curcell)
2534 (list col (ses-read-printer (format "Column %s printer: "
2535 (ses-column-letter col))
2536 (ses-col-printer col)))))
2538 (unless (eq newval t)
2539 (ses-begin-change)
2540 (ses-set-parameter 'ses--col-printers newval col)
2541 (save-excursion
2542 (dotimes (row ses--numrows)
2543 (ses-print-cell row col)))))
2545 (defun ses-read-default-printer (newval)
2546 "Set the default printer function for cells that have no other.
2547 See `ses-read-cell-printer' for input forms."
2548 (interactive
2549 (list (ses-read-printer "Default printer: " ses--default-printer)))
2550 (unless (eq newval t)
2551 (ses-begin-change)
2552 (ses-set-parameter 'ses--default-printer newval)
2553 (ses-reprint-all t)))
2556 ;;----------------------------------------------------------------------------
2557 ;; Spreadsheet size adjustments
2558 ;;----------------------------------------------------------------------------
2560 (defun ses-insert-row (count)
2561 "Insert a new row before the current one.
2562 With prefix, insert COUNT rows before current one."
2563 (interactive "*p")
2564 (ses-check-curcell 'end)
2565 (or (> count 0) (signal 'args-out-of-range nil))
2566 (ses-begin-change)
2567 (let ((inhibit-quit t)
2568 (inhibit-read-only t)
2569 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2570 newrow)
2571 ;;Create a new set of cell-variables
2572 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2573 0 (1- ses--numcols))
2574 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2575 ;;Insert each row
2576 (ses-goto-print row 0)
2577 (dotimes-with-progress-reporter (x count) "Inserting row..."
2578 ;;Create a row of empty cells. The `symbol' fields will be set by
2579 ;;the call to ses-relocate-all.
2580 (setq newrow (make-vector ses--numcols nil))
2581 (dotimes (col ses--numcols)
2582 (aset newrow col (ses-make-cell)))
2583 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2584 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2585 (insert ses--blank-line))
2586 ;;Insert empty lines in cell data area (will be replaced by
2587 ;;ses-relocate-all)
2588 (ses-goto-data row 0)
2589 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2590 (ses-relocate-all row 0 count 0)
2591 ;;If any cell printers insert constant text, insert that text
2592 ;;into the line.
2593 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2594 (global (ses-call-printer ses--default-printer)))
2595 (if (or (> (length cols) 0) (> (length global) 0))
2596 (dotimes (x count)
2597 (dotimes (col ses--numcols)
2598 ;;These cells are always nil, only constant formatting printed
2599 (1value (ses-print-cell (+ x row) col))))))
2600 (when (> ses--header-row row)
2601 ;;Inserting before header
2602 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2603 (ses-reset-header-string)))
2604 ;;Reconstruct text attributes
2605 (ses-setup)
2606 ;;Prepare for undo
2607 (push '(apply ses-widen) buffer-undo-list)
2608 ;;Return to current cell
2609 (if ses--curcell
2610 (ses-jump-safe ses--curcell)
2611 (ses-goto-print (1- ses--numrows) 0)))
2613 (defun ses-delete-row (count)
2614 "Delete the current row.
2615 With prefix, deletes COUNT rows starting from the current one."
2616 (interactive "*p")
2617 (ses-check-curcell)
2618 (or (> count 0) (signal 'args-out-of-range nil))
2619 (let ((inhibit-quit t)
2620 (inhibit-read-only t)
2621 (row (car (ses-sym-rowcol ses--curcell))))
2622 (setq count (min count (- ses--numrows row)))
2623 (ses-begin-change)
2624 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2625 ;;Delete lines from print area
2626 (ses-goto-print row 0)
2627 (ses-delete-line count)
2628 ;;Delete lines from cell data area
2629 (ses-goto-data row 0)
2630 (ses-delete-line (* count (1+ ses--numcols)))
2631 ;;Relocate variables and formulas
2632 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2633 (ses-relocate-all row 0 (- count) 0)
2634 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2635 0 (1- ses--numcols))
2636 (when (> ses--header-row row)
2637 (if (<= ses--header-row (+ row count))
2638 ;;Deleting the header row
2639 (ses-set-parameter 'ses--header-row 0)
2640 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2641 (ses-reset-header-string)))
2642 ;;Reconstruct attributes
2643 (ses-setup)
2644 ;;Prepare for undo
2645 (push '(apply ses-widen) buffer-undo-list)
2646 (ses-jump-safe ses--curcell))
2648 (defun ses-insert-column (count &optional col width printer)
2649 "Insert a new column before COL (default is the current one).
2650 With prefix, insert COUNT columns before current one.
2651 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2652 \(otherwise they're taken from the current column)."
2653 (interactive "*p")
2654 (ses-check-curcell)
2655 (or (> count 0) (signal 'args-out-of-range nil))
2656 (or col
2657 (setq col (cdr (ses-sym-rowcol ses--curcell))
2658 width (ses-col-width col)
2659 printer (ses-col-printer col)))
2660 (ses-begin-change)
2661 (let ((inhibit-quit t)
2662 (inhibit-read-only t)
2663 (widths ses--col-widths)
2664 (printers ses--col-printers)
2665 has-skip)
2666 ;;Create a new set of cell-variables
2667 (ses-create-cell-variable-range 0 (1- ses--numrows)
2668 ses--numcols (+ ses--numcols count -1))
2669 ;;Insert each column.
2670 (dotimes-with-progress-reporter (x count) "Inserting column..."
2671 ;;Create a column of empty cells. The `symbol' fields will be set by
2672 ;;the call to ses-relocate-all.
2673 (ses-adjust-print-width col (1+ width))
2674 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2675 (dotimes (row ses--numrows)
2676 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2677 ;;Inserting in the middle of a spill-over
2678 (setq has-skip t))
2679 (ses-aset-with-undo ses--cells row
2680 (ses-vector-insert (aref ses--cells row)
2681 col (ses-make-cell)))
2682 ;;Insert empty lines in cell data area (will be replaced by
2683 ;;ses-relocate-all)
2684 (ses-goto-data row col)
2685 (insert ?\n))
2686 ;; Insert column width and printer.
2687 (setq widths (ses-vector-insert widths col width)
2688 printers (ses-vector-insert printers col printer)))
2689 (ses-set-parameter 'ses--col-widths widths)
2690 (ses-set-parameter 'ses--col-printers printers)
2691 (ses-reset-header-string)
2692 (ses-relocate-all 0 col 0 count)
2693 (if has-skip
2694 (ses-reprint-all t)
2695 (when (or (> (length (ses-call-printer printer)) 0)
2696 (> (length (ses-call-printer ses--default-printer)) 0))
2697 ;; Either column printer or global printer inserts some constant text.
2698 ;; Reprint the new columns to insert that text.
2699 (dotimes (x ses--numrows)
2700 (dotimes (y count)
2701 ;; Always nil here --- this is a blank column.
2702 (1value (ses-print-cell-new-width x (+ y col))))))
2703 (ses-setup)))
2704 (ses-jump-safe ses--curcell))
2706 (defun ses-delete-column (count)
2707 "Delete the current column.
2708 With prefix, deletes COUNT columns starting from the current one."
2709 (interactive "*p")
2710 (ses-check-curcell)
2711 (or (> count 0) (signal 'args-out-of-range nil))
2712 (let ((inhibit-quit t)
2713 (inhibit-read-only t)
2714 (rowcol (ses-sym-rowcol ses--curcell))
2715 (width 0)
2716 col origrow has-skip)
2717 (setq origrow (car rowcol)
2718 col (cdr rowcol)
2719 count (min count (- ses--numcols col)))
2720 (if (= count ses--numcols)
2721 (error "Can't delete all columns!"))
2722 ;;Determine width of column(s) being deleted
2723 (dotimes (x count)
2724 (setq width (+ width (ses-col-width (+ col x)) 1)))
2725 (ses-begin-change)
2726 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2727 (ses-adjust-print-width col (- width))
2728 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2729 ;;Delete lines from cell data area
2730 (ses-goto-data row col)
2731 (ses-delete-line count)
2732 ;;Delete cells. Check if deletion area begins or ends with a skip.
2733 (if (or (eq (ses-cell-value row col) '*skip*)
2734 (and (< col ses--numcols)
2735 (eq (ses-cell-value row (+ col count)) '*skip*)))
2736 (setq has-skip t))
2737 (ses-aset-with-undo ses--cells row
2738 (ses-vector-delete (aref ses--cells row) col count)))
2739 ;;Update globals
2740 (ses-set-parameter 'ses--col-widths
2741 (ses-vector-delete ses--col-widths col count))
2742 (ses-set-parameter 'ses--col-printers
2743 (ses-vector-delete ses--col-printers col count))
2744 (ses-reset-header-string)
2745 ;;Relocate variables and formulas
2746 (ses-relocate-all 0 col 0 (- count))
2747 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2748 ses--numcols (+ ses--numcols count -1))
2749 (if has-skip
2750 (ses-reprint-all t)
2751 (ses-setup))
2752 (if (>= col ses--numcols)
2753 (setq col (1- col)))
2754 (ses-goto-print origrow col)))
2756 (defun ses-forward-or-insert (&optional count)
2757 "Move to next cell in row, or inserts a new cell if already in last one, or
2758 inserts a new row if at bottom of print area. Repeat COUNT times."
2759 (interactive "p")
2760 (ses-check-curcell 'end)
2761 (setq deactivate-mark t) ; Doesn't combine well with ranges.
2762 (dotimes (x count)
2763 (ses-set-curcell)
2764 (if (not ses--curcell)
2765 (progn ; At bottom of print area.
2766 (barf-if-buffer-read-only)
2767 (ses-insert-row 1))
2768 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2769 (when (/= 32
2770 (char-before (next-single-property-change (point)
2771 'cursor-intangible)))
2772 ;; We're already in last nonskipped cell on line. Need to create a
2773 ;; new column.
2774 (barf-if-buffer-read-only)
2775 (ses-insert-column (- count x)
2776 ses--numcols
2777 (ses-col-width col)
2778 (ses-col-printer col)))))
2779 (forward-char)))
2781 (defun ses-append-row-jump-first-column ()
2782 "Insert a new row after current one and jump to its first column."
2783 (interactive "*")
2784 (ses-check-curcell)
2785 (ses-begin-change)
2786 (beginning-of-line 2)
2787 (ses-set-curcell)
2788 (ses-insert-row 1))
2790 (defun ses-set-column-width (col newwidth)
2791 "Set the width of the current column."
2792 (interactive
2793 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2794 (barf-if-buffer-read-only)
2795 (list col
2796 (if current-prefix-arg
2797 (prefix-numeric-value current-prefix-arg)
2798 (read-from-minibuffer (format "Column %s width (default %d): "
2799 (ses-column-letter col)
2800 (ses-col-width col))
2801 nil ; No initial contents.
2802 nil ; No override keymap.
2803 t ; Convert to Lisp object.
2804 nil ; No history.
2805 (number-to-string
2806 (ses-col-width col))))))) ; Default value.
2807 (if (< newwidth 1)
2808 (error "Invalid column width"))
2809 (ses-begin-change)
2810 (ses-reset-header-string)
2811 (save-excursion
2812 (let ((inhibit-quit t))
2813 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2814 (ses-set-parameter 'ses--col-widths newwidth col))
2815 (dotimes (row ses--numrows)
2816 (ses-print-cell-new-width row col))))
2819 ;;----------------------------------------------------------------------------
2820 ;; Cut and paste, import and export
2821 ;;----------------------------------------------------------------------------
2823 (defun ses--advice-copy-region-as-kill (crak-fun beg end &rest args)
2824 ;; FIXME: Why doesn't it make sense to copy read-only or
2825 ;; intangible attributes? They're removed upon yank!
2826 "It doesn't make sense to copy read-only or intangible attributes into the
2827 kill ring. It probably doesn't make sense to copy keymap properties.
2828 We'll assume copying front-sticky properties doesn't make sense, either.
2830 This advice also includes some SES-specific code because otherwise it's too
2831 hard to override how mouse-1 works."
2832 (when (> beg end)
2833 (let ((temp beg))
2834 (setq beg end
2835 end temp)))
2836 (if (not (and (derived-mode-p 'ses-mode)
2837 (eq (get-text-property beg 'read-only) 'ses)
2838 (eq (get-text-property (1- end) 'read-only) 'ses)))
2839 (apply crak-fun beg end args) ; Normal copy-region-as-kill.
2840 (kill-new (ses-copy-region beg end))
2841 (if transient-mark-mode
2842 (setq deactivate-mark t))
2843 nil))
2844 (advice-add 'copy-region-as-kill :around #'ses--advice-copy-region-as-kill)
2846 (defun ses-copy-region (beg end)
2847 "Treat the region as rectangular. Convert the intangible attributes to
2848 SES attributes recording the contents of the cell as of the time of copying."
2849 (when (= end ses--data-marker)
2850 ;;Avoid overflow situation
2851 (setq end (1- ses--data-marker)))
2852 (let* ((x (mapconcat #'ses-copy-region-helper
2853 (extract-rectangle beg (1- end)) "\n")))
2854 (remove-text-properties 0 (length x)
2855 '(read-only t
2856 cursor-intangible t
2857 keymap t
2858 front-sticky t)
2862 (defun ses-copy-region-helper (line)
2863 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2864 external form by attaching to each print cell a 'ses attribute that records
2865 the corresponding data cell."
2866 (or (> (length line) 1)
2867 (error "Empty range"))
2868 (let ((inhibit-read-only t)
2869 (pos 0)
2870 mycell next sym rowcol)
2871 (while pos
2872 (setq sym (ses--cell-at-pos pos line)
2873 next (next-single-property-change pos 'cursor-intangible line)
2874 rowcol (ses-sym-rowcol sym)
2875 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2876 (put-text-property pos (or next (length line))
2877 'ses
2878 (list (ses-cell-symbol mycell)
2879 (ses-cell-formula mycell)
2880 (ses-cell-printer mycell))
2881 line)
2882 (setq pos next)))
2883 line)
2885 (defun ses-kill-override (beg end)
2886 "Generic override for any commands that kill text.
2887 We clear the killed cells instead of deleting them."
2888 (interactive "r")
2889 (ses-check-curcell 'needrange)
2890 ;; For some reason, the text-read-only error is not caught by `delete-region',
2891 ;; so we have to use subterfuge.
2892 (let ((buffer-read-only t))
2893 (1value (condition-case nil
2894 (noreturn (funcall (lookup-key (current-global-map)
2895 (this-command-keys))
2896 beg end))
2897 (buffer-read-only nil)))) ; The expected error.
2898 ;; Because the buffer was marked read-only, the kill command turned itself
2899 ;; into a copy. Now we clear the cells or signal the error. First we check
2900 ;; whether the buffer really is read-only.
2901 (barf-if-buffer-read-only)
2902 (ses-begin-change)
2903 (ses-dorange ses--curcell
2904 (ses-clear-cell row col))
2905 (ses-jump (car ses--curcell)))
2907 (defun ses--advice-yank (yank-fun &optional arg &rest args)
2908 "In SES mode, the yanked text is inserted as cells.
2910 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2911 SES buffer), the formulas and print functions are restored for the cells. If
2912 the text contains tabs, this is an insertion of tab-separated formulas.
2913 Otherwise the text is inserted as the formula for the current cell.
2915 When inserting cells, the formulas are usually relocated to keep the same
2916 relative references to neighboring cells. This is best if the formulas
2917 generally refer to other cells within the yanked text. You can use the C-u
2918 prefix to specify insertion without relocation, which is best when the
2919 formulas refer to cells outside the yanked text.
2921 When inserting formulas, the text is treated as a string constant if it doesn't
2922 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2923 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2924 as symbols."
2925 (if (not (and (derived-mode-p 'ses-mode)
2926 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2927 (apply yank-fun arg args) ; Normal non-SES yank.
2928 (ses-check-curcell 'end)
2929 (push-mark (point))
2930 (let ((text (current-kill (cond
2931 ((listp arg) 0)
2932 ((eq arg '-) -1)
2933 (t (1- arg))))))
2934 (or (ses-yank-cells text arg)
2935 (ses-yank-tsf text arg)
2936 (ses-yank-one (ses-yank-resize 1 1)
2937 text
2939 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2940 ;; Just one cell --- delete final tab or newline.
2941 (1- (length text)))
2942 arg)))
2943 (if (consp arg)
2944 (exchange-point-and-mark))))
2945 (advice-add 'yank :around #'ses--advice-yank)
2947 (defun ses-yank-pop (arg)
2948 "Replace just-yanked stretch of killed text with a different stretch.
2949 This command is allowed only immediately after a `yank' or a `yank-pop',
2950 when the region contains a stretch of reinserted previously-killed text.
2951 We replace it with a different stretch of killed text.
2952 Unlike standard `yank-pop', this function uses `undo' to delete the
2953 previous insertion."
2954 (interactive "*p")
2955 (or (eq last-command 'yank)
2956 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2957 ;;macro definition.
2958 (noreturn (error "Previous command was not a yank")))
2959 (undo)
2960 (ses-set-curcell)
2961 (yank (1+ (or arg 1)))
2962 (setq this-command 'yank))
2964 (defun ses-yank-cells (text arg)
2965 "If the TEXT has a proper set of 'ses attributes, insert the text as
2966 cells, else return nil. The cells are reprinted--the supplied text is
2967 ignored because the column widths, default printer, etc. at yank time might
2968 be different from those at kill-time. ARG is a list to indicate that
2969 formulas are to be inserted without relocation."
2970 (let ((first (get-text-property 0 'ses text))
2971 (last (get-text-property (1- (length text)) 'ses text)))
2972 (when (and first last) ;;Otherwise not proper set of attributes
2973 (setq first (ses-sym-rowcol (car first))
2974 last (ses-sym-rowcol (car last)))
2975 (let* ((needrows (- (car last) (car first) -1))
2976 (needcols (- (cdr last) (cdr first) -1))
2977 (rowcol (ses-yank-resize needrows needcols))
2978 (rowincr (- (car rowcol) (car first)))
2979 (colincr (- (cdr rowcol) (cdr first)))
2980 (pos 0)
2981 myrow mycol x)
2982 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2983 (setq myrow (+ row (car rowcol)))
2984 (dotimes (col needcols)
2985 (setq mycol (+ col (cdr rowcol))
2986 last (get-text-property pos 'ses text)
2987 pos (next-single-property-change pos 'ses text)
2988 x (ses-sym-rowcol (car last)))
2989 (if (not last)
2990 ;; Newline --- all remaining cells on row are skipped.
2991 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2992 last (list nil nil nil)
2993 pos (1- pos)))
2994 (if (/= (car x) (- myrow rowincr))
2995 (error "Cell row error"))
2996 (if (< (- mycol colincr) (cdr x))
2997 ;; Some columns were skipped.
2998 (let ((oldcol mycol))
2999 (while (< (- mycol colincr) (cdr x))
3000 (ses-clear-cell myrow mycol)
3001 (setq col (1+ col)
3002 mycol (1+ mycol)))
3003 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
3004 (when (car last) ; Skip this for *skip* cells.
3005 (setq x (nth 2 last))
3006 (unless (equal x (ses-cell-printer myrow mycol))
3007 (or (not x)
3008 (stringp x)
3009 (eq (car-safe x) 'ses-safe-printer)
3010 (setq x `(ses-safe-printer ,x)))
3011 (ses-set-cell myrow mycol 'printer x))
3012 (setq x (cadr last))
3013 (if (atom arg)
3014 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
3015 (or (atom x)
3016 (eq (car-safe x) 'ses-safe-formula)
3017 (setq x `(ses-safe-formula ,x)))
3018 (ses-cell-set-formula myrow mycol x)))
3019 (when pos
3020 (if (get-text-property pos 'ses text)
3021 (error "Missing newline between rows"))
3022 (setq pos (next-single-property-change pos 'ses text))))
3023 t))))
3025 (defun ses-yank-one (rowcol text from to arg)
3026 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
3027 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
3028 (let ((val (condition-case nil
3029 (read-from-string text from to)
3030 (error (cons nil from)))))
3031 (cond
3032 ((< (cdr val) (or to (length text)))
3033 ;; Invalid sexp --- leave it as a string.
3034 (setq val (substring text from to)))
3035 ((and (car val) (symbolp (car val)))
3036 (setq val (if (consp arg)
3037 (list 'quote (car val)) ; Keep symbol.
3038 (substring text from to)))) ; Treat symbol as text.
3040 (setq val (car val))))
3041 (let ((row (car rowcol))
3042 (col (cdr rowcol)))
3043 (or (atom val)
3044 (setq val `(ses-safe-formula ,val)))
3045 (ses-cell-set-formula row col val))))
3047 (defun ses-yank-tsf (text arg)
3048 "If TEXT contains tabs and/or newlines, treat the tabs as
3049 column-separators and the newlines as row-separators and insert the text as
3050 cell formulas--else return nil. Treat plain symbols as strings unless ARG
3051 is a list. Ignore a final newline."
3052 (if (or (not (string-match "[\t\n]" text))
3053 (= (match-end 0) (length text)))
3054 ;;Not TSF format
3056 (if (/= (aref text (1- (length text))) ?\n)
3057 (setq text (concat text "\n")))
3058 (let ((pos -1)
3059 (spots (list -1))
3060 (cols 0)
3061 (needrows 0)
3062 needcols rowcol)
3063 ;;Find all the tabs and newlines
3064 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
3065 (push pos spots)
3066 (setq cols (1+ cols))
3067 (when (eq (aref text pos) ?\n)
3068 (if (not needcols)
3069 (setq needcols cols)
3070 (or (= needcols cols)
3071 (error "Inconsistent row lengths")))
3072 (setq cols 0
3073 needrows (1+ needrows))))
3074 ;;Insert the formulas
3075 (setq rowcol (ses-yank-resize needrows needcols))
3076 (dotimes (row needrows)
3077 (dotimes (col needcols)
3078 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
3079 (+ (cdr rowcol) needcols (- col) -1))
3080 text (1+ (cadr spots)) (car spots) arg)
3081 (setq spots (cdr spots))))
3082 (ses-goto-print (+ (car rowcol) needrows -1)
3083 (+ (cdr rowcol) needcols -1))
3084 t)))
3086 (defun ses-yank-resize (needrows needcols)
3087 "If this yank will require inserting rows and/or columns, ask for
3088 confirmation and then insert them. Result is (row,col) for top left of yank
3089 spot, or error signal if user requests cancel."
3090 (ses-begin-change)
3091 (let ((rowcol (if ses--curcell
3092 (ses-sym-rowcol ses--curcell)
3093 (cons ses--numrows 0)))
3094 rowbool colbool)
3095 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
3096 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
3097 rowbool (> needrows 0)
3098 colbool (> needcols 0))
3099 (when (or rowbool colbool)
3100 ;;Need to insert. Get confirm
3101 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
3102 (if rowbool (format "%d rows" needrows) "")
3103 (if (and rowbool colbool) " and " "")
3104 (if colbool (format "%d columns" needcols) "")))
3105 (error "Canceled"))
3106 (when rowbool
3107 (let (ses--curcell)
3108 (save-excursion
3109 (ses-goto-print ses--numrows 0)
3110 (ses-insert-row needrows))))
3111 (when colbool
3112 (ses-insert-column needcols
3113 ses--numcols
3114 (ses-col-width (1- ses--numcols))
3115 (ses-col-printer (1- ses--numcols)))))
3116 rowcol))
3118 (defun ses-export-tsv (_beg _end)
3119 "Export values from the current range, with tabs between columns and
3120 newlines between rows. Result is placed in kill ring."
3121 (interactive "r")
3122 (ses-export-tab nil))
3124 (defun ses-export-tsf (_beg _end)
3125 "Export formulas from the current range, with tabs between columns and
3126 newlines between rows. Result is placed in kill ring."
3127 (interactive "r")
3128 (ses-export-tab t))
3130 (defun ses-export-tab (want-formulas)
3131 "Export the current range with tabs between columns and newlines between rows.
3132 Result is placed in kill ring. The export is values unless WANT-FORMULAS
3133 is non-nil. Newlines and tabs in the export text are escaped."
3134 (ses-check-curcell 'needrange)
3135 (let ((print-escape-newlines t)
3136 result item)
3137 (ses-dorange ses--curcell
3138 (setq item (if want-formulas
3139 (ses-cell-formula row col)
3140 (ses-cell-value row col)))
3141 (if (eq (car-safe item) 'ses-safe-formula)
3142 ;;Hide our deferred safety-check marker
3143 (setq item (cadr item)))
3144 (if (or (not item) (eq item '*skip*))
3145 (setq item ""))
3146 (when (eq (car-safe item) 'quote)
3147 (push "'" result)
3148 (setq item (cadr item)))
3149 (setq item (prin1-to-string item t))
3150 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
3151 (push item result)
3152 (cond
3153 ((< col maxcol)
3154 (push "\t" result))
3155 ((< row maxrow)
3156 (push "\n" result))))
3157 (setq result (apply #'concat (nreverse result)))
3158 (kill-new result)))
3161 ;;----------------------------------------------------------------------------
3162 ;; Other user commands
3163 ;;----------------------------------------------------------------------------
3165 (defun ses-unset-header-row ()
3166 "Select the default header row."
3167 (interactive)
3168 (ses-set-header-row 0))
3170 (defun ses-set-header-row (row)
3171 "Set the ROW to display in the header-line.
3172 With a numerical prefix arg, use that row.
3173 With no prefix arg, use the current row.
3174 With a \\[universal-argument] prefix arg, prompt the user.
3175 The top row is row 1. Selecting row 0 displays the default header row."
3176 (interactive
3177 (list (if (numberp current-prefix-arg) current-prefix-arg
3178 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3179 (if current-prefix-arg
3180 (read-number "Header row: " currow)
3181 currow)))))
3182 (if (or (< row 0) (> row ses--numrows))
3183 (error "Invalid header-row"))
3184 (ses-begin-change)
3185 (let ((oldval ses--header-row))
3186 (let (buffer-undo-list)
3187 (ses-set-parameter 'ses--header-row row))
3188 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
3189 (ses-reset-header-string))
3191 (defun ses-mark-row ()
3192 "Mark the entirety of current row as a range."
3193 (interactive)
3194 (ses-check-curcell 'range)
3195 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
3196 (push-mark (point))
3197 (ses-goto-print (1+ row) 0)
3198 (push-mark (point) nil t)
3199 (ses-goto-print row 0)))
3201 (defun ses-mark-column ()
3202 "Mark the entirety of current column as a range."
3203 (interactive)
3204 (ses-check-curcell 'range)
3205 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
3206 (row 0))
3207 (push-mark (point))
3208 (ses-goto-print (1- ses--numrows) col)
3209 (forward-char 1)
3210 (push-mark (point) nil t)
3211 (while (eq '*skip* (ses-cell-value row col))
3212 ;;Skip over initial cells in column that can't be selected
3213 (setq row (1+ row)))
3214 (ses-goto-print row col)))
3216 (defun ses-end-of-line ()
3217 "Move point to last cell on line."
3218 (interactive)
3219 (ses-check-curcell 'end 'range)
3220 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3221 ; anyway.
3222 (let ((col (1- ses--numcols))
3223 row rowcol)
3224 (if (symbolp ses--curcell)
3225 ;; Single cell.
3226 (setq row (car (ses-sym-rowcol ses--curcell)))
3227 ;; Range --- use whichever end of the range the point is at.
3228 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
3229 (car ses--curcell)
3230 (cdr ses--curcell))))
3231 ;; If range already includes the last cell in a row, point is actually
3232 ;; in the following row.
3233 (if (<= (cdr rowcol) (1- col))
3234 (setq row (car rowcol))
3235 (setq row (1+ (car rowcol)))
3236 (if (= row ses--numrows)
3237 ;;Already at end - can't go anywhere
3238 (setq col 0))))
3239 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
3240 (while (eq (ses-cell-value row col) '*skip*)
3241 ;; Back to beginning of multi-column cell.
3242 (setq col (1- col)))
3243 (ses-goto-print row col)))))
3245 (defun ses-renarrow-buffer ()
3246 "Narrow the buffer so only the print area is visible.
3247 Use after \\[widen]."
3248 (interactive)
3249 (setq ses--deferred-narrow t))
3251 (defun ses-sort-column (sorter &optional reverse)
3252 "Sort the range by a specified column.
3253 With prefix, sorts in REVERSE order."
3254 (interactive "*sSort column: \nP")
3255 (ses-check-curcell 'needrange)
3256 (let ((min (ses-sym-rowcol (car ses--curcell)))
3257 (max (ses-sym-rowcol (cdr ses--curcell))))
3258 (let ((minrow (car min))
3259 (mincol (cdr min))
3260 (maxrow (car max))
3261 (maxcol (cdr max))
3262 keys extracts end)
3263 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3264 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3265 (error "Invalid sort column"))
3266 ;;Get key columns and sort them
3267 (dotimes (x (- maxrow minrow -1))
3268 (ses-goto-print (+ minrow x) sorter)
3269 (setq end (next-single-property-change (point) 'cursor-intangible))
3270 (push (cons (buffer-substring-no-properties (point) end)
3271 (+ minrow x))
3272 keys))
3273 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3274 ;;Extract the lines in reverse sorted order
3275 (or reverse
3276 (setq keys (nreverse keys)))
3277 (dolist (x keys)
3278 (ses-goto-print (cdr x) (1+ maxcol))
3279 (setq end (point))
3280 (ses-goto-print (cdr x) mincol)
3281 (push (ses-copy-region (point) end) extracts))
3282 (deactivate-mark)
3283 ;;Paste the lines sequentially
3284 (dotimes (x (- maxrow minrow -1))
3285 (ses-goto-print (+ minrow x) mincol)
3286 (ses-set-curcell)
3287 (ses-yank-cells (pop extracts) nil)))))
3289 (defun ses-sort-column-click (event reverse)
3290 "Mouse version of `ses-sort-column'."
3291 (interactive "*e\nP")
3292 (setq event (event-end event))
3293 (select-window (posn-window event))
3294 (setq event (car (posn-col-row event))) ; Click column.
3295 (let ((col 0))
3296 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3297 (setq event (- event (ses-col-width col) 1)
3298 col (1+ col)))
3299 (if (>= col ses--numcols)
3300 (ding)
3301 (ses-sort-column (ses-column-letter col) reverse))))
3303 (defun ses-insert-range ()
3304 "Insert into minibuffer the list of cells currently highlighted in the
3305 spreadsheet."
3306 (interactive "*")
3307 (let (x)
3308 (with-current-buffer (window-buffer minibuffer-scroll-window)
3309 (ses-command-hook) ; For ses-coverage.
3310 (ses-check-curcell 'needrange)
3311 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3312 ,(cdr ses--curcell))))))
3313 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3315 (defun ses-insert-ses-range ()
3316 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
3317 highlighted range in the spreadsheet."
3318 (interactive "*")
3319 (let (x)
3320 (with-current-buffer (window-buffer minibuffer-scroll-window)
3321 (ses-command-hook) ; For ses-coverage.
3322 (ses-check-curcell 'needrange)
3323 (setq x (format "(ses-range %S %S)"
3324 (car ses--curcell)
3325 (cdr ses--curcell))))
3326 (insert x)))
3328 (defun ses-insert-range-click (event)
3329 "Mouse version of `ses-insert-range'."
3330 (interactive "*e")
3331 (mouse-set-point event)
3332 (ses-insert-range))
3334 (defun ses-insert-ses-range-click (event)
3335 "Mouse version of `ses-insert-ses-range'."
3336 (interactive "*e")
3337 (mouse-set-point event)
3338 (ses-insert-ses-range))
3340 (defun ses-replace-name-in-formula (formula old-name new-name)
3341 (let ((new-formula formula))
3342 (unless (and (consp formula)
3343 (eq (car-safe formula) 'quote))
3344 (while formula
3345 (let ((elt (car-safe formula)))
3346 (cond
3347 ((consp elt)
3348 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3349 ((and (symbolp elt)
3350 (eq (car-safe formula) old-name))
3351 (setcar formula new-name))))
3352 (setq formula (cdr formula))))
3353 new-formula))
3355 (defun ses-rename-cell (new-name &optional cell)
3356 "Rename current cell."
3357 (interactive "*SEnter new name: ")
3359 (and (local-variable-p new-name)
3360 (ses-is-cell-sym-p new-name)
3361 (error "Already a cell name"))
3362 (and (boundp new-name)
3363 (null (yes-or-no-p (format "`%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)
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)))
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)))))))
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
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)
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))))))))))
3492 ;;----------------------------------------------------------------------------
3493 ;; Checking formulas for safety
3494 ;;----------------------------------------------------------------------------
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))
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)))
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)
3519 (setq checker (funcall checker formula))
3520 (if (not checker)
3522 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3523 formula checker)))))
3526 ;;----------------------------------------------------------------------------
3527 ;; Standard formulas
3528 ;;----------------------------------------------------------------------------
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)))
3534 (defun ses--clean-_ (x y)
3535 "Clean list X by replacing by Y any occurrence of nil or `*skip*'.
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))))
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!
3553 By passing in REST some flags one can configure the way the range
3554 is read and how it is formatted.
3556 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3557 1 2 3 and 4.
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).
3565 If the range is one row, then `>' can be used as a shorthand to
3566 `>v' or `>^', and `<' to `<v' or `<^'.
3568 If the range is one column, then `v' can be used as a shorthand to
3569 `v>' or `v<', and `^' to `^>' or `v<'.
3571 A `!' flag will remove all cells whose value is nil or `*skip*'.
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.
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.
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)))))
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)))
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))))))
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))
3664 (defun ses+ (&rest args)
3665 "Compute the sum of the arguments, ignoring blanks."
3666 (apply #'+ (apply #'ses-delete-blanks args)))
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)))
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)))
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))
3697 ;;----------------------------------------------------------------------------
3698 ;; Standard print functions
3699 ;;----------------------------------------------------------------------------
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))))))
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)))
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 ?-))
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 ?-))
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 ?~))
3747 (defun ses-unsafe (_value)
3748 "Substitute for an unsafe formula or printer."
3749 (error "Unsafe formula or printer"))
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))
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)
3762 (provide 'ses)
3764 ;;; ses.el ends here