1 ;;; ses.el -- Simple Emacs Spreadsheet -*- lexical-binding:t -*-
3 ;; Copyright (C) 2002-2017 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/>.
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
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.
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
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.
70 (eval-when-compile (require 'cl-lib
))
73 ;;----------------------------------------------------------------------------
74 ;; User-customizable variables
75 ;;----------------------------------------------------------------------------
78 "Simple Emacs Spreadsheet."
81 :link
'(custom-manual "(ses) Top")
85 (defcustom ses-initial-size
'(1 .
1)
86 "Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
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."
93 :type
'(integer :match
(lambda (widget value
) (> value
0))))
95 (defcustom ses-initial-default-printer
"%.7g"
96 "Initial default printer for a new spreadsheet."
99 (list :tag
"Parenthesized string" string
)
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."
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."
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."
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
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)))
148 (define-key (1value newmap
) (car keys
) (cadr keys
))
149 (setq keys
(cddr keys
)))
151 "Local keymap for Simple Emacs Spreadsheet.")
153 (easy-menu-define ses-menu ses-mode-map
154 "Menu bar menu for 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
)
179 (define-key newmap
(pop keys
) (pop keys
)))
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
191 "\M-k" ses-delete-column
193 "\C-k" ses-delete-row
194 "\C-j" ses-append-row-jump-first-column
196 "\M-H" ses-mark-column
197 "\C-d" ses-clear-cell-forward
198 "\C-?" ses-clear-cell-backward
203 "c" ses-recalculate-cell
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
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
232 (define-key newmap (car keys) (cadr keys))
233 (setq keys (cddr keys)))
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))
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
279 ses-center-span ses-dashfill ses-dashfill-span
282 "List of print functions to be included in initial history of
283 printer functions. None of these standard-printer functions,
284 except function `ses-prin1', is suitable for use as a column
285 printer or a global-default printer because they invoke the
286 column or default printer and then modify its output.")
289 ;;----------------------------------------------------------------------------
290 ;; Local variables and constants
291 ;;----------------------------------------------------------------------------
294 (defconst ses-localvars
295 '(ses--blank-line ses--cells ses--col-printers
296 ses--col-widths ses--curcell ses--curcell-overlay
298 (ses--local-printer-hashmap . :hashmap)
299 (ses--numlocprn . 0); count of local printers
300 ses--deferred-narrow ses--deferred-recalc
301 ses--deferred-write ses--file-format
302 ses--named-cell-hashmap
303 (ses--header-hscroll . -1) ; Flag for "initial recalc needed"
304 ses--header-row ses--header-string ses--linewidth
305 ses--numcols ses--numrows ses--symbolic-formulas
306 ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
307 ses--Dijkstra-weight-bound
308 ;; This list is useful for clean-up of symbols when an area
309 ;; containing renamed cell is deleted.
310 ses--in-killing-named-cell-list
311 ;; Global variables that we override
312 next-line-add-newlines transient-mark-mode)
313 "Buffer-local variables used by SES."))
315 (defmacro ses--metaprogramming (exp) (declare (debug t)) (eval exp t))
316 (ses--metaprogramming
317 `(progn ,@(mapcar (lambda (x) `(defvar ,(or (car-safe x) x))) ses-localvars)))
319 (defun ses-set-localvars ()
320 "Set buffer-local and initialize some SES variables."
321 (dolist (x ses-localvars)
324 (set (make-local-variable x) nil))
328 (set (make-local-variable (car x)) (cdr x)))
329 ((eq (cdr x) :hashmap)
330 (set (make-local-variable (car x)) (make-hash-table :test 'eq)))
331 (t (error "Unexpected initializer `%S' in list `ses-localvars' for entry %S"
332 (cdr x) (car x)) ) ))
333 (t (error "Unexpected elements `%S' in list `ses-localvars'" x)))))
335 ;;; This variable is documented as being permitted in file-locals:
336 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
338 (defconst ses-paramlines-plist
339 '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
340 ses--header-row -2 ses--file-format 1 ses--numrows 2
341 ses--numcols 3 ses--numlocprn 4)
342 "Offsets from \"Global parameters\" line to various parameter lines in the
343 data area of a spreadsheet.")
345 (defconst ses-paramfmt-plist
346 '(ses--col-widths "(ses-column-widths %S)"
347 ses--col-printers "(ses-column-printers %S)"
348 ses--default-printer "(ses-default-printer %S)"
349 ses--header-row "(ses-header-row %S)"
350 ses--file-format " %S ;SES file-format"
351 ses--numrows " %S ;numrows"
352 ses--numcols " %S ;numcols"
353 ses--numlocprn " %S ;numlocprn")
354 "Formats of \"Global parameters\" various parameters in the data
355 area of a spreadsheet.")
358 ;; "Side-effect variables". They are set in one function, altered in
359 ;; another as a side effect, then read back by the first, as a way of
360 ;; passing back more than one value. These declarations are just to make
361 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
362 ;; think the make-local-variable trick above is cleaner).
365 (defvar ses-relocate-return nil
366 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
367 `ses-relocate-all'. Set to `delete' if a cell-reference was deleted from a
368 formula--so the formula needs recalculation. Set to `range' if the size of a
369 `ses-range' was changed--so both the formula's value and list of dependents
370 need to be recalculated.")
372 (defvar ses-call-printer-return nil
373 "Set to t if last cell printer invoked by `ses-call-printer' requested
374 left-justification of the result. Set to error-signal if `ses-call-printer'
375 encountered an error during printing. Otherwise nil.")
377 (defvar ses-start-time nil
378 "Time when current operation started. Used by `ses-time-check' to decide
379 when to emit a progress message.")
382 ;;----------------------------------------------------------------------------
384 ;;----------------------------------------------------------------------------
386 (defmacro ses-get-cell (row col)
387 "Return the cell structure that stores information about cell (ROW,COL)."
389 `(aref (aref ses--cells ,row) ,col))
391 (cl-defstruct (ses-cell
393 (:constructor ses-make-cell
394 (&optional symbol formula printer references))
396 ;; This is treated as an 4-elem array in various places.
397 ;; Mostly in ses-set-cell.
398 (:type vector) ;Not named.
399 (:conc-name ses-cell--))
400 symbol formula printer references properties)
402 (cl-defstruct (ses--locprn
404 (:constructor ses-make-local-printer-info
405 (def &optional (compiled (ses-local-printer-compile def))
406 (number ses--numlocprn))))
412 (defmacro ses-cell-symbol (row &optional col)
413 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
415 `(ses-cell--symbol ,(if col `(ses-get-cell ,row ,col) row)))
416 (put 'ses-cell-symbol 'safe-function t)
418 (defmacro ses-cell-formula (row &optional col)
419 "From a CELL or a pair (ROW,COL), get the function that computes its value."
421 `(ses-cell--formula ,(if col `(ses-get-cell ,row ,col) row)))
423 (defmacro ses-cell-printer (row &optional col)
424 "From a CELL or a pair (ROW,COL), get the function that prints its value."
426 `(ses-cell--printer ,(if col `(ses-get-cell ,row ,col) row)))
428 (defmacro ses-cell-references (row &optional col)
429 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
430 functions refer to its value."
432 `(ses-cell--references ,(if col `(ses-get-cell ,row ,col) row)))
434 (defmacro ses-sym-rowcol (sym)
435 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0). Result
436 is nil if SYM is not a symbol that names a cell."
438 `(let ((rc (and (symbolp ,sym) (get ,sym 'ses-cell))))
439 (if (eq rc :ses-named)
440 (gethash ,sym ses--named-cell-hashmap)
443 (defun ses-cell-p (cell)
444 "Return non-nil if CELL is a cell of current buffer."
447 (eq cell (let ((rowcol (ses-sym-rowcol (ses-cell-symbol cell))))
449 (ses-get-cell (car rowcol) (cdr rowcol)))))))
451 (defun ses-plist-delq (plist prop)
452 "Return PLIST after deleting the first pair (if any) with symbol PROP.
453 This can alter PLIST."
456 ((eq (car plist) prop) (cddr plist))
457 (t (let* ((plist-1 (cdr plist))
458 (plist-2 (cdr plist-1)))
459 (setcdr plist-1 (ses-plist-delq plist-2 prop))
462 (defvar ses--ses-buffer-list nil "A list of buffers containing a SES spreadsheet.")
464 (defun ses--unbind-cell-name (name)
465 "Make NAME non longer a renamed cell name."
466 (remhash name ses--named-cell-hashmap)
467 (kill-local-variable name)
468 ;; remove symbol property 'ses-cell from symbol NAME, unless this
469 ;; symbol is also a renamed cell name in another SES buffer.
470 (let (used-elsewhere (buffer-list ses--ses-buffer-list) buf)
472 (setq buf (pop buffer-list))
474 ((eq buf (current-buffer)))
475 ;; This case should not happen, some SES buffer has been
476 ;; killed without the ses-killbuffer-hook being called.
477 ((null (buffer-live-p buf))
478 ;; Silently repair ses--ses-buffer-list
479 (setq ses--ses-buffer-list (delq buf ses--ses-buffer-list)))
481 (with-current-buffer buf
482 (when (gethash name ses--named-cell-hashmap)
483 (setq used-elsewhere t
484 buffer-list nil))))))
485 (unless used-elsewhere
486 (setplist name (ses-plist-delq (symbol-plist name) 'ses-cell))) ))
488 (defmacro ses--letref (vars place &rest body)
489 (declare (indent 2) (debug (sexp form &rest body)))
490 (gv-letplace (getter setter) place
491 `(cl-macrolet ((,(nth 0 vars) () ',getter)
492 (,(nth 1 vars) (v) (funcall ',setter v)))
495 (defmacro ses-cell-property (property-name row &optional col)
496 "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
498 When COL is omitted, CELL=ROW is a cell object. When COL is
499 present ROW and COL are the integer coordinates of the cell of
502 `(alist-get ,property-name
503 (ses-cell--properties
504 ,(if col `(ses-get-cell ,row ,col) row))))
506 (defmacro ses-cell-property-pop (property-name row &optional col)
507 "From a CELL or a pair (ROW,COL), get and remove the property value of
508 the corresponding cell with name PROPERTY-NAME."
509 `(ses--letref (pget pset)
510 (alist-get ,property-name
511 (ses-cell--properties
512 ,(if col `(ses-get-cell ,row ,col) row))
514 (prog1 (pget) (pset nil))))
516 (defmacro ses-cell-value (row &optional col)
517 "From a CELL or a pair (ROW,COL), get the current value for that cell."
519 `(symbol-value (ses-cell-symbol ,row ,col)))
521 (defmacro ses-col-width (col)
522 "Return the width for column COL."
524 `(aref ses--col-widths ,col))
526 (defmacro ses-col-printer (col)
527 "Return the default printer for column COL."
529 `(aref ses--col-printers ,col))
531 (defun ses-is-cell-sym-p (sym)
532 "Check whether SYM point at a cell of this spread sheet."
533 (let ((rowcol (get sym 'ses-cell)))
535 (if (eq rowcol :ses-named)
536 (and ses--named-cell-hashmap (gethash sym ses--named-cell-hashmap))
537 (and (< (car rowcol) ses--numrows)
538 (< (cdr rowcol) ses--numcols)
539 (eq (ses-cell-symbol (car rowcol) (cdr rowcol)) sym))))))
541 (defun ses--cell (sym value formula printer references)
542 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
543 FORMULA, does not reprint using PRINTER, does not check REFERENCES.
544 Safety-checking for FORMULA and PRINTER are deferred until first use."
545 (let ((rowcol (ses-sym-rowcol sym)))
546 (ses-formula-record formula)
547 (ses-printer-record printer)
548 (unless (or formula (eq value '*skip*))
549 (setq formula (macroexp-quote value)))
551 (eq safe-functions t)
552 (setq formula `(ses-safe-formula ,formula)))
555 (eq safe-functions t)
556 (setq printer `(ses-safe-printer ,printer)))
557 (setf (ses-get-cell (car rowcol) (cdr rowcol))
558 (ses-make-cell sym formula printer references)))
561 (defun ses-local-printer-compile (printer)
562 "Convert local printer function into faster printer
565 ((functionp printer) printer)
569 (format ,printer x))))
570 ((stringp (car-safe printer))
573 (setq ses-call-printer-return t)
574 (format ,(car printer) x))))
575 (t (error "Invalid printer %S" printer))))
577 (defun ses--local-printer (name def)
578 "Define a local printer with name NAME and definition DEF.
579 Return the printer info."
582 (ses-printer-validate def))
583 (error "Invalid local printer definition"))
584 (and (gethash name ses--local-printer-hashmap)
585 (error "Duplicate printer definition %S" name))
586 (add-to-list 'ses-read-printer-history (symbol-name name))
588 (ses-make-local-printer-info (ses-safe-printer def))
589 ses--local-printer-hashmap))
591 (defmacro ses-column-widths (widths)
592 "Load the vector of column widths from the spreadsheet file. This is a
593 macro to prevent propagate-on-load viruses."
594 (or (and (vectorp widths) (= (length widths) ses--numcols))
595 (error "Bad column-width vector"))
596 ;;To save time later, we also calculate the total width of each line in the
597 ;;print area (excluding the terminating newline)
598 (setq ses--col-widths widths
599 ses--linewidth (apply #'+ -1 (mapcar #'1+ widths))
600 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
603 (defmacro ses-column-printers (printers)
604 "Load the vector of column printers from the spreadsheet file and checks
605 them for safety. This is a macro to prevent propagate-on-load viruses."
606 (or (and (vectorp printers) (= (length printers) ses--numcols))
607 (error "Bad column-printers vector"))
608 (dotimes (x ses--numcols)
609 (aset printers x (ses-safe-printer (aref printers x))))
610 (setq ses--col-printers printers)
611 (mapc #'ses-printer-record printers)
614 (defmacro ses-default-printer (def)
615 "Load the global default printer from the spreadsheet file and checks it
616 for safety. This is a macro to prevent propagate-on-load viruses."
617 (setq ses--default-printer (ses-safe-printer def))
618 (ses-printer-record def)
621 (defmacro ses-header-row (row)
622 "Load the header row from the spreadsheet file and checks it
623 for safety. This is a macro to prevent propagate-on-load viruses."
624 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
625 (error "Bad header-row"))
626 (setq ses--header-row row)
629 (defmacro ses-dorange (curcell &rest body)
630 "Execute BODY repeatedly, with the variables `row' and `col' set to each
631 cell in the range specified by CURCELL. The range is available in the
632 variables `minrow', `maxrow', `mincol', and `maxcol'."
633 (declare (indent defun) (debug (form body)))
634 (let ((cur (make-symbol "cur"))
635 (min (make-symbol "min"))
636 (max (make-symbol "max"))
637 (r (make-symbol "r"))
638 (c (make-symbol "c")))
639 `(let* ((,cur ,curcell)
640 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
641 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
642 (let ((minrow (car ,min))
646 (if (or (> minrow maxrow) (> mincol maxcol))
647 (error "Empty range"))
648 (dotimes (,r (- maxrow minrow -1))
649 (let ((row (+ ,r minrow)))
650 (dotimes (,c (- maxcol mincol -1))
651 (let ((col (+ ,c mincol)))
654 ;;Support for coverage testing.
655 (defmacro 1value (form)
656 "For code-coverage testing, indicate that FORM is expected to always have
660 (defmacro noreturn (form)
661 "For code-coverage testing, indicate that FORM will always signal an error."
666 ;;----------------------------------------------------------------------------
668 ;;----------------------------------------------------------------------------
670 (defun ses-vector-insert (array idx new)
671 "Create a new vector which is one larger than ARRAY and has NEW inserted
673 (let* ((len (length array))
674 (result (make-vector (1+ len) new)))
677 (if (< x idx) x (1+ x))
681 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
682 (defun ses-vector-delete (array idx count)
683 "Create a new vector which is a copy of ARRAY with COUNT objects removed
684 starting at element IDX. ARRAY is either a vector or a symbol whose value
685 is a vector--if a symbol, the new vector is assigned as the symbol's value."
686 (let* ((a (if (arrayp array) array (symbol-value array)))
687 (len (- (length a) count))
688 (result (make-vector len nil)))
690 (aset result x (aref a (if (< x idx) x (+ x count)))))
695 (defun ses-delete-line (count)
696 "Like `kill-line', but no kill ring."
699 (delete-region pos (point))))
701 (defun ses-printer-validate (printer)
702 "Signal an error if PRINTER is not a valid SES cell printer."
705 ;; printer is a local printer
706 (and (symbolp printer) (gethash printer ses--local-printer-hashmap))
708 (and (stringp (car-safe printer)) (not (cdr printer)))
709 (error "Invalid printer function %S" printer))
712 (defun ses-printer-record (printer)
713 "Add PRINTER to `ses-read-printer-history' if not already there, after first
714 checking that it is a valid printer function."
715 (ses-printer-validate printer)
716 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
718 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
720 (defun ses-formula-record (formula)
721 "If FORMULA is of the form \\='SYMBOL, add it to the list of symbolic formulas
722 for this spreadsheet."
723 (when (and (eq (car-safe formula) 'quote)
724 (symbolp (cadr formula)))
725 (add-to-list 'ses--symbolic-formulas
726 (list (symbol-name (cadr formula))))))
728 (defun ses-column-letter (col)
729 "Return the alphabetic name of column number COL.
730 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
731 (let ((units (char-to-string (+ ?A (% col 26)))))
734 (concat (ses-column-letter (1- (/ col 26))) units))))
736 (defun ses-create-cell-symbol (row col)
737 "Produce a symbol that names the cell (ROW,COL). (0,0) => A1."
738 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
740 (defun ses-decode-cell-symbol (str)
741 "Decode a symbol \"A1\" => (0,0). Return nil if STR is not a
742 canonical cell name."
743 (let (case-fold-search)
744 (and (string-match "\\`\\([A-Z]+\\)\\([0-9]+\\)\\'" str)
745 (let* ((col-str (match-string-no-properties 1 str))
748 (col-idx (1- (length col-str)))
749 (row (1- (string-to-number
750 (match-string-no-properties 2 str)))))
755 (setq col (+ col (* (- (aref col-str col-idx) ?A)
757 col-base (* col-base 26)
758 col-idx (1- col-idx))
760 (setq col (+ col col-base)))))
763 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
764 "Create buffer-local variables for cells. This is undoable."
765 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
768 (dotimes (row (1+ (- maxrow minrow)))
769 (dotimes (col (1+ (- maxcol mincol)))
770 (setq xrow (+ row minrow)
772 sym (ses-create-cell-symbol xrow xcol))
773 (put sym 'ses-cell (cons xrow xcol))
774 (make-local-variable sym)))))
776 (defun ses-create-cell-variable (sym row col)
777 "Create a buffer-local variable `SYM' for cell at position (ROW, COL).
779 SYM is the symbol for that variable, ROW and COL are integers for
780 row and column of the cell, with numbering starting from 0.
782 Return nil in case of failure."
783 (unless (local-variable-p sym)
784 (make-local-variable sym)
785 (if (let (case-fold-search) (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name sym)))
786 (put sym 'ses-cell (cons row col))
787 (put sym 'ses-cell :ses-named)
788 (setq ses--named-cell-hashmap (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
789 (puthash sym (cons row col) ses--named-cell-hashmap))))
791 ;; We do not delete the ses-cell properties for the cell-variables, in
792 ;; case a formula that refers to this cell is in the kill-ring and is
793 ;; later pasted back in.
794 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
795 "Destroy buffer-local variables for cells. This is undoable."
797 (dotimes (row (1+ (- maxrow minrow)))
798 (dotimes (col (1+ (- maxcol mincol)))
799 (let ((xrow (+ row minrow)) (xcol (+ col mincol)))
800 (setq sym (if (and (< xrow ses--numrows) (< xcol ses--numcols))
801 (ses-cell-symbol xrow xcol)
802 (ses-create-cell-symbol xrow xcol))))
804 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
806 (kill-local-variable sym))))
807 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
810 (defun ses-reset-header-string ()
811 "Flag the header string for update. Upon undo, the header string will be
813 (push '(apply ses-reset-header-string) buffer-undo-list)
814 (setq ses--header-hscroll -1))
816 ;;Split this code off into a function to avoid coverage-testing difficulties
817 (defmacro ses--time-check (format &rest args)
818 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
819 and ARGS and reset `ses-start-time' to the current time."
820 `(when (> (- (float-time) ses-start-time) 1.0)
821 (message ,format ,@args)
822 (setq ses-start-time (float-time))))
825 ;;----------------------------------------------------------------------------
827 ;;----------------------------------------------------------------------------
829 (defmacro ses-set-cell (row col field val)
830 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
831 cell (ROW,COL). This is undoable. The cell's data will be updated through
832 `post-command-hook'."
836 (let* ((cell (ses-get-cell row col))
838 ,(let ((field (progn (cl-assert (eq (car field) 'quote))
840 (if (eq field 'value)
841 `(ses-set-with-undo (ses-cell-symbol cell) val)
842 ;; (let* ((slots (get 'ses-cell 'cl-struct-slots))
843 ;; (slot (or (assq field slots)
844 ;; (error "Unknown field %S" field)))
845 ;; (idx (- (length slots)
846 ;; (length (memq slot slots)))))
847 ;; `(ses-aset-with-undo cell ,idx val))
848 (let ((getter (intern-soft (format "ses-cell--%s" field))))
849 `(ses-setter-with-undo
852 (lambda (newval cell)
853 (setf (,getter cell) newval))))
856 (add-to-list 'ses--deferred-write (cons row col))))
857 nil)) ; Make coverage-tester happy.
859 (defun ses-cell-set-formula (row col formula)
860 "Store a new formula for (ROW . COL) and enqueue the cell for
861 recalculation via `post-command-hook'. Updates the reference lists for the
862 cells that this cell refers to. Does not update cell value or reprint the
863 cell. To avoid inconsistencies, this function is not interruptible, which
864 means Emacs will crash if FORMULA contains a circular list."
865 (let* ((cell (ses-get-cell row col))
866 (old (ses-cell-formula cell)))
867 (let ((sym (ses-cell-symbol cell))
868 (oldref (ses-formula-references old))
869 (newref (ses-formula-references formula))
872 (cl-pushnew sym ses--deferred-recalc)
873 ;;Delete old references from this cell. Skip the ones that are also
876 (unless (memq ref newref)
877 (setq x (ses-sym-rowcol ref)
880 (ses-set-cell xrow xcol 'references
881 (delq sym (ses-cell-references xrow xcol)))))
882 ;;Add new ones. Skip ones left over from old list
884 (setq x (ses-sym-rowcol ref)
887 x (ses-cell-references xrow xcol))
889 (ses-set-cell xrow xcol 'references (cons sym x))))
890 (ses-formula-record formula)
891 (ses-set-cell row col 'formula formula))))
894 (defun ses-repair-cell-reference-all ()
895 "Repair cell reference and warn if there was some reference corruption."
898 ;; Step 1, reset :ses-repair-reference cell property in the whole sheet.
899 (dotimes (row ses--numrows)
900 (dotimes (col ses--numcols)
901 (let ((references (ses-cell-property-pop :ses-repair-reference
904 (push (list (ses-cell-symbol row col)
909 ;; Step 2, build new.
910 (dotimes (row ses--numrows)
911 (dotimes (col ses--numcols)
912 (let* ((cell (ses-get-cell row col))
913 (sym (ses-cell-symbol cell))
914 (formula (ses-cell-formula cell))
915 (new-ref (ses-formula-references formula)))
916 (dolist (ref new-ref)
917 (let ((rowcol (ses-sym-rowcol ref)))
918 (cl-pushnew sym (ses-cell-property :ses-repair-reference
922 ;; Step 3, overwrite with check.
923 (dotimes (row ses--numrows)
924 (dotimes (col ses--numcols)
925 (let* ((cell (ses-get-cell row col))
926 (irrelevant (ses-cell-references cell))
927 (new-ref (ses-cell-property-pop :ses-repair-reference cell))
929 (dolist (ref new-ref)
930 (if (memq ref irrelevant)
931 (setq irrelevant (delq ref irrelevant))
933 (ses-set-cell row col 'references new-ref)
934 (when (or missing irrelevant)
935 (push `( ,(ses-cell-symbol cell)
936 ,@(and missing (list :missing missing))
937 ,@(and irrelevant (list :irrelevant irrelevant)))
940 (warn "----------------------------------------------------------------
941 Some references were corrupted.
943 The following is a list where each element ELT is such
944 that (car ELT) is the reference of cell CELL with corruption,
945 and (cdr ELT) is a property list where
947 * property `:corrupt-property' means that
948 property `:ses-repair-reference' of cell CELL was initially non
951 * property `:missing' is a list of missing references
953 * property `:irrelevant' is a list of non needed references
956 (message "No reference corruption found"))))
958 (defun ses-calculate-cell (row col force)
959 "Calculate and print the value for cell (ROW,COL) using the cell's formula
960 function and print functions, if any. Result is nil for normal operation, or
961 the error signal if the formula or print function failed. The old value is
962 left unchanged if it was *skip* and the new value is nil.
963 Any cells that depend on this cell are queued for update after the end of
964 processing for the current keystroke, unless the new value is the same as
965 the old and FORCE is nil."
966 (let ((cell (ses-get-cell row col))
967 cycle-error formula-error printer-error)
968 (let ((oldval (ses-cell-value cell))
969 (formula (ses-cell-formula cell))
971 this-cell-Dijkstra-attempt+1)
972 (when (eq (car-safe formula) 'ses-safe-formula)
973 (setq formula (ses-safe-formula (cadr formula)))
974 (ses-set-cell row col 'formula formula))
976 (setq newval (eval formula t))
978 ;; Variable `sig' can't be nil.
979 (nconc sig (list (ses-cell-symbol cell)))
980 (setq formula-error sig
982 (if (and (not newval) (eq oldval '*skip*))
983 ;; Don't lose the *skip* --- previous field spans this one.
984 (setq newval '*skip*))
986 (when (or force (not (eq newval oldval)))
987 (cl-pushnew (cons row col) ses--deferred-write :test #'equal) ; In case force=t.
988 (ses--letref (pget pset)
989 (ses-cell-property :ses-Dijkstra-attempt cell)
990 (let ((this-cell-Dijkstra-attempt (pget)))
991 (if (null this-cell-Dijkstra-attempt)
993 (setq this-cell-Dijkstra-attempt
994 (cons ses--Dijkstra-attempt-nb 0)))
995 (unless (= ses--Dijkstra-attempt-nb
996 (car this-cell-Dijkstra-attempt))
997 (setcar this-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
998 (setcdr this-cell-Dijkstra-attempt 0)))
999 (setq this-cell-Dijkstra-attempt+1
1000 (1+ (cdr this-cell-Dijkstra-attempt)))))
1001 (ses-set-cell row col 'value newval)
1002 (dolist (ref (ses-cell-references cell))
1003 (cl-pushnew ref ses--deferred-recalc)
1004 (ses--letref (pget pset)
1005 (let ((ref-rowcol (ses-sym-rowcol ref)))
1007 :ses-Dijkstra-attempt
1008 (car ref-rowcol) (cdr ref-rowcol)))
1009 (let ((ref-cell-Dijkstra-attempt (pget)))
1011 (if (null ref-cell-Dijkstra-attempt)
1013 (setq ref-cell-Dijkstra-attempt
1014 (cons ses--Dijkstra-attempt-nb
1015 this-cell-Dijkstra-attempt+1)))
1016 (if (= (car ref-cell-Dijkstra-attempt) ses--Dijkstra-attempt-nb)
1017 (setcdr ref-cell-Dijkstra-attempt
1018 (max (cdr ref-cell-Dijkstra-attempt)
1019 this-cell-Dijkstra-attempt+1))
1020 (setcar ref-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
1021 (setcdr ref-cell-Dijkstra-attempt
1022 this-cell-Dijkstra-attempt+1)))))
1024 (when (> this-cell-Dijkstra-attempt+1 ses--Dijkstra-weight-bound)
1025 ;; Update print of this cell.
1026 (throw 'cycle (setq formula-error
1027 `(error ,(format "Found cycle on cells %S"
1028 (ses-cell-symbol cell)))
1029 cycle-error formula-error)))))))
1030 (setq printer-error (ses-print-cell row col))
1033 (error (error-message-string cycle-error)))
1034 formula-error printer-error)))
1036 (defun ses-clear-cell (row col)
1037 "Delete formula and printer for cell (ROW,COL)."
1038 (ses-set-cell row col 'printer nil)
1039 (ses-cell-set-formula row col nil))
1041 (defcustom ses-self-reference-early-detection nil
1042 "True if cycle detection is early for cells that refer to themselves."
1047 (defun ses-update-cells (list &optional force)
1048 "Recalculate cells in LIST, checking for dependency loops. Prints
1049 progress messages every second. Dependent cells are not recalculated
1050 if the cell's value is unchanged and FORCE is nil."
1051 (let ((ses--deferred-recalc list)
1054 curlist prevlist this-sym this-rowcol formula)
1055 (with-temp-message " "
1056 (while ses--deferred-recalc
1057 ;; In each loop, recalculate cells that refer only to other cells that
1058 ;; have already been recalculated or aren't in the recalculation region.
1059 ;; Repeat until all cells have been processed or until the set of cells
1060 ;; being worked on stops changing.
1062 (message "Recalculating... (%d cells left)"
1063 (length ses--deferred-recalc)))
1064 (setq curlist ses--deferred-recalc
1065 ses--deferred-recalc nil
1068 ;; this-sym has to be popped from curlist *BEFORE* the check, and not
1069 ;; after because of the case of cells referring to themselves.
1070 (setq this-sym (pop curlist)
1071 this-rowcol (ses-sym-rowcol this-sym)
1072 formula (ses-cell-formula (car this-rowcol)
1075 (dolist (ref (ses-formula-references formula))
1076 (if (and ses-self-reference-early-detection (eq ref this-sym))
1077 (error "Cycle found: cell %S is self-referring" this-sym)
1078 (when (or (memq ref curlist)
1079 (memq ref ses--deferred-recalc))
1080 ;; This cell refers to another that isn't done yet
1081 (cl-pushnew this-sym ses--deferred-recalc :test #'equal)
1083 ;; ses-update-cells is called from post-command-hook, so
1084 ;; inhibit-quit is implicitly bound to t.
1086 ;; Abort the recalculation. User will probably undo now.
1088 (ses-calculate-cell (car this-rowcol) (cdr this-rowcol) force)))
1089 (dolist (ref ses--deferred-recalc)
1090 (cl-pushnew ref nextlist :test #'equal)))
1091 (when ses--deferred-recalc
1092 ;; Just couldn't finish these.
1093 (dolist (x ses--deferred-recalc)
1094 (let ((this-rowcol (ses-sym-rowcol x)))
1095 (ses-set-cell (car this-rowcol) (cdr this-rowcol) 'value '*error*)
1096 (1value (ses-print-cell (car this-rowcol) (cdr this-rowcol)))))
1097 (error "Circular references: %s" ses--deferred-recalc))
1099 ;; Can't use save-excursion here: if the cell under point is updated,
1100 ;; save-excursion's marker will move past the cell.
1104 ;;----------------------------------------------------------------------------
1106 ;;----------------------------------------------------------------------------
1108 (defun ses-in-print-area ()
1109 "Return t if point is in print area of spreadsheet."
1110 (<= (point) ses--data-marker))
1112 ;; We turn off point-motion-hooks and explicitly position the cursor, in case
1113 ;; the intangible properties have gotten screwed up (e.g., when ses-goto-print
1114 ;; is called during a recursive ses-print-cell).
1115 (defun ses-goto-print (row col)
1116 "Move point to print area for cell (ROW,COL)."
1118 (goto-char (point-min))
1120 ;; Calculate column position.
1122 (setq n (+ n (ses-col-width c) 1)))
1123 ;; Move to the position.
1124 (and (> n (move-to-column n))
1126 ;; Move point to the bol of next line (for TAB at the last cell).
1129 (defun ses--cell-at-pos (pos &optional object)
1130 (or (get-text-property pos 'cursor-intangible object)
1131 ;; (when (> pos (if object 0 (point-min)))
1132 ;; (get-text-property (1- pos) 'cursor-intangible object))
1135 (defun ses--curcell (&optional pos)
1136 "Return the current cell symbol, or a cons (BEG,END) for a
1137 region, or nil if cursor is not at a cell."
1138 (unless pos (setq pos (point)))
1139 (if (or (not mark-active)
1143 (ses--cell-at-pos pos)
1145 (let* ((re (max pos (mark t)))
1146 (bcell (ses--cell-at-pos (min pos (mark t))))
1147 (ecell (ses--cell-at-pos (1- re))))
1148 (when (= re ses--data-marker)
1149 ;; Correct for overflow.
1150 (setq ecell (ses--cell-at-pos (- (region-end) 2))))
1151 (if (and bcell ecell)
1155 (defun ses-set-curcell ()
1156 "Set `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
1157 region, or nil if cursor is not at a cell."
1158 (setq ses--curcell (ses--curcell))
1161 (defun ses-check-curcell (&rest args)
1162 "Signal an error if `ses--curcell' is inappropriate.
1163 The end marker is appropriate if some argument is `end'.
1164 A range is appropriate if some argument is `range'.
1165 A single cell is appropriate unless some argument is `needrange'."
1166 (ses-set-curcell); fix bug#21054
1169 (or (memq 'end args)
1170 (error "Not at cell")))
1171 ((consp ses--curcell)
1172 (or (memq 'range args)
1173 (memq 'needrange args)
1174 (error "Can't use a range")))
1175 ((memq 'needrange args)
1176 (error "Need a range"))))
1181 (defun ses-print-cell (row col)
1182 "Format and print the value of cell (ROW,COL) to the print area.
1183 Use the cell's printer function. If the cell's new print form is too wide,
1184 it will spill over into the following cell, but will not run off the end of the
1185 row or overwrite the next non-nil field. Result is nil for normal operation,
1186 or the error signal if the printer function failed and the cell was formatted
1187 with \"%s\". If the cell's value is *skip*, nothing is printed because the
1188 preceding cell has spilled over."
1189 (catch 'ses-print-cell
1190 (let* ((cell (ses-get-cell row col))
1191 (value (ses-cell-value cell))
1192 (printer (ses-cell-printer cell))
1194 text sig startpos x)
1195 ;; Create the string to print.
1198 ;; Don't print anything.
1199 (throw 'ses-print-cell nil))
1200 ((eq value '*error*)
1201 (setq text (make-string (ses-col-width col) ?#)))
1203 ;; Deferred safety-check on printer.
1204 (if (eq (car-safe printer) 'ses-safe-printer)
1205 (ses-set-cell row col 'printer
1206 (setq printer (ses-safe-printer (cadr printer)))))
1209 (let ((ses--row row)
1211 (ses-call-printer (or printer
1212 (ses-col-printer col)
1213 ses--default-printer)
1215 (if (consp ses-call-printer-return)
1216 ;; Printer returned an error.
1217 (setq sig ses-call-printer-return))))
1218 ;; Adjust print width to match column width.
1219 (let ((width (ses-col-width col))
1220 (len (string-width text)))
1223 ;; Fill field to length with spaces.
1224 (setq len (make-string (- width len) ?\s)
1225 text (if (or (stringp value)
1226 (eq ses-call-printer-return t))
1228 (concat len text))))
1230 ;; Spill over into following cells, if possible.
1231 (let ((maxwidth width))
1232 (while (and (> len maxwidth)
1233 (< maxcol ses--numcols)
1234 (or (not (setq x (ses-cell-value row maxcol)))
1237 ;; Set this cell to '*skip* so it won't overwrite our spillover.
1238 (ses-set-cell row maxcol 'value '*skip*))
1239 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
1240 maxcol (1+ maxcol)))
1241 (if (<= len maxwidth)
1242 ;; Fill to complete width of all the fields spanned.
1243 (setq text (concat text (make-string (- maxwidth len) ?\s)))
1244 ;; Not enough room to end of line or next non-nil field. Truncate
1245 ;; if string or decimal; otherwise fill with error indicator.
1246 (setq sig `(error "Too wide" ,text))
1249 (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
1250 ((and (numberp value)
1251 (string-match "\\.[0-9]+" text)
1254 (- (match-end 0) (match-beginning 0))))))
1255 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
1256 (setq text (concat (substring text
1258 (- (match-beginning 0) width))
1259 (substring text (match-end 0)))))
1261 (setq text (make-string maxwidth ?#)))))))))
1262 ;; Substitute question marks for tabs and newlines. Newlines are used as
1263 ;; row-separators; tabs could confuse the reimport logic.
1264 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
1265 (ses-goto-print row col)
1266 (setq startpos (point))
1267 ;; Install the printed result. This is not interruptible.
1268 (let ((inhibit-read-only t)
1270 (delete-region (point) (progn
1271 (move-to-column (+ (current-column)
1272 (string-width text)))
1274 ;; We use concat instead of inserting separate strings in order to
1275 ;; reduce the number of cells in the undo list.
1276 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
1277 ;; We use set-text-properties to prevent a wacky print function from
1278 ;; inserting rogue properties, and to ensure that the keymap property is
1279 ;; inherited (is it a bug that only unpropertized strings actually
1280 ;; inherit from surrounding text?)
1281 (set-text-properties 0 (length x) nil x)
1282 (insert-and-inherit x)
1283 (put-text-property startpos (point) 'cursor-intangible
1284 (ses-cell-symbol cell))
1285 (when (and (zerop row) (zerop col))
1286 ;; Reconstruct special beginning-of-buffer attributes.
1287 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
1288 (put-text-property (point-min) (point) 'read-only 'ses)
1289 (put-text-property (point-min) (1+ (point-min))
1290 ;; `cursor-intangible' shouldn't be sticky at BOB.
1291 'front-sticky '(read-only keymap))))
1292 (if (= row (1- ses--header-row))
1293 ;; This line is part of the header --- force recalc.
1294 (ses-reset-header-string))
1295 ;; If this cell (or a preceding one on the line) previously spilled over
1296 ;; and has gotten shorter, redraw following cells on line recursively.
1297 (when (and (< maxcol ses--numcols)
1298 (eq (ses-cell-value row maxcol) '*skip*))
1299 (ses-set-cell row maxcol 'value nil)
1300 (ses-print-cell row maxcol))
1301 ;; Return to start of cell.
1302 (goto-char startpos)
1305 (defun ses-call-printer (printer &optional value)
1306 "Invoke PRINTER (a string or parenthesized string or function-symbol or
1307 lambda of one argument) on VALUE. Result is the printed cell as a string.
1308 The variable `ses-call-printer-return' is set to t if the printer used
1309 parenthesis to request left-justification, or the error-signal if the
1310 printer signaled one (and \"%s\" is used as the default printer), else nil."
1311 (setq ses-call-printer-return nil)
1312 (condition-case signal
1316 (format printer value)
1318 ((stringp (car-safe printer))
1319 (setq ses-call-printer-return t)
1321 (format (car printer) value)
1326 (or (and (symbolp printer)
1327 (let ((locprn (gethash printer
1328 ses--local-printer-hashmap)))
1330 (ses--locprn-compiled locprn))))
1335 (or (stringp (car-safe value))
1336 (error "Printer should return \"string\" or (\"string\")"))
1337 (setq ses-call-printer-return t)
1340 (setq ses-call-printer-return signal)
1341 (ses-prin1 value))))
1343 (defun ses-adjust-print-width (col change)
1344 "Insert CHANGE spaces in front of column COL, or at end of line if
1345 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
1346 `inhibit-quit' to t."
1347 (let ((inhibit-read-only t)
1348 (blank (if (> change 0) (make-string change ?\s)))
1349 (at-end (= col ses--numcols)))
1350 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
1351 ;; ses-set-with-undo always returns t for strings.
1352 (1value (ses-set-with-undo 'ses--blank-line
1353 (concat (make-string ses--linewidth ?\s) "\n")))
1354 (dotimes (row ses--numrows)
1355 (ses-goto-print row col)
1357 ;; Insert new columns before newline.
1361 (delete-char (- change))))))
1363 (defun ses-print-cell-new-width (row col)
1364 "Same as `ses-print-cell', except if the cell's value is *skip*,
1365 the preceding nonskipped cell is reprinted. This function is used
1366 when the width of cell (ROW,COL) has changed."
1367 (if (not (eq (ses-cell-value row col) '*skip*))
1368 (ses-print-cell row col)
1369 ;;Cell was skipped over - reprint previous
1370 (ses-goto-print row col)
1372 (let ((rowcol (ses-sym-rowcol (ses--cell-at-pos (point)))))
1373 (ses-print-cell (car rowcol) (cdr rowcol)))))
1376 ;;----------------------------------------------------------------------------
1378 ;;----------------------------------------------------------------------------
1381 "Turn off narrowing, to be reenabled at end of command loop."
1382 (if (buffer-narrowed-p)
1383 (setq ses--deferred-narrow t))
1386 (defun ses-goto-data (def &optional col)
1387 "Move point to data area for (DEF,COL). If DEF is a row
1388 number, COL is the column number for a data cell -- otherwise DEF
1389 is one of the symbols ses--col-widths, ses--col-printers,
1390 ses--default-printer, ses--numrows, or ses--numcols."
1395 (goto-char ses--data-marker)
1396 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
1397 ;; Convert def-symbol to offset.
1398 (setq def (plist-get ses-paramlines-plist def))
1399 (or def (signal 'args-out-of-range nil))
1400 (goto-char ses--params-marker)
1401 (forward-line def)))
1403 (defun ses-file-format-extend-parameter-list (new-file-format)
1404 "Extend the global parameters list when file format is updated
1405 from 2 to 3. This happens when local printer function are added
1406 to a sheet that was created with SES version 2. This is not
1407 undoable. Return nil when there was no change, and non nil otherwise."
1410 ((and (= ses--file-format 2) (= 3 new-file-format))
1411 (ses-set-parameter 'ses--file-format 3)
1412 (message "Upgrading from SES-2 to SES-3 file format")
1414 (goto-char ses--params-marker)
1415 (forward-line (plist-get ses-paramlines-plist 'ses--numlocprn ))
1416 (insert (format (plist-get ses-paramfmt-plist 'ses--numlocprn)
1421 (defun ses-set-parameter (def value &optional elem)
1422 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1423 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1424 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
1426 ;; We call ses-goto-data early, using the old values of numrows and numcols
1427 ;; in case one of them is being changed.
1429 (let ((inhibit-read-only t)
1430 (fmt (plist-get ses-paramfmt-plist
1435 (setq oldval (aref (symbol-value def) elem))
1436 (aset (symbol-value def) elem value))
1437 (setq oldval (symbol-value def))
1439 ;; Special undo since it's outside the narrowed buffer.
1440 (let (buffer-undo-list)
1441 (delete-region (point) (line-end-position))
1442 (insert (format fmt (symbol-value def))))
1443 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1446 (defun ses-write-cells ()
1447 "Write cells in `ses--deferred-write' from local variables to data area.
1448 Newlines in the data are escaped."
1449 (let* ((inhibit-read-only t)
1450 (print-escape-newlines t)
1451 rowcol row col cell sym formula printer text)
1452 (setq ses-start-time (float-time))
1453 (with-temp-message " "
1455 (while ses--deferred-write
1456 (ses--time-check "Writing... (%d cells left)"
1457 (length ses--deferred-write))
1458 (setq rowcol (pop ses--deferred-write)
1461 cell (ses-get-cell row col)
1462 sym (ses-cell-symbol cell)
1463 formula (ses-cell-formula cell)
1464 printer (ses-cell-printer cell))
1465 (if (eq (car-safe formula) 'ses-safe-formula)
1466 (setq formula (cadr formula)))
1467 (if (eq (car-safe printer) 'ses-safe-printer)
1468 (setq printer (cadr printer)))
1469 (setq text (prin1-to-string
1470 ;; We could shorten it to (ses-cell SYM VAL) when
1471 ;; the other parameters are nil, but in practice most
1472 ;; cells have non-nil `references', so it's
1473 ;; rather pointless.
1476 ,(unless (equal formula (symbol-value sym))
1479 ,(ses-cell-references cell))))
1480 (ses-goto-data row col)
1481 (delete-region (point) (line-end-position))
1486 ;;----------------------------------------------------------------------------
1487 ;; Formula relocation
1488 ;;----------------------------------------------------------------------------
1490 (defun ses-formula-references (formula &optional result-so-far)
1491 "Produce a list of symbols for cells that this FORMULA's value
1492 refers to. For recursive calls, RESULT-SO-FAR is the list being
1493 constructed, or t to get a wrong-type-argument error when the
1494 first reference is found."
1495 (if (ses-sym-rowcol formula)
1496 ;; Entire formula is one symbol.
1497 (cl-pushnew formula result-so-far :test #'equal)
1500 ((eq (car formula) 'ses-range)
1502 (cdr (funcall 'macroexpand
1503 (list 'ses-range (nth 1 formula)
1505 (cl-pushnew cur result-so-far :test #'equal)))
1506 ((null (eq (car formula) 'quote))
1507 ;;Recursive call for subformulas
1508 (dolist (cur formula)
1509 (setq result-so-far (ses-formula-references cur result-so-far))))
1511 ;;Ignore other stuff
1513 ;; other type of atom are ignored
1517 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1518 "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
1519 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1520 by (ROWINCR,COLINCR)."
1521 (let ((row (car rowcol))
1523 (if (or (< row startrow) (< col startcol))
1525 (setq row (+ row rowincr)
1526 col (+ col colincr))
1527 (if (and (>= row startrow) (>= col startcol)
1528 (< row ses--numrows) (< col ses--numcols))
1529 ;;Relocate this variable, unless it is a named cell
1530 (if (eq (get sym 'ses-cell) :ses-named)
1532 (ses-create-cell-symbol row col))
1533 ;;Delete reference to a deleted cell
1536 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1537 "Produce a copy of FORMULA where all symbols that refer to cells in row
1538 STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
1539 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1540 (ses-relocate-formula \\='(+ A1 B2 D3) 1 2 1 -1)
1542 If ROWINCR or COLINCR is negative, references to cells being deleted are
1544 (ses-relocate-formula \\='(+ A1 B2 D3) 0 1 0 -1)
1546 Sets `ses-relocate-return' to `delete' if cell-references were removed."
1547 (let (rowcol result)
1548 (if (or (atom formula) (eq (car formula) 'quote))
1549 (if (setq rowcol (ses-sym-rowcol formula))
1550 (ses-relocate-symbol formula rowcol
1551 startrow startcol rowincr colincr)
1552 ;; Constants pass through as-is.
1554 (dolist (cur formula)
1555 (setq rowcol (ses-sym-rowcol cur))
1558 (setq cur (ses-relocate-symbol cur rowcol
1559 startrow startcol rowincr colincr))
1562 ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
1563 ;; don't change the flag if it's already 'range, since range implies
1565 (unless ses-relocate-return
1566 (setq ses-relocate-return 'delete))))
1567 ((eq (car-safe cur) 'ses-range)
1568 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1571 ((or (atom cur) (eq (car cur) 'quote))
1572 ;; Constants pass through unchanged.
1575 ;; Recursively copy and alter subformulas.
1576 (push (ses-relocate-formula cur startrow startcol
1579 (nreverse result))))
1581 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1582 "Relocate one RANGE, of the form (ses-range MIN MAX). Cells starting
1583 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1584 new range, or nil if the entire range is deleted. If new rows are being added
1585 just beyond the end of a row range, or new columns just beyond a column range,
1586 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1587 if the range was altered."
1588 (let* ((minorig (cadr range))
1589 (minrowcol (ses-sym-rowcol minorig))
1590 (min (ses-relocate-symbol minorig minrowcol
1593 (maxorig (nth 2 range))
1594 (maxrowcol (ses-sym-rowcol maxorig))
1595 (max (ses-relocate-symbol maxorig maxrowcol
1600 ((and (not min) (not max))
1601 (setq range nil)) ; The entire range is deleted.
1603 ;; Inserting or deleting rows.
1606 ;; Chopped off beginning of range.
1607 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1608 ses-relocate-return 'range))
1611 ;; Trying to insert a nonexistent row.
1612 (setq max (ses-create-cell-symbol (1- ses--numrows)
1614 ;; End of range is being deleted.
1615 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1616 ses-relocate-return 'range))
1618 (= (car maxrowcol) (1- startrow))
1619 (= (cdr minrowcol) (cdr maxrowcol))
1620 ;; Insert after ending row of vertical range --- include it.
1621 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1622 (cdr maxrowcol))))))
1624 ;; Inserting or deleting columns.
1627 ;; Chopped off beginning of range.
1628 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1629 ses-relocate-return 'range))
1632 ;; Trying to insert a nonexistent column.
1633 (setq max (ses-create-cell-symbol (car maxrowcol)
1635 ;; End of range is being deleted.
1636 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1637 ses-relocate-return 'range))
1639 (= (cdr maxrowcol) (1- startcol))
1640 (= (car minrowcol) (car maxrowcol))
1641 ;; Insert after ending column of horizontal range --- include it.
1642 (setq max (ses-create-cell-symbol (car maxrowcol)
1643 (+ startcol colincr -1)))))))
1645 (if (/= (- (funcall field maxrowcol)
1646 (funcall field minrowcol))
1647 (- (funcall field (ses-sym-rowcol max))
1648 (funcall field (ses-sym-rowcol min))))
1649 ;; This range has changed size.
1650 (setq ses-relocate-return 'range))
1651 `(ses-range ,min ,max ,@(cl-cdddr range)))))
1653 (defun ses-relocate-all (minrow mincol rowincr colincr)
1654 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1655 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1658 (let (mycell newval xrow)
1659 (dotimes-with-progress-reporter
1660 (row ses--numrows) "Relocating formulas..."
1661 (dotimes (col ses--numcols)
1662 (setq ses-relocate-return nil
1663 mycell (ses-get-cell row col)
1664 newval (ses-relocate-formula (ses-cell-formula mycell)
1665 minrow mincol rowincr colincr)
1666 xrow (- row rowincr))
1667 (ses-set-cell row col 'formula newval)
1668 (if (eq ses-relocate-return 'range)
1669 ;; This cell contains a (ses-range X Y) where a cell has been
1670 ;; inserted or deleted in the middle of the range.
1671 (push (cons row col) reform))
1672 (if ses-relocate-return
1673 ;; This cell referred to a cell that's been deleted or is no
1674 ;; longer part of the range. We can't fix that now because
1675 ;; reference lists cells have been partially updated.
1676 (cl-pushnew (ses-create-cell-symbol row col)
1677 ses--deferred-recalc :test #'equal))
1678 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1679 minrow mincol rowincr colincr))
1680 (ses-set-cell row col 'references newval)
1681 (and (>= row minrow) (>= col mincol)
1682 (let ((sym (ses-cell-symbol row col))
1683 (xcol (- col colincr)))
1688 ;; the following could also be tested as
1689 ;; (null (eq sym (ses-create-cell-symbol xrow xcol)))
1690 (eq (get sym 'ses-cell) :ses-named))
1691 ;; This is a renamed cell, do not update the cell
1692 ;; name, but just update the coordinate property.
1693 (puthash sym (cons row col) ses--named-cell-hashmap)
1694 (ses-set-cell row col 'symbol
1695 (setq sym (ses-create-cell-symbol row col)))
1696 (unless (local-variable-if-set-p sym)
1697 (set (make-local-variable sym) nil)
1698 (put sym 'ses-cell (cons row col)))))) )))
1699 ;; Relocate the cell values.
1700 (let (oldval myrow mycol xrow xcol)
1702 ((and (<= rowincr 0) (<= colincr 0))
1703 ;; Deletion of rows and/or columns.
1704 (dotimes-with-progress-reporter
1705 (row (- ses--numrows minrow)) "Relocating variables..."
1706 (setq myrow (+ row minrow))
1707 (dotimes (col (- ses--numcols mincol))
1708 (setq mycol (+ col mincol)
1709 xrow (- myrow rowincr)
1710 xcol (- mycol colincr))
1711 (let ((sym (ses-cell-symbol myrow mycol)))
1712 ;; We don't need to relocate value for renamed cells, as they keep the same
1714 (unless (eq (get sym 'ses-cell) :ses-named)
1715 (ses-set-cell myrow mycol 'value
1716 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1717 (ses-cell-value xrow xcol)
1718 ;; Cell is off the end of the array.
1719 (symbol-value (ses-create-cell-symbol xrow xcol))))))))
1720 (when ses--in-killing-named-cell-list
1721 (message "Unbinding killed named cell symbols...")
1722 (setq ses-start-time (float-time))
1723 (while ses--in-killing-named-cell-list
1724 (ses--time-check "Unbinding killed named cell symbols... (%d left)" (length ses--in-killing-named-cell-list))
1725 (ses--unbind-cell-name (pop ses--in-killing-named-cell-list)) )
1728 ((and (wholenump rowincr) (wholenump colincr))
1729 ;; Insertion of rows and/or columns. Run the loop backwards.
1730 (let ((disty (1- ses--numrows))
1731 (distx (1- ses--numcols))
1733 (dotimes-with-progress-reporter
1734 (row (- ses--numrows minrow)) "Relocating variables..."
1735 (setq myrow (- disty row))
1736 (dotimes (col (- ses--numcols mincol))
1737 (setq mycol (- distx col)
1738 xrow (- myrow rowincr)
1739 xcol (- mycol colincr))
1740 (if (or (< xrow minrow) (< xcol mincol))
1741 ;; Newly-inserted value.
1743 ;; Transfer old value.
1744 (setq oldval (ses-cell-value xrow xcol)))
1745 (ses-set-cell myrow mycol 'value oldval)))
1746 t)) ; Make testcover happy by returning non-nil here.
1748 (error "ROWINCR and COLINCR must have the same sign"))))
1749 ;; Reconstruct reference lists for cells that contain ses-ranges that have
1752 (message "Fixing ses-ranges...")
1754 (setq ses-start-time (float-time))
1756 (ses--time-check "Fixing ses-ranges... (%d left)" (length reform))
1757 (setq row (caar reform)
1759 reform (cdr reform))
1760 (ses-cell-set-formula row col (ses-cell-formula row col))))
1764 ;;----------------------------------------------------------------------------
1766 ;;----------------------------------------------------------------------------
1768 (defun ses-begin-change ()
1769 "For undo, remember point before we start changing hidden stuff."
1770 (let ((inhibit-read-only t))
1771 (insert-and-inherit "X")
1772 (delete-region (1- (point)) (point))))
1774 (defun ses-setter-with-undo (accessors newval &rest args)
1775 "Set a field/variable and record it so it can be undone.
1776 Result is non-nil if field/variable has changed."
1777 (let ((oldval (apply (car accessors) args)))
1778 (unless (equal-including-properties oldval newval)
1779 (push `(apply ses-setter-with-undo ,accessors ,oldval ,@args)
1781 (apply (cdr accessors) newval args)
1784 (defun ses-aset-with-undo (array idx newval)
1785 (ses-setter-with-undo (eval-when-compile
1787 (lambda (newval array idx) (aset array idx newval))))
1790 (defun ses-set-with-undo (sym newval)
1791 (ses-setter-with-undo
1793 (cons (lambda (sym) (if (boundp sym) (symbol-value sym) :ses--unbound))
1794 (lambda (newval sym) (if (eq newval :ses--unbound)
1796 (set sym newval)))))
1799 ;;----------------------------------------------------------------------------
1800 ;; Startup for major mode
1801 ;;----------------------------------------------------------------------------
1804 "Parse the current buffer and set up buffer-local variables.
1805 Does not execute cell formulas or print functions."
1807 ;; Read our global parameters, which should be a 3-element list.
1808 (goto-char (point-max))
1809 (search-backward ";; Local Variables:\n" nil t)
1811 (setq ses--params-marker (point-marker))
1812 (let* ((params (ignore-errors (read (current-buffer))))
1813 (params-len (safe-length params)))
1814 (or (and (>= params-len 3)
1816 (numberp (car params))
1817 (numberp (cadr params))
1818 (>= (cadr params) 0)
1819 (numberp (nth 2 params))
1820 (> (nth 2 params) 0)
1821 (or (<= params-len 3)
1822 (let ((numlocprn (nth 3 params)))
1823 (and (integerp numlocprn) (>= numlocprn 0)))))
1824 (error "Invalid SES file"))
1825 (setq ses--file-format (car params)
1826 ses--numrows (cadr params)
1827 ses--numcols (nth 2 params)
1828 ses--numlocprn (or (nth 3 params) 0))
1829 (when (= ses--file-format 1)
1830 (let (buffer-undo-list) ; This is not undoable.
1831 (ses-goto-data 'ses--header-row)
1832 (insert "(ses-header-row 0)\n")
1833 (ses-set-parameter 'ses--file-format 3)
1834 (message "Upgrading from SES-1 to SES-2 file format")))
1835 (or (<= ses--file-format 3)
1836 (error "This file needs a newer version of the SES library code"))
1837 ;; Initialize cell array.
1838 (setq ses--cells (make-vector ses--numrows nil))
1839 (dotimes (row ses--numrows)
1840 (aset ses--cells row (make-vector ses--numcols nil)))
1841 ;; initialize local printer map.
1842 (clrhash ses--local-printer-hashmap))
1844 ;; Skip over print area, which we assume is correct.
1845 (goto-char (point-min))
1846 (forward-line ses--numrows)
1847 (or (looking-at-p ses-print-data-boundary)
1848 (error "Missing marker between print and data areas"))
1850 (setq ses--data-marker (point-marker))
1851 (forward-char (1- (length ses-print-data-boundary)))
1852 ;; Initialize printer and symbol lists.
1853 (mapc #'ses-printer-record ses-standard-printer-functions)
1854 (setq ses--symbolic-formulas nil)
1856 ;; Load local printer definitions.
1857 ;; This must be loaded *BEFORE* cells and column printers because the latter
1860 (forward-line (* ses--numrows (1+ ses--numcols)))
1861 (let ((numlocprn ses--numlocprn))
1862 (setq ses--numlocprn 0)
1863 (dotimes (_ numlocprn)
1864 (let ((x (read (current-buffer))))
1865 (or (and (looking-at-p "\n")
1866 (eq (car-safe x) 'ses-local-printer)
1867 (apply #'ses--local-printer (cdr x)))
1868 (error "local printer-def error"))
1869 (setq ses--numlocprn (1+ ses--numlocprn))))))
1870 ;; Load cell definitions.
1871 (dotimes (row ses--numrows)
1872 (dotimes (col ses--numcols)
1873 (let* ((x (read (current-buffer)))
1874 (sym (car-safe (cdr-safe x))))
1875 (or (and (looking-at-p "\n")
1876 (eq (car-safe x) 'ses-cell)
1877 (ses-create-cell-variable sym row col))
1878 (error "Cell-def error"))
1879 (apply #'ses--cell (cdr x))))
1880 (or (looking-at-p "\n\n")
1881 (error "Missing blank line between rows")))
1882 ;; Skip local printer function declaration --- that were already loaded.
1883 (forward-line (+ 2 ses--numlocprn))
1884 ;; Load global parameters.
1885 (let ((widths (read (current-buffer)))
1886 (n1 (char-after (point)))
1887 (printers (read (current-buffer)))
1888 (n2 (char-after (point)))
1889 (def-printer (read (current-buffer)))
1890 (n3 (char-after (point)))
1891 (head-row (read (current-buffer)))
1892 (n4 (char-after (point))))
1893 (or (and (eq (car-safe widths) 'ses-column-widths)
1895 (eq (car-safe printers) 'ses-column-printers)
1897 (eq (car-safe def-printer) 'ses-default-printer)
1899 (eq (car-safe head-row) 'ses-header-row)
1901 (error "Invalid SES global parameters"))
1902 (1value (eval widths t))
1903 (1value (eval def-printer t))
1904 (1value (eval printers t))
1905 (1value (eval head-row t)))
1906 ;; Should be back at global-params.
1908 (or (looking-at-p ses-initial-global-parameters-re)
1909 (error "Problem with column-defs or global-params"))
1910 ;; Check for overall newline count in definitions area.
1912 (let ((start (point)))
1913 (ses-goto-data 'ses--numrows)
1914 (or (= (point) start)
1915 (error "Extraneous newlines someplace?"))))
1918 "Set up for display of only the printed cell values.
1920 Narrows the buffer to show only the print area. Gives it `read-only' and
1921 `intangible' properties. Sets up highlighting for current cell."
1923 (let ((end (point-min))
1925 (with-silent-modifications
1926 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1927 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1928 (mapc #'delete-overlay (overlays-in (point-min) (point-max)))
1929 ;; The print area is read-only (except for our special commands) and
1930 ;; uses a special keymap.
1931 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1932 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1933 ;; For the beginning of the buffer, we want the read-only and keymap
1934 ;; attributes to be inherited from the first character.
1935 (put-text-property (point-min) (1+ (point-min))
1936 ;; `cursor-intangible' shouldn't be sticky at BOB.
1937 'front-sticky '(read-only keymap))
1938 ;; Create intangible properties, which also indicate which cell the text
1940 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1941 (dotimes (col ses--numcols)
1943 sym (ses-cell-symbol row col))
1944 (unless (eq (symbol-value sym) '*skip*)
1945 ;; Include skipped cells following this one.
1946 (while (and (< col (1- ses--numcols))
1947 (eq (ses-cell-value row (1+ col)) '*skip*))
1948 (setq end (+ end (ses-col-width col) 1)
1949 ;; Beware: Modifying the iteration variable of `dotimes'
1950 ;; may or may not affect the iteration!
1952 (setq end (save-excursion
1954 (move-to-column (+ (current-column) (- end pos)
1955 (ses-col-width col)))
1957 (+ end (ses-col-width col) 1)
1960 (put-text-property pos end 'cursor-intangible sym))))))
1961 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1962 ;; because column A must be at least 1 column wide.
1963 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1964 (overlay-put ses--curcell-overlay 'face 'underline))
1966 (defun ses-cleanup ()
1967 "Cleanup when changing a buffer from SES mode to something else.
1968 Delete overlays, remove special text properties."
1970 (let ((inhibit-read-only t)
1971 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1972 ;; user "the file is modified, do you really want to make modifications
1973 ;; to this buffer", where the "modifications" refer to the irrelevant
1974 ;; set-text-properties below.
1975 (buffer-file-name nil)
1976 (was-modified (buffer-modified-p)))
1977 ;; Delete read-only, keymap, and intangible properties.
1978 (set-text-properties (point-min) (point-max) nil)
1980 (mapc #'delete-overlay (overlays-in (point-min) (point-max)))
1981 (unless was-modified
1982 (restore-buffer-modified-p nil))))
1984 (defun ses-killbuffer-hook ()
1985 "Hook when the current buffer is killed."
1986 (setq ses--ses-buffer-list (delq (current-buffer) ses--ses-buffer-list)))
1991 "Major mode for Simple Emacs Spreadsheet.
1993 When you invoke SES in a new buffer, it is divided into cells
1994 that you can enter data into. You can navigate the cells with
1995 the arrow keys and add more cells with the tab key. The contents
1996 of these cells can be numbers, text, or Lisp expressions. (To
1997 enter text, enclose it in double quotes.)
1999 In an expression, you can use cell coordinates to refer to the
2000 contents of another cell. For example, you can sum a range of
2001 cells with `(+ A1 A2 A3)'. There are specialized functions like
2002 `ses+' (addition for ranges with empty cells), `ses-average' (for
2003 performing calculations on cells), and `ses-range' and `ses-select'
2004 \(for extracting ranges of cells).
2006 Each cell also has a print function that controls how it is
2009 Each SES buffer is divided into a print area and a data area.
2010 Normally, you can simply use SES to look at and manipulate the print
2011 area, and let SES manage the data area outside the visible region.
2013 See \"ses-example.ses\" (in `data-directory') for an example
2014 spreadsheet, and the Info node `(ses)Top.'
2016 In the following, note the separate keymaps for cell editing mode
2017 and print mode specifications. Key definitions:
2020 These key definitions are active only in the print area (the visible
2022 \\{ses-mode-print-map}
2023 These are active only in the minibuffer, when entering or editing a
2025 \\{ses-mode-edit-map}"
2027 (unless (and (boundp 'ses--deferred-narrow)
2028 (eq ses--deferred-narrow 'ses-mode))
2029 (kill-all-local-variables)
2031 (setq major-mode 'ses-mode
2033 next-line-add-newlines nil
2035 ;; SES deliberately puts lots of trailing whitespace in its buffer.
2036 show-trailing-whitespace nil
2037 ;; Cell ranges do not work reasonably without this.
2038 transient-mark-mode t
2039 ;; Not to use tab characters for safe (tabs may do bad for column
2041 indent-tabs-mode nil)
2042 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
2043 (1value (add-hook 'kill-buffer-hook 'ses-killbuffer-hook nil t))
2044 (cl-pushnew (current-buffer) ses--ses-buffer-list :test 'eq)
2045 ;; This makes revert impossible if the buffer is read-only.
2046 ;; (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
2047 (setq header-line-format '(:eval (progn
2048 (when (/= (window-hscroll)
2049 ses--header-hscroll)
2050 ;; Reset ses--header-hscroll first,
2051 ;; to avoid recursion problems when
2052 ;; debugging ses-create-header-string
2053 (setq ses--header-hscroll
2055 (ses-create-header-string))
2056 ses--header-string)))
2057 (setq-local mode-line-process '(:eval (ses--mode-line-process)))
2058 (add-hook 'pre-redisplay-functions #'ses--cursor-sensor-highlight
2059 ;; Highlight the cell after moving cursor out of intangible.
2061 (cursor-intangible-mode 1)
2062 (let ((was-empty (zerop (buffer-size)))
2063 (was-modified (buffer-modified-p)))
2066 ;; Initialize buffer to contain one cell, for now.
2067 (insert ses-initial-file-contents))
2071 (unless (equal ses-initial-default-printer
2072 (1value ses--default-printer))
2073 (1value (ses-read-default-printer ses-initial-default-printer)))
2074 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
2075 (1value (ses-set-column-width 0 ses-initial-column-width)))
2077 (if (> (car ses-initial-size) (1value ses--numrows))
2078 (1value (ses-insert-row (1- (car ses-initial-size)))))
2079 (if (> (cdr ses-initial-size) (1value ses--numcols))
2080 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
2082 (restore-buffer-modified-p was-modified)
2083 (buffer-disable-undo)
2084 (buffer-enable-undo)
2085 (goto-char (point-min))))
2086 (use-local-map ses-mode-map)
2087 ;; Set the deferred narrowing flag (we can't narrow until after
2088 ;; after-find-file completes). If .ses is on the auto-load alist and the
2089 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
2090 ;; special flag to detect this (will be reset by ses-command-hook). For
2091 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
2092 ;; so use an idle timer to make sure.
2093 (setq ses--deferred-narrow 'ses-mode)
2094 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
2095 (run-with-idle-timer 0.01 nil 'ses-command-hook)
2096 (run-mode-hooks 'ses-mode-hook)))
2098 (put 'ses-mode 'mode-class 'special)
2100 (defun ses-command-hook ()
2101 "Invoked from `post-command-hook'. If point has moved to a different cell,
2102 moves the underlining overlay. Performs any recalculations or cell-data
2103 writes that have been deferred. If buffer-narrowing has been deferred,
2104 narrows the buffer now."
2106 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
2107 (when ses--deferred-recalc
2108 ;; We reset the deferred list before starting on the recalc --- in
2109 ;; case of error, we don't want to retry the recalc after every
2111 (ses-initialize-Dijkstra-attempt)
2112 (let ((old ses--deferred-recalc))
2113 (setq ses--deferred-recalc nil)
2114 (ses-update-cells old)))
2115 (when ses--deferred-write
2116 ;; We don't reset the deferred list before starting --- the most
2117 ;; likely error is keyboard-quit, and we do want to keep trying these
2118 ;; writes after a quit.
2120 (push '(apply ses-widen) buffer-undo-list))
2121 (when ses--deferred-narrow
2122 ;; We're not allowed to narrow the buffer until after-find-file has
2123 ;; read the local variables at the end of the file. Now it's safe to
2124 ;; do the narrowing.
2125 (narrow-to-region (point-min) ses--data-marker)
2126 (setq ses--deferred-narrow nil)))
2127 ;; Prevent errors in this post-command-hook from silently erasing the hook!
2129 (unless executing-kbd-macro
2131 (message "%s" (error-message-string err))))
2132 nil) ; Make coverage-tester happy.
2134 (defun ses--mode-line-process ()
2135 (let ((cmlp (window-parameter nil 'ses--mode-line-process))
2136 (curcell (ses--curcell (window-point))))
2137 (if (equal curcell (car cmlp))
2142 ((atom curcell) (list " cell " (symbol-name curcell)))
2145 (symbol-name (car curcell))
2147 (symbol-name (cdr curcell)))))))
2148 (set-window-parameter nil 'ses--mode-line-process (cons curcell mlp))
2151 (defun ses--cursor-sensor-highlight (window)
2152 (let ((curcell (ses--curcell))
2153 (ol (window-parameter window 'ses--curcell-overlay)))
2155 (setq ol (make-overlay (point) (point)))
2156 (overlay-put ol 'window window)
2157 (overlay-put ol 'face 'underline)
2158 (set-window-parameter window 'ses--curcell-overlay ol))
2159 ;; Use underline overlay for single-cells only, turn off otherwise.
2162 (let* ((pos (window-point window))
2163 (next (next-single-property-change pos 'cursor-intangible)))
2164 (move-overlay ol pos (1- next))))))
2166 (defun ses-create-header-string ()
2167 "Set up `ses--header-string' as the buffer's header line.
2168 Based on the current set of columns and `window-hscroll' position."
2169 (let ((totwidth (- (window-hscroll)))
2171 ;; Leave room for the left-side fringe and scrollbar.
2172 (push (propertize " " 'display '((space :align-to 0))) result)
2173 (dotimes (col ses--numcols)
2174 (setq width (ses-col-width col)
2175 totwidth (+ totwidth width 1))
2177 ;; Scrolled so intercolumn space is leftmost.
2179 (when (> totwidth 1)
2180 (if (> ses--header-row 0)
2182 (ses-goto-print (1- ses--header-row) col)
2183 (setq x (buffer-substring-no-properties (point)
2185 ;; Strip trailing space.
2186 (if (string-match "[ \t]+\\'" x)
2187 (setq x (substring x 0 (match-beginning 0))))
2188 ;; Cut off excess text.
2189 (if (>= (length x) totwidth)
2190 (setq x (substring x 0 (- totwidth -1)))))
2191 (setq x (ses-column-letter col)))
2192 (push (propertize x 'face ses-box-prop) result)
2193 (push (propertize "."
2194 'display `((space :align-to ,(1- totwidth)))
2197 ;; Allow the following space to be squished to make room for the 3-D box
2198 ;; Coverage test ignores properties, thinks this is always a space!
2199 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2201 (if (> ses--header-row 0)
2202 (push (propertize (format " [row %d]" ses--header-row)
2203 'display '((height (- 1))))
2205 (setq ses--header-string (apply #'concat (nreverse result)))))
2208 ;;----------------------------------------------------------------------------
2209 ;; Redisplay and recalculation
2210 ;;----------------------------------------------------------------------------
2212 (defun ses-jump (sym)
2213 "Move point to cell SYM."
2214 (interactive (let* (names
2217 (and ses--named-cell-hashmap
2218 (progn (maphash (lambda (key val) (push (symbol-name key) names))
2219 ses--named-cell-hashmap)
2223 (error "Invalid cell name")
2224 (list (intern s)))))
2225 (let ((rowcol (ses-sym-rowcol sym)))
2226 (or rowcol (error "Invalid cell name"))
2227 (if (eq (symbol-value sym) '*skip*)
2228 (error "Cell is covered by preceding cell"))
2229 (ses-goto-print (car rowcol) (cdr rowcol))))
2231 (defun ses-jump-safe (cell)
2232 "Like `ses-jump', but no error if invalid cell."
2236 (defun ses-reprint-all (&optional nonarrow)
2237 "Recreate the display area. Calls all printer functions. Narrows to
2238 print area if NONARROW is nil."
2242 (setq ses--deferred-narrow t))
2243 (let ((startcell (ses--cell-at-pos (point)))
2244 (inhibit-read-only t))
2246 (goto-char (point-min))
2247 (search-forward ses-print-data-boundary)
2248 (backward-char (length ses-print-data-boundary))
2249 (delete-region (point-min) (point))
2250 ;; Insert all blank lines before printing anything, so ses-print-cell can
2251 ;; find the data area when inserting or deleting *skip* values for cells.
2252 (dotimes (_ ses--numrows)
2253 (insert-and-inherit ses--blank-line))
2254 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2255 (if (eq (ses-cell-value row 0) '*skip*)
2256 ;; Column deletion left a dangling skip.
2257 (ses-set-cell row 0 'value nil))
2258 (dotimes (col ses--numcols)
2259 (ses-print-cell row col))
2260 (beginning-of-line 2))
2261 (ses-jump-safe startcell)))
2263 (defun ses-initialize-Dijkstra-attempt ()
2264 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2265 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2267 ;; These functions use the variables 'row' and 'col' that are dynamically bound
2268 ;; by ses-print-cell. We define these variables at compile-time to make the
2275 (defun ses-recalculate-cell (&optional ses--curcell)
2276 "Recalculate and reprint the current cell or range.
2278 If SES--CURCELL is non nil use it as current cell or range
2279 without any check, otherwise fnuction (ses-check-curcell 'range)
2282 For an individual cell, shows the error if the formula or printer
2283 signals one, or otherwise shows the cell's complete value. For a range, the
2284 cells are recalculated in \"natural\" order, so cells that other cells refer
2285 to are recalculated first."
2287 (or ses--curcell (ses-check-curcell 'range))
2289 (ses-initialize-Dijkstra-attempt)
2290 (let (sig cur-rowcol)
2291 (setq ses-start-time (float-time))
2292 (if (atom ses--curcell)
2294 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2296 (setf (ses-cell-property :ses-Dijkstra-attempt
2299 (cons ses--Dijkstra-attempt-nb 0))
2300 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2301 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2302 (cdr cur-rowcol)))))
2303 ;; First, recalculate all cells that don't refer to other cells and
2304 ;; produce a list of cells with references.
2305 (ses-dorange ses--curcell
2306 (ses--time-check "Recalculating... %s" (ses-cell-symbol row col))
2309 ;; The t causes an error if the cell has references. If no
2310 ;; references, the t will be the result value.
2311 (1value (ses-formula-references (ses-cell-formula row col) t))
2312 (setf (ses-cell-property :ses-Dijkstra-attempt row col)
2313 (cons ses--Dijkstra-attempt-nb 0))
2314 (when (setq sig (ses-calculate-cell row col t))
2315 (nconc sig (list (ses-cell-symbol row col)))))
2316 (wrong-type-argument
2317 ;; The formula contains a reference.
2318 (cl-pushnew (ses-cell-symbol row col) ses--deferred-recalc
2320 ;; Do the update now, so we can force recalculation.
2321 (let ((x ses--deferred-recalc))
2322 (setq ses--deferred-recalc nil)
2323 (condition-case hold
2324 (ses-update-cells x t)
2325 (error (setq sig hold))))
2328 (message "%s" (error-message-string sig)))
2329 ((consp ses--curcell)
2332 (princ (symbol-value ses--curcell))))))
2334 (defun ses-recalculate-all ()
2335 "Recalculate and reprint all cells."
2337 (let ((startcell (ses--cell-at-pos (point)))
2338 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2339 (1- ses--numcols)))))
2340 (ses-recalculate-cell ses--curcell)
2341 (ses-jump-safe startcell)))
2343 (defun ses-truncate-cell ()
2344 "Reprint current cell, but without spillover into any following blank cells."
2347 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2350 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
2351 (eq (ses-cell-value row (1+ col)) '*skip*))
2352 ;; This cell has spill-over. We'll momentarily pretend the following cell
2355 (list (ses-cell-symbol row (1+ col)))
2357 (ses-print-cell row col))
2358 ;; Now remove the *skip*. ses-print-cell is always nil here.
2359 (ses-set-cell row (1+ col) 'value nil)
2360 (1value (ses-print-cell row (1+ col))))))
2362 (defun ses-reconstruct-all ()
2363 "Reconstruct buffer based on cell data stored in Emacs variables."
2366 ;;Reconstruct reference lists.
2368 ;;Delete old reference lists
2369 (dotimes-with-progress-reporter
2370 (row ses--numrows) "Deleting references..."
2371 (dotimes (col ses--numcols)
2372 (ses-set-cell row col 'references nil)))
2373 ;;Create new reference lists
2374 (dotimes-with-progress-reporter
2375 (row ses--numrows) "Computing references..."
2376 (dotimes (col ses--numcols)
2377 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2378 (setq x (ses-sym-rowcol ref)
2381 (ses-set-cell yrow ycol 'references
2382 (cons (ses-cell-symbol row col)
2383 (ses-cell-references yrow ycol)))))))
2384 ;; Delete everything and reconstruct basic data area.
2386 (let ((inhibit-read-only t))
2387 (goto-char (point-max))
2388 (if (search-backward ";; Local Variables:\n" nil t)
2389 (delete-region (point-min) (point))
2390 ;; Buffer is quite screwed up --- can't even save the user-specified
2392 (delete-region (point-min) (point-max))
2393 (insert ses-initial-file-trailer)
2394 (goto-char (point-min)))
2395 ;; Create a blank display area.
2396 (dotimes (_ ses--numrows)
2397 (insert ses--blank-line))
2398 (insert ses-print-data-boundary)
2399 (backward-char (1- (length ses-print-data-boundary)))
2400 (setq ses--data-marker (point-marker))
2401 (forward-char (1- (length ses-print-data-boundary)))
2402 ;; Placeholders for cell data.
2403 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2404 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
2406 (insert ses-initial-global-parameters)
2407 (backward-char (1- (length ses-initial-global-parameters)))
2408 (setq ses--params-marker (point-marker))
2409 (forward-char (1- (length ses-initial-global-parameters))))
2410 (ses-set-parameter 'ses--col-widths ses--col-widths)
2411 (ses-set-parameter 'ses--col-printers ses--col-printers)
2412 (ses-set-parameter 'ses--default-printer ses--default-printer)
2413 (ses-set-parameter 'ses--header-row ses--header-row)
2414 (ses-set-parameter 'ses--numrows ses--numrows)
2415 (ses-set-parameter 'ses--numcols ses--numcols)
2416 ;;Keep our old narrowing
2418 (ses-recalculate-all)
2419 (goto-char (point-min)))
2422 ;;----------------------------------------------------------------------------
2423 ;; Input of cell formulas
2424 ;;----------------------------------------------------------------------------
2426 (defun ses-edit-cell (row col newval)
2427 "Display current cell contents in minibuffer, for editing. Returns nil if
2428 cell formula was unsafe and user declined confirmation."
2431 (barf-if-buffer-read-only)
2433 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2436 (formula (ses-cell-formula row col))
2438 (if (eq (car-safe formula) 'ses-safe-formula)
2439 (setq formula (cadr formula)))
2440 (if (eq (car-safe formula) 'quote)
2441 (setq initial (format "'%S" (cadr formula)))
2442 (setq initial (prin1-to-string formula)))
2443 (if (stringp formula)
2444 ;; Position cursor inside close-quote.
2445 (setq initial (cons initial (length initial))))
2447 (read-from-minibuffer (format "Cell %s: " ses--curcell)
2450 t ; Convert to Lisp object.
2451 'ses-read-cell-history)))))
2452 (when (ses-warn-unsafe newval 'unsafep)
2454 (ses-cell-set-formula row col newval)
2457 (defun ses-read-cell (row col newval)
2458 "Self-insert for initial character of cell function."
2460 (let* ((initial (this-command-keys))
2461 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2462 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
2463 (barf-if-buffer-read-only)
2466 (if (equal initial "\"")
2468 (if (not (stringp curval)) (setq curval nil))
2469 (read-string (if curval
2470 (format "String Cell %s (default %s): "
2471 ses--curcell curval)
2472 (format "String Cell %s: " ses--curcell))
2473 nil 'ses-read-string-history curval))
2474 (read-from-minibuffer
2475 (format "Cell %s: " ses--curcell)
2476 (cons (if (equal initial "(") "()" initial) 2)
2478 t ; Convert to Lisp object.
2479 'ses-read-cell-history
2480 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2483 (when (ses-edit-cell row col newval)
2484 (ses-command-hook) ; Update cell widths before movement.
2485 (dolist (x ses-after-entry-functions)
2488 (defun ses-read-symbol (row col symb)
2489 "Self-insert for a symbol as a cell formula. The set of all symbols that
2490 have been used as formulas in this spreadsheet is available for completions."
2492 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2494 (barf-if-buffer-read-only)
2495 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2496 ses--symbolic-formulas))
2499 (if (string= newval "")
2500 nil ; Don't create zero-length symbols!
2501 (list 'quote (intern newval))))))
2502 (when (ses-edit-cell row col symb)
2503 (ses-command-hook) ; Update cell widths before movement.
2504 (dolist (x ses-after-entry-functions)
2507 (defun ses-clear-cell-forward (count)
2508 "Delete formula and printer for current cell and then move to next cell.
2509 With prefix, deletes several cells."
2512 (1value (ses-clear-cell-backward (- count)))
2517 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2518 (or rowcol (signal 'end-of-buffer nil))
2519 (ses-clear-cell (car rowcol) (cdr rowcol)))
2522 (defun ses-clear-cell-backward (count)
2523 "Move to previous cell and then delete it. With prefix, deletes several
2527 (1value (ses-clear-cell-forward (- count)))
2528 (ses-check-curcell 'end)
2531 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
2533 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2534 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2537 ;;----------------------------------------------------------------------------
2538 ;; Input of cell-printer functions
2539 ;;----------------------------------------------------------------------------
2541 (defun ses-read-printer (prompt default)
2542 "Common code for functions `ses-read-cell-printer', `ses-read-column-printer',
2543 `ses-read-default-printer' and `ses-define-local-printer'.
2544 PROMPT should end with \": \". Result is t if operation was
2546 (barf-if-buffer-read-only)
2549 (setq prompt (format "%s (default %S): "
2550 (substring prompt 0 -2)
2552 (let ((new (read-from-minibuffer prompt
2553 nil ; Initial contents.
2555 t ; Evaluate the result.
2556 'ses-read-printer-history
2557 (prin1-to-string default))))
2558 (if (equal new default)
2559 ;; User changed mind, decided not to change printer.
2561 (ses-printer-validate new)
2564 (stringp (car-safe new))
2565 (and (symbolp new) (gethash new ses--local-printer-hashmap))
2566 (ses-warn-unsafe new 'unsafep-function)
2570 (defun ses-read-cell-printer (newval)
2571 "Set the printer function for the current cell or range.
2573 A printer function is either a string (a format control-string with one
2574 %-sequence -- result from format will be right-justified), or a list of one
2575 string (result from format will be left-justified), or a lambda-expression of
2576 one argument, or a symbol that names a function of one argument. In the
2577 latter two cases, the function's result should be either a string (will be
2578 right-justified) or a list of one string (will be left-justified)."
2581 (ses-check-curcell 'range)
2582 ;;Default is none if not all cells in range have same printer
2583 (catch 'ses-read-cell-printer
2584 (ses-dorange ses--curcell
2585 (let ((x (ses-cell-printer row col)))
2586 (if (eq (car-safe x) 'ses-safe-printer)
2590 (unless (equal default x)
2591 ;;Range contains differing printer functions
2593 (throw 'ses-read-cell-printer t))))))
2594 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2596 (unless (eq newval t)
2598 (ses-dorange ses--curcell
2599 (ses-set-cell row col 'printer newval)
2600 (ses-print-cell row col))))
2602 (defun ses-read-column-printer (col newval)
2603 "Set the printer function for the current column.
2604 See `ses-read-cell-printer' for input forms."
2606 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2608 (list col (ses-read-printer (format "Column %s printer: "
2609 (ses-column-letter col))
2610 (ses-col-printer col)))))
2612 (unless (eq newval t)
2614 (ses-set-parameter 'ses--col-printers newval col)
2616 (dotimes (row ses--numrows)
2617 (ses-print-cell row col)))))
2619 (defun ses-read-default-printer (newval)
2620 "Set the default printer function for cells that have no other.
2621 See `ses-read-cell-printer' for input forms."
2623 (list (ses-read-printer "Default printer: " ses--default-printer)))
2624 (unless (eq newval t)
2626 (ses-set-parameter 'ses--default-printer newval)
2627 (ses-reprint-all t)))
2630 ;;----------------------------------------------------------------------------
2631 ;; Spreadsheet size adjustments
2632 ;;----------------------------------------------------------------------------
2634 (defun ses-insert-row (count)
2635 "Insert a new row before the current one.
2636 With prefix, insert COUNT rows before current one."
2638 (ses-check-curcell 'end)
2639 (or (> count 0) (signal 'args-out-of-range nil))
2641 (let ((inhibit-quit t)
2642 (inhibit-read-only t)
2643 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2645 ;;Create a new set of cell-variables
2646 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2647 0 (1- ses--numcols))
2648 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2650 (ses-goto-print row 0)
2651 (dotimes-with-progress-reporter (x count) "Inserting row..."
2652 ;;Create a row of empty cells. The `symbol' fields will be set by
2653 ;;the call to ses-relocate-all.
2654 (setq newrow (make-vector ses--numcols nil))
2655 (dotimes (col ses--numcols)
2656 (aset newrow col (ses-make-cell)))
2657 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2658 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2659 (insert ses--blank-line))
2660 ;;Insert empty lines in cell data area (will be replaced by
2662 (ses-goto-data row 0)
2663 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2664 (ses-relocate-all row 0 count 0)
2665 ;;If any cell printers insert constant text, insert that text
2667 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2668 (global (ses-call-printer ses--default-printer)))
2669 (if (or (> (length cols) 0) (> (length global) 0))
2671 (dotimes (col ses--numcols)
2672 ;;These cells are always nil, only constant formatting printed
2673 (1value (ses-print-cell (+ x row) col))))))
2674 (when (> ses--header-row row)
2675 ;;Inserting before header
2676 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2677 (ses-reset-header-string)))
2678 ;;Reconstruct text attributes
2681 (push '(apply ses-widen) buffer-undo-list)
2682 ;;Return to current cell
2684 (ses-jump-safe ses--curcell)
2685 (ses-goto-print (1- ses--numrows) 0)))
2687 (defun ses-delete-row (count)
2688 "Delete the current row.
2689 With prefix, deletes COUNT rows starting from the current one."
2692 (or (> count 0) (signal 'args-out-of-range nil))
2693 (let ((inhibit-quit t)
2694 (inhibit-read-only t)
2695 (row (car (ses-sym-rowcol ses--curcell))))
2696 (setq count (min count (- ses--numrows row)))
2698 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2699 ;;Delete lines from print area
2700 (ses-goto-print row 0)
2701 (ses-delete-line count)
2702 ;;Delete lines from cell data area
2703 (ses-goto-data row 0)
2704 (ses-delete-line (* count (1+ ses--numcols)))
2705 ;; Collect named cells in the deleted rows, in order to clean the
2706 ;; symbols out of the named cell hash map, once the deletion is
2708 (unless (null ses--in-killing-named-cell-list)
2709 (warn "Internal error, `ses--in-killing-named-cell-list' should be nil, but is equal to %S"
2710 ses--in-killing-named-cell-list)
2711 (setq ses--in-killing-named-cell-list nil))
2712 (dotimes-with-progress-reporter (nrow count)
2713 "Collecting named cell in deleted rows..."
2714 (dotimes (col ses--numcols)
2715 (let* ((row (+ row nrow))
2716 (sym (ses-cell-symbol row col)))
2717 (and (eq (get sym 'ses-cell) :ses-named)
2718 (push sym ses--in-killing-named-cell-list)))))
2719 ;;Relocate variables and formulas
2720 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2721 (ses-relocate-all row 0 (- count) 0)
2722 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2723 0 (1- ses--numcols))
2724 (when (> ses--header-row row)
2725 (if (<= ses--header-row (+ row count))
2726 ;;Deleting the header row
2727 (ses-set-parameter 'ses--header-row 0)
2728 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2729 (ses-reset-header-string)))
2730 ;;Reconstruct attributes
2733 (push '(apply ses-widen) buffer-undo-list)
2734 (ses-jump-safe ses--curcell))
2736 (defun ses-insert-column (count &optional col width printer)
2737 "Insert a new column before COL (default is the current one).
2738 With prefix, insert COUNT columns before current one.
2739 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2740 \(otherwise they're taken from the current column)."
2743 (or (> count 0) (signal 'args-out-of-range nil))
2745 (setq col (cdr (ses-sym-rowcol ses--curcell))
2746 width (ses-col-width col)
2747 printer (ses-col-printer col)))
2749 (let ((inhibit-quit t)
2750 (inhibit-read-only t)
2751 (widths ses--col-widths)
2752 (printers ses--col-printers)
2754 ;;Create a new set of cell-variables
2755 (ses-create-cell-variable-range 0 (1- ses--numrows)
2756 ses--numcols (+ ses--numcols count -1))
2757 ;;Insert each column.
2758 (dotimes-with-progress-reporter (x count) "Inserting column..."
2759 ;;Create a column of empty cells. The `symbol' fields will be set by
2760 ;;the call to ses-relocate-all.
2761 (ses-adjust-print-width col (1+ width))
2762 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2763 (dotimes (row ses--numrows)
2764 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2765 ;;Inserting in the middle of a spill-over
2767 (ses-aset-with-undo ses--cells row
2768 (ses-vector-insert (aref ses--cells row)
2769 col (ses-make-cell)))
2770 ;;Insert empty lines in cell data area (will be replaced by
2772 (ses-goto-data row col)
2774 ;; Insert column width and printer.
2775 (setq widths (ses-vector-insert widths col width)
2776 printers (ses-vector-insert printers col printer)))
2777 (ses-set-parameter 'ses--col-widths widths)
2778 (ses-set-parameter 'ses--col-printers printers)
2779 (ses-reset-header-string)
2780 (ses-relocate-all 0 col 0 count)
2783 (when (or (> (length (ses-call-printer printer)) 0)
2784 (> (length (ses-call-printer ses--default-printer)) 0))
2785 ;; Either column printer or global printer inserts some constant text.
2786 ;; Reprint the new columns to insert that text.
2787 (dotimes (x ses--numrows)
2789 ;; Always nil here --- this is a blank column.
2790 (1value (ses-print-cell-new-width x (+ y col))))))
2792 (ses-jump-safe ses--curcell))
2794 (defun ses-delete-column (count)
2795 "Delete the current column.
2796 With prefix, deletes COUNT columns starting from the current one."
2799 (or (> count 0) (signal 'args-out-of-range nil))
2800 (let ((inhibit-quit t)
2801 (inhibit-read-only t)
2802 (rowcol (ses-sym-rowcol ses--curcell))
2804 col origrow has-skip)
2805 (setq origrow (car rowcol)
2807 count (min count (- ses--numcols col)))
2808 (if (= count ses--numcols)
2809 (error "Can't delete all columns!"))
2810 ;;Determine width of column(s) being deleted
2812 (setq width (+ width (ses-col-width (+ col x)) 1)))
2814 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2815 (ses-adjust-print-width col (- width))
2816 ;; Prepare collecting named cells in the deleted columns, in order
2817 ;; to clean the symbols out of the named cell hash map, once the
2818 ;; deletion is complete
2819 (unless (null ses--in-killing-named-cell-list)
2820 (warn "Internal error, `ses--in-killing-named-cell-list' should be nil, but is equal to %S"
2821 ses--in-killing-named-cell-list)
2822 (setq ses--in-killing-named-cell-list nil))
2823 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2824 ;;Delete lines from cell data area
2825 (ses-goto-data row col)
2826 (ses-delete-line count)
2827 ;; Collect named cells in the deleted columns within this row
2828 (dotimes (ncol count)
2829 (let ((sym (ses-cell-symbol row (+ col ncol))))
2830 (and (eq (get sym 'ses-cell) :ses-named)
2831 (push sym ses--in-killing-named-cell-list))))
2832 ;;Delete cells. Check if deletion area begins or ends with a skip.
2833 (if (or (eq (ses-cell-value row col) '*skip*)
2834 (and (< col ses--numcols)
2835 (eq (ses-cell-value row (+ col count)) '*skip*)))
2837 (ses-aset-with-undo ses--cells row
2838 (ses-vector-delete (aref ses--cells row) col count)))
2840 (ses-set-parameter 'ses--col-widths
2841 (ses-vector-delete ses--col-widths col count))
2842 (ses-set-parameter 'ses--col-printers
2843 (ses-vector-delete ses--col-printers col count))
2844 (ses-reset-header-string)
2845 ;;Relocate variables and formulas
2846 (ses-relocate-all 0 col 0 (- count))
2847 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2848 ses--numcols (+ ses--numcols count -1))
2852 (if (>= col ses--numcols)
2853 (setq col (1- col)))
2854 (ses-goto-print origrow col)))
2856 (defun ses-forward-or-insert (&optional count)
2857 "Move to next cell in row, or inserts a new cell if already in last one, or
2858 inserts a new row if at bottom of print area. Repeat COUNT times."
2860 (ses-check-curcell 'end)
2861 (setq deactivate-mark t) ; Doesn't combine well with ranges.
2864 (if (not ses--curcell)
2865 (progn ; At bottom of print area.
2866 (barf-if-buffer-read-only)
2868 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2870 (char-before (next-single-property-change (point)
2871 'cursor-intangible)))
2872 ;; We're already in last nonskipped cell on line. Need to create a
2874 (barf-if-buffer-read-only)
2875 (ses-insert-column (- count x)
2878 (ses-col-printer col)))))
2881 (defun ses-append-row-jump-first-column ()
2882 "Insert a new row after current one and jump to its first column."
2886 (beginning-of-line 2)
2890 (defun ses-set-column-width (col newwidth)
2891 "Set the width of the current column."
2893 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2894 (barf-if-buffer-read-only)
2896 (if current-prefix-arg
2897 (prefix-numeric-value current-prefix-arg)
2898 (read-from-minibuffer (format "Column %s width (default %d): "
2899 (ses-column-letter col)
2900 (ses-col-width col))
2901 nil ; No initial contents.
2902 nil ; No override keymap.
2903 t ; Convert to Lisp object.
2906 (ses-col-width col))))))) ; Default value.
2908 (error "Invalid column width"))
2910 (ses-reset-header-string)
2912 (let ((inhibit-quit t))
2913 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2914 (ses-set-parameter 'ses--col-widths newwidth col))
2915 (dotimes (row ses--numrows)
2916 (ses-print-cell-new-width row col))))
2919 ;;----------------------------------------------------------------------------
2920 ;; Cut and paste, import and export
2921 ;;----------------------------------------------------------------------------
2923 (defun ses--advice-copy-region-as-kill (crak-fun beg end &rest args)
2924 ;; FIXME: Why doesn't it make sense to copy read-only or
2925 ;; intangible attributes? They're removed upon yank!
2926 "It doesn't make sense to copy read-only or intangible attributes into the
2927 kill ring. It probably doesn't make sense to copy keymap properties.
2928 We'll assume copying front-sticky properties doesn't make sense, either.
2930 This advice also includes some SES-specific code because otherwise it's too
2931 hard to override how mouse-1 works."
2936 (if (not (and (derived-mode-p 'ses-mode)
2937 (eq (get-text-property beg 'read-only) 'ses)
2938 (eq (get-text-property (1- end) 'read-only) 'ses)))
2939 (apply crak-fun beg end args) ; Normal copy-region-as-kill.
2940 (kill-new (ses-copy-region beg end))
2941 (if transient-mark-mode
2942 (setq deactivate-mark t))
2944 (advice-add 'copy-region-as-kill :around #'ses--advice-copy-region-as-kill)
2946 (defun ses-copy-region (beg end)
2947 "Treat the region as rectangular. Convert the intangible attributes to
2948 SES attributes recording the contents of the cell as of the time of copying."
2949 (when (= end ses--data-marker)
2950 ;;Avoid overflow situation
2951 (setq end (1- ses--data-marker)))
2952 (let* ((x (mapconcat #'ses-copy-region-helper
2953 (extract-rectangle beg (1- end)) "\n")))
2954 (remove-text-properties 0 (length x)
2962 (defun ses-copy-region-helper (line)
2963 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2964 external form by attaching to each print cell a `ses' attribute that records
2965 the corresponding data cell."
2966 (or (> (length line) 1)
2967 (error "Empty range"))
2968 (let ((inhibit-read-only t)
2970 mycell next sym rowcol)
2972 (setq sym (ses--cell-at-pos pos line)
2973 next (next-single-property-change pos 'cursor-intangible line)
2974 rowcol (ses-sym-rowcol sym)
2975 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2976 (put-text-property pos (or next (length line))
2978 (list (ses-cell-symbol mycell)
2979 (ses-cell-formula mycell)
2980 (ses-cell-printer mycell))
2985 (defun ses-kill-override (beg end)
2986 "Generic override for any commands that kill text.
2987 We clear the killed cells instead of deleting them."
2989 (ses-check-curcell 'needrange)
2990 ;; For some reason, the text-read-only error is not caught by `delete-region',
2991 ;; so we have to use subterfuge.
2992 (let ((buffer-read-only t))
2993 (1value (condition-case nil
2994 (noreturn (funcall (lookup-key (current-global-map)
2995 (this-command-keys))
2997 (buffer-read-only nil)))) ; The expected error.
2998 ;; Because the buffer was marked read-only, the kill command turned itself
2999 ;; into a copy. Now we clear the cells or signal the error. First we check
3000 ;; whether the buffer really is read-only.
3001 (barf-if-buffer-read-only)
3003 (ses-dorange ses--curcell
3004 (ses-clear-cell row col))
3005 (ses-jump (car ses--curcell)))
3007 (defun ses--advice-yank (yank-fun &optional arg &rest args)
3008 "In SES mode, the yanked text is inserted as cells.
3010 If the text contains `ses' attributes (meaning it went to the kill-ring from a
3011 SES buffer), the formulas and print functions are restored for the cells. If
3012 the text contains tabs, this is an insertion of tab-separated formulas.
3013 Otherwise the text is inserted as the formula for the current cell.
3015 When inserting cells, the formulas are usually relocated to keep the same
3016 relative references to neighboring cells. This is best if the formulas
3017 generally refer to other cells within the yanked text. You can use the C-u
3018 prefix to specify insertion without relocation, which is best when the
3019 formulas refer to cells outside the yanked text.
3021 When inserting formulas, the text is treated as a string constant if it doesn't
3022 make sense as a sexp or would otherwise be considered a symbol. Use `sym' to
3023 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
3025 (if (not (and (derived-mode-p 'ses-mode)
3026 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
3027 (apply yank-fun arg args) ; Normal non-SES yank.
3028 (ses-check-curcell 'end)
3030 (let ((text (current-kill (cond
3034 (or (ses-yank-cells text arg)
3035 (ses-yank-tsf text arg)
3036 (ses-yank-one (ses-yank-resize 1 1)
3039 (if (memq (aref text (1- (length text))) '(?\t ?\n))
3040 ;; Just one cell --- delete final tab or newline.
3044 (exchange-point-and-mark))))
3045 (advice-add 'yank :around #'ses--advice-yank)
3047 (defun ses-yank-pop (arg)
3048 "Replace just-yanked stretch of killed text with a different stretch.
3049 This command is allowed only immediately after a `yank' or a `yank-pop',
3050 when the region contains a stretch of reinserted previously-killed text.
3051 We replace it with a different stretch of killed text.
3052 Unlike standard `yank-pop', this function uses `undo' to delete the
3053 previous insertion."
3055 (or (eq last-command 'yank)
3056 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
3058 (noreturn (error "Previous command was not a yank")))
3061 (yank (1+ (or arg 1)))
3062 (setq this-command 'yank))
3064 (defun ses-yank-cells (text arg)
3065 "If the TEXT has a proper set of `ses' attributes, insert the text as
3066 cells, else return nil. The cells are reprinted--the supplied text is
3067 ignored because the column widths, default printer, etc. at yank time might
3068 be different from those at kill-time. ARG is a list to indicate that
3069 formulas are to be inserted without relocation."
3070 (let ((first (get-text-property 0 'ses text))
3071 (last (get-text-property (1- (length text)) 'ses text)))
3072 (when (and first last) ;;Otherwise not proper set of attributes
3073 (setq first (ses-sym-rowcol (car first))
3074 last (ses-sym-rowcol (car last)))
3075 (let* ((needrows (- (car last) (car first) -1))
3076 (needcols (- (cdr last) (cdr first) -1))
3077 (rowcol (ses-yank-resize needrows needcols))
3078 (rowincr (- (car rowcol) (car first)))
3079 (colincr (- (cdr rowcol) (cdr first)))
3082 (dotimes-with-progress-reporter (row needrows) "Yanking..."
3083 (setq myrow (+ row (car rowcol)))
3084 (dotimes (col needcols)
3085 (setq mycol (+ col (cdr rowcol))
3086 last (get-text-property pos 'ses text)
3087 pos (next-single-property-change pos 'ses text)
3088 x (ses-sym-rowcol (car last)))
3090 ;; Newline --- all remaining cells on row are skipped.
3091 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
3092 last (list nil nil nil)
3094 (if (/= (car x) (- myrow rowincr))
3095 (error "Cell row error"))
3096 (if (< (- mycol colincr) (cdr x))
3097 ;; Some columns were skipped.
3098 (let ((oldcol mycol))
3099 (while (< (- mycol colincr) (cdr x))
3100 (ses-clear-cell myrow mycol)
3103 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
3104 (when (car last) ; Skip this for *skip* cells.
3105 (setq x (nth 2 last))
3106 (unless (equal x (ses-cell-printer myrow mycol))
3109 (eq (car-safe x) 'ses-safe-printer)
3110 (setq x `(ses-safe-printer ,x)))
3111 (ses-set-cell myrow mycol 'printer x))
3112 (setq x (cadr last))
3114 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
3116 (eq (car-safe x) 'ses-safe-formula)
3117 (setq x `(ses-safe-formula ,x)))
3118 (ses-cell-set-formula myrow mycol x)))
3120 (if (get-text-property pos 'ses text)
3121 (error "Missing newline between rows"))
3122 (setq pos (next-single-property-change pos 'ses text))))
3125 (defun ses-yank-one (rowcol text from to arg)
3126 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
3127 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
3128 (let ((val (condition-case nil
3129 (read-from-string text from to)
3130 (error (cons nil from)))))
3132 ((< (cdr val) (or to (length text)))
3133 ;; Invalid sexp --- leave it as a string.
3134 (setq val (substring text from to)))
3135 ((and (car val) (symbolp (car val)))
3136 (setq val (if (consp arg)
3137 (list 'quote (car val)) ; Keep symbol.
3138 (substring text from to)))) ; Treat symbol as text.
3140 (setq val (car val))))
3141 (let ((row (car rowcol))
3144 (setq val `(ses-safe-formula ,val)))
3145 (ses-cell-set-formula row col val))))
3147 (defun ses-yank-tsf (text arg)
3148 "If TEXT contains tabs and/or newlines, treat the tabs as
3149 column-separators and the newlines as row-separators and insert the text as
3150 cell formulas--else return nil. Treat plain symbols as strings unless ARG
3151 is a list. Ignore a final newline."
3152 (if (or (not (string-match "[\t\n]" text))
3153 (= (match-end 0) (length text)))
3156 (if (/= (aref text (1- (length text))) ?\n)
3157 (setq text (concat text "\n")))
3163 ;;Find all the tabs and newlines
3164 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
3166 (setq cols (1+ cols))
3167 (when (eq (aref text pos) ?\n)
3169 (setq needcols cols)
3170 (or (= needcols cols)
3171 (error "Inconsistent row lengths")))
3173 needrows (1+ needrows))))
3174 ;;Insert the formulas
3175 (setq rowcol (ses-yank-resize needrows needcols))
3176 (dotimes (row needrows)
3177 (dotimes (col needcols)
3178 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
3179 (+ (cdr rowcol) needcols (- col) -1))
3180 text (1+ (cadr spots)) (car spots) arg)
3181 (setq spots (cdr spots))))
3182 (ses-goto-print (+ (car rowcol) needrows -1)
3183 (+ (cdr rowcol) needcols -1))
3186 (defun ses-yank-resize (needrows needcols)
3187 "If this yank will require inserting rows and/or columns, ask for
3188 confirmation and then insert them. Result is (row,col) for top left of yank
3189 spot, or error signal if user requests cancel."
3191 (let ((rowcol (if ses--curcell
3192 (ses-sym-rowcol ses--curcell)
3193 (cons ses--numrows 0)))
3195 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
3196 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
3197 rowbool (> needrows 0)
3198 colbool (> needcols 0))
3199 (when (or rowbool colbool)
3200 ;;Need to insert. Get confirm
3201 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
3202 (if rowbool (format "%d rows" needrows) "")
3203 (if (and rowbool colbool) " and " "")
3204 (if colbool (format "%d columns" needcols) "")))
3209 (ses-goto-print ses--numrows 0)
3210 (ses-insert-row needrows))))
3212 (ses-insert-column needcols
3214 (ses-col-width (1- ses--numcols))
3215 (ses-col-printer (1- ses--numcols)))))
3218 (defun ses-export-tsv (_beg _end)
3219 "Export values from the current range, with tabs between columns and
3220 newlines between rows. Result is placed in kill ring."
3222 (ses-export-tab nil))
3224 (defun ses-export-tsf (_beg _end)
3225 "Export formulas from the current range, with tabs between columns and
3226 newlines between rows. Result is placed in kill ring."
3230 (defun ses-export-tab (want-formulas)
3231 "Export the current range with tabs between columns and newlines between rows.
3232 Result is placed in kill ring. The export is values unless WANT-FORMULAS
3233 is non-nil. Newlines and tabs in the export text are escaped."
3234 (ses-check-curcell 'needrange)
3235 (let ((print-escape-newlines t)
3237 (ses-dorange ses--curcell
3238 (setq item (if want-formulas
3239 (ses-cell-formula row col)
3240 (ses-cell-value row col)))
3241 (if (eq (car-safe item) 'ses-safe-formula)
3242 ;;Hide our deferred safety-check marker
3243 (setq item (cadr item)))
3244 (if (or (not item) (eq item '*skip*))
3246 (when (eq (car-safe item) 'quote)
3248 (setq item (cadr item)))
3249 (setq item (ses-prin1 item))
3250 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
3256 (push "\n" result))))
3257 (setq result (apply #'concat (nreverse result)))
3261 ;;----------------------------------------------------------------------------
3262 ;; Other user commands
3263 ;;----------------------------------------------------------------------------
3265 (defun ses-unset-header-row ()
3266 "Select the default header row."
3268 (ses-set-header-row 0))
3270 (defun ses-set-header-row (row)
3271 "Set the ROW to display in the header-line.
3272 With a numerical prefix arg, use that row.
3273 With no prefix arg, use the current row.
3274 With a \\[universal-argument] prefix arg, prompt the user.
3275 The top row is row 1. Selecting row 0 displays the default header row."
3277 (list (if (numberp current-prefix-arg) current-prefix-arg
3278 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3279 (if current-prefix-arg
3280 (read-number "Header row: " currow)
3282 (if (or (< row 0) (> row ses--numrows))
3283 (error "Invalid header-row"))
3285 (let ((oldval ses--header-row))
3286 (let (buffer-undo-list)
3287 (ses-set-parameter 'ses--header-row row))
3288 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
3289 (ses-reset-header-string))
3291 (defun ses-mark-row ()
3292 "Mark the entirety of current row as a range."
3294 (ses-check-curcell 'range)
3295 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
3297 (ses-goto-print (1+ row) 0)
3298 (push-mark (point) nil t)
3299 (ses-goto-print row 0)))
3301 (defun ses-mark-column ()
3302 "Mark the entirety of current column as a range."
3304 (ses-check-curcell 'range)
3305 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
3308 (ses-goto-print (1- ses--numrows) col)
3310 (push-mark (point) nil t)
3311 (while (eq '*skip* (ses-cell-value row col))
3312 ;;Skip over initial cells in column that can't be selected
3313 (setq row (1+ row)))
3314 (ses-goto-print row col)))
3316 (defun ses-end-of-line ()
3317 "Move point to last cell on line."
3319 (ses-check-curcell 'end 'range)
3320 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3322 (let ((col (1- ses--numcols))
3324 (if (symbolp ses--curcell)
3326 (setq row (car (ses-sym-rowcol ses--curcell)))
3327 ;; Range --- use whichever end of the range the point is at.
3328 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
3330 (cdr ses--curcell))))
3331 ;; If range already includes the last cell in a row, point is actually
3332 ;; in the following row.
3333 (if (<= (cdr rowcol) (1- col))
3334 (setq row (car rowcol))
3335 (setq row (1+ (car rowcol)))
3336 (if (= row ses--numrows)
3337 ;;Already at end - can't go anywhere
3339 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
3340 (while (eq (ses-cell-value row col) '*skip*)
3341 ;; Back to beginning of multi-column cell.
3342 (setq col (1- col)))
3343 (ses-goto-print row col)))))
3345 (defun ses-renarrow-buffer ()
3346 "Narrow the buffer so only the print area is visible.
3347 Use after \\[widen]."
3349 (setq ses--deferred-narrow t))
3351 (defun ses-sort-column (sorter &optional reverse)
3352 "Sort the range by a specified column.
3353 With prefix, sorts in REVERSE order."
3354 (interactive "*sSort column: \nP")
3355 (ses-check-curcell 'needrange)
3356 (let ((min (ses-sym-rowcol (car ses--curcell)))
3357 (max (ses-sym-rowcol (cdr ses--curcell))))
3358 (let ((minrow (car min))
3363 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3364 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3365 (error "Invalid sort column"))
3366 ;;Get key columns and sort them
3367 (dotimes (x (- maxrow minrow -1))
3368 (ses-goto-print (+ minrow x) sorter)
3369 (setq end (next-single-property-change (point) 'cursor-intangible))
3370 (push (cons (buffer-substring-no-properties (point) end)
3373 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3374 ;;Extract the lines in reverse sorted order
3376 (setq keys (nreverse keys)))
3378 (ses-goto-print (cdr x) (1+ maxcol))
3380 (ses-goto-print (cdr x) mincol)
3381 (push (ses-copy-region (point) end) extracts))
3383 ;;Paste the lines sequentially
3384 (dotimes (x (- maxrow minrow -1))
3385 (ses-goto-print (+ minrow x) mincol)
3387 (ses-yank-cells (pop extracts) nil)))))
3389 (defun ses-sort-column-click (event reverse)
3390 "Mouse version of `ses-sort-column'."
3391 (interactive "*e\nP")
3392 (setq event (event-end event))
3393 (select-window (posn-window event))
3394 (setq event (car (posn-col-row event))) ; Click column.
3396 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3397 (setq event (- event (ses-col-width col) 1)
3399 (if (>= col ses--numcols)
3401 (ses-sort-column (ses-column-letter col) reverse))))
3403 (defun ses-insert-range ()
3404 "Insert into minibuffer the list of cells currently highlighted in the
3408 (with-current-buffer (window-buffer minibuffer-scroll-window)
3409 (ses-command-hook) ; For ses-coverage.
3410 (ses-check-curcell 'needrange)
3411 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3412 ,(cdr ses--curcell))))))
3413 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3415 (defun ses-insert-ses-range ()
3416 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
3417 highlighted range in the spreadsheet."
3420 (with-current-buffer (window-buffer minibuffer-scroll-window)
3421 (ses-command-hook) ; For ses-coverage.
3422 (ses-check-curcell 'needrange)
3423 (setq x (format "(ses-range %S %S)"
3425 (cdr ses--curcell))))
3428 (defun ses-insert-range-click (event)
3429 "Mouse version of `ses-insert-range'."
3431 (mouse-set-point event)
3434 (defun ses-insert-ses-range-click (event)
3435 "Mouse version of `ses-insert-ses-range'."
3437 (mouse-set-point event)
3438 (ses-insert-ses-range))
3440 (defun ses-replace-name-in-formula (formula old-name new-name)
3441 (let ((new-formula formula))
3442 (unless (and (consp formula)
3443 (eq (car-safe formula) 'quote))
3445 (let ((elt (car-safe formula)))
3448 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3450 (eq (car-safe formula) old-name))
3451 (setcar formula new-name))))
3452 (setq formula (cdr formula))))
3455 (defun ses-rename-cell (new-name &optional cell)
3456 "Rename current cell."
3457 (interactive "*SEnter new name: ")
3459 (and (local-variable-p new-name)
3460 (ses-is-cell-sym-p new-name)
3461 (error "Already a cell name"))
3462 (and (boundp new-name)
3465 "`%S' is already bound outside this buffer, continue? "
3467 (error "Already a bound cell name")))
3469 (sym (if (ses-cell-p cell)
3470 (ses-cell-symbol cell)
3475 (rowcol (ses-sym-rowcol sym))
3478 new-rowcol old-name)
3479 (setq cell (or cell (ses-get-cell row col))
3480 old-name (ses-cell-symbol cell)
3481 new-rowcol (ses-decode-cell-symbol (symbol-name new-name)))
3482 ;; when ses-rename-cell is called interactively, then 'sym' is the
3483 ;; 'cursor-intangible' property of text at cursor position, while
3484 ;; 'old-name' is the symbol stored in array cell at coordinate
3485 ;; 'rowcol' corresponding to 'ses-cell' property of symbol
3486 ;; 'sym'. Both must be the same.
3487 (unless (eq sym old-name)
3488 (error "Spreadsheet is broken, both symbols %S and %S refering to cell (%d,%d)" sym old-name row col))
3490 ;; the new name is of A1 type, so we test that the coordinate
3491 ;; inferred from new name
3492 (if (equal new-rowcol rowcol)
3493 (put new-name 'ses-cell rowcol)
3494 (error "Not a valid name for this cell location"))
3495 (setq ses--named-cell-hashmap
3496 (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
3497 (put new-name 'ses-cell :ses-named)
3498 (puthash new-name rowcol ses--named-cell-hashmap))
3499 (push `(ses-rename-cell ,old-name ,cell) buffer-undo-list)
3500 ;; Replace name by new name in formula of cells refering to renamed cell.
3501 (dolist (ref (ses-cell-references cell))
3502 (let* ((x (ses-sym-rowcol ref))
3503 (xcell (ses-get-cell (car x) (cdr x))))
3504 (setf (ses-cell-formula xcell)
3505 (ses-replace-name-in-formula
3506 (ses-cell-formula xcell)
3509 ;; Replace name by new name in reference list of cells to which renamed
3511 (dolist (ref (ses-formula-references (ses-cell-formula cell)))
3512 (let* ((x (ses-sym-rowcol ref))
3513 (xcell (ses-get-cell (car x) (cdr x))))
3514 (setf (ses-cell-references xcell)
3515 (cons new-name (delq old-name
3516 (ses-cell-references xcell))))))
3517 (set (make-local-variable new-name) (symbol-value sym))
3518 (setf (ses-cell--symbol cell) new-name)
3520 (if (eq (get old-name 'ses-cell) :ses-named)
3521 (ses--unbind-cell-name old-name)
3522 (kill-local-variable old-name))
3523 (and curcell (setq ses--curcell new-name))
3525 (or curcell (ses-goto-print row col))
3526 (let* ((pos (point))
3527 (inhibit-read-only t)
3528 (end (next-single-property-change pos 'cursor-intangible)))
3529 (put-text-property pos end 'cursor-intangible new-name)))
3530 ;; Update the cell name in the mode-line.
3531 (force-mode-line-update)))
3533 (defun ses-refresh-local-printer (name _compiled-value) ;FIXME: unused arg?
3534 "Refresh printout for all cells which use printer NAME.
3535 NAME should be the name of a locally defined printer.
3536 Uses the value COMPILED-VALUE for this printer."
3537 (message "Refreshing cells using printer %S" name)
3539 (dotimes (row ses--numrows)
3540 (dotimes (col ses--numcols)
3541 (let ((cell-printer (ses-cell-printer row col)))
3542 (when (eq cell-printer name)
3546 (ses-print-cell row col)))))))
3549 (defun ses-define-local-printer (name definition)
3550 "Define a local printer with name NAME and definition DEFINITION.
3552 NAME shall be a symbol. Use TAB to complete over existing local
3555 DEFINITION shall be either a string formatter, e.g.:
3557 \"%.2f\" or (\"%.2f\") for left alignment.
3559 or a lambda expression, e.g. for formatting in ISO format dates
3560 created with a '(calcFunc-date YEAR MONTH DAY)' formula:
3565 ((eq (car-safe x) 'date)
3566 (let ((calc-format-date '(X YYYY \"-\" MM \"-\" DD)))
3567 (math-format-date x)))
3568 (t (ses-center-span val ?# 'ses-prin1))))
3570 If NAME is already used to name a local printer function, then
3571 the current definition is proposed as default value, and the
3572 function is redefined."
3574 (let (name def already-defined-names)
3575 (maphash (lambda (key val) (push (symbol-name key) already-defined-names))
3576 ses--local-printer-hashmap)
3577 (setq name (completing-read "Enter printer name: " already-defined-names))
3578 (when (string= name "")
3579 (error "Invalid printer name"))
3580 (setq name (intern name))
3581 (let* ((cur-printer (gethash name ses--local-printer-hashmap))
3582 (default (and cur-printer (ses--locprn-def cur-printer))))
3583 (setq def (ses-read-printer (format "Enter definition of printer %S: " name)
3587 (let* ((cur-printer (gethash name ses--local-printer-hashmap))
3588 (default (and cur-printer (ses--locprn-def cur-printer)))
3591 ;; cancelled operation => do nothing
3593 ;; no change => do nothing
3594 ((and cur-printer (equal definition default)))
3595 ;; re-defined printer
3597 (setq create-printer 0)
3598 (setf (ses--locprn-def cur-printer) definition)
3599 (ses-refresh-local-printer
3601 (setf (ses--locprn-compiled cur-printer)
3602 (ses-local-printer-compile definition))))
3605 (setq create-printer 1)
3608 (ses-make-local-printer-info definition))
3609 ses--local-printer-hashmap)))
3610 (when create-printer
3611 (let ((printer-def-text
3613 "(ses-local-printer "
3616 (prin1-to-string (ses--locprn-def cur-printer))
3619 (ses-goto-data ses--numrows
3620 (ses--locprn-number cur-printer))
3621 (let ((inhibit-read-only t))
3622 ;; Special undo since it's outside the narrowed buffer.
3623 (let (buffer-undo-list)
3624 (if (= create-printer 0)
3625 (delete-region (point) (line-end-position))
3628 (insert printer-def-text)
3629 (when (= create-printer 1)
3630 (ses-file-format-extend-parameter-list 3)
3631 (ses-set-parameter 'ses--numlocprn
3632 (1+ ses--numlocprn))))))))))
3634 (defsubst ses-define-if-new-local-printer (name def)
3635 "Same as function `ses-define-if-new-local-printer', except
3636 that the definition occurs only when the local printer does not
3639 Function `ses-define-if-new-local-printer' is not interactive; it
3640 is intended for mode hooks to add local printers automatically."
3641 (unless (gethash name ses--local-printer-hashmap)
3642 (ses-define-local-printer name def)))
3644 ;;----------------------------------------------------------------------------
3645 ;; Checking formulas for safety
3646 ;;----------------------------------------------------------------------------
3648 (defun ses-safe-printer (printer)
3649 "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
3650 (if (or (stringp printer)
3651 (stringp (car-safe printer))
3653 (and (symbolp printer) (gethash printer ses--local-printer-hashmap))
3654 (ses-warn-unsafe printer 'unsafep-function))
3658 (defun ses-safe-formula (formula)
3659 "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
3660 (if (ses-warn-unsafe formula 'unsafep)
3662 `(ses-unsafe ',formula)))
3664 (defun ses-warn-unsafe (formula checker)
3665 "Apply CHECKER to FORMULA.
3666 If result is non-nil, asks user for confirmation about FORMULA,
3667 which might be unsafe. Returns t if formula is safe or user allows
3668 execution anyway. Always returns t if `safe-functions' is t."
3669 (if (eq safe-functions t)
3671 (setq checker (funcall checker formula))
3674 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3675 formula checker)))))
3678 ;;----------------------------------------------------------------------------
3679 ;; Standard formulas
3680 ;;----------------------------------------------------------------------------
3682 (defun ses--clean-! (&rest x)
3683 "Clean by `delq' list X from any occurrence of nil or `*skip*'."
3684 (delq nil (delq '*skip* x)))
3686 (defun ses--clean-_ (x y)
3687 "Clean list X by replacing by Y any occurrence of nil or `*skip*'.
3689 This will change X by making `setcar' on its cons cells."
3690 (let ((ret x) ret-elt)
3692 (setq ret-elt (car ret))
3693 (when (memq ret-elt '(nil *skip*))
3695 (setq ret (cdr ret))))
3698 (defmacro ses-range (from to &rest rest)
3699 "Expand to a list of cell-symbols for the range going from
3700 FROM up to TO. The range automatically expands to include any
3701 new row or column inserted into its middle. The SES library code
3702 specifically looks for the symbol `ses-range', so don't create an
3703 alias for this macro!
3705 By passing in REST some flags one can configure the way the range
3706 is read and how it is formatted.
3708 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3711 Readout direction is specified by a `>v', `>^', `<v', `<^',
3712 `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3713 of such a flag, a default direction of `^<' is assumed. This
3714 way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3715 while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3717 If the range is one row, then `>' can be used as a shorthand to
3718 `>v' or `>^', and `<' to `<v' or `<^'.
3720 If the range is one column, then `v' can be used as a shorthand to
3721 `v>' or `v<', and `^' to `^>' or `v<'.
3723 A `!' flag will remove all cells whose value is nil or `*skip*'.
3725 A `_' flag will replace nil or `*skip*' by the value following
3726 the `_' flag. If the `_' flag is the last argument, then they are
3727 replaced by integer 0.
3729 A `*', `*1' or `*2' flag will vectorize the range in the sense of
3730 Calc. See info node `(Calc) Top'. Flag `*' will output either a
3731 vector or a matrix depending on the number of rows, `*1' will
3732 flatten the result to a one row vector, and `*2' will make a
3733 matrix whatever the number of rows.
3735 Warning: interaction with Calc is experimental and may produce
3736 confusing results if you are not aware of Calc data format.
3737 Use `math-format-value' as a printer for Calc objects."
3745 (ses-dorange (cons from to)
3746 (when (/= prev-row row)
3747 (push result-row result)
3748 (setq result-row nil))
3749 (push (ses-cell-symbol row col) result-row)
3750 (setq prev-row row))
3751 (push result-row result)
3753 (let ((x (pop rest)))
3755 (`>v (setq transpose nil reorient-x nil reorient-y nil))
3756 (`>^ (setq transpose nil reorient-x nil reorient-y t))
3757 (`<^ (setq transpose nil reorient-x t reorient-y t))
3758 (`<v (setq transpose nil reorient-x t reorient-y nil))
3759 (`v> (setq transpose t reorient-x nil reorient-y t))
3760 (`^> (setq transpose t reorient-x nil reorient-y nil))
3761 (`^< (setq transpose t reorient-x t reorient-y nil))
3762 (`v< (setq transpose t reorient-x t reorient-y t))
3763 ((or `* `*2 `*1) (setq vectorize x))
3764 (`! (setq clean 'ses--clean-!))
3765 (`_ (setq clean `(lambda (&rest x)
3766 (ses--clean-_ x ,(if rest (pop rest) 0)))))
3769 ; shorthands one row
3770 ((and (null (cddr result)) (memq x '(> <)))
3771 (push (intern (concat (symbol-name x) "v")) rest))
3772 ; shorthands one col
3773 ((and (null (cdar result)) (memq x '(v ^)))
3774 (push (intern (concat (symbol-name x) ">")) rest))
3775 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3777 (setcdr (last result 2) nil)
3778 (setq result (cdr (nreverse result))))
3780 (setq result (mapcar #'nreverse result)))
3782 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3785 (dolist (elt (pop result))
3786 (setcar iter (cons elt (car iter)))
3787 (setq iter (cdr iter))))
3790 (cl-flet ((vectorize-*1
3792 (cons clean (cons (quote 'vec) (apply #'append result))))
3795 (cons clean (cons (quote 'vec)
3797 (cons clean (cons (quote 'vec) x)))
3800 (`nil (cons clean (apply #'append result)))
3801 (`*1 (vectorize-*1 clean result))
3802 (`*2 (vectorize-*2 clean result))
3803 (`* (funcall (if (cdr result)
3808 (defun ses-delete-blanks (&rest args)
3809 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3812 (unless (memq cur '(nil *skip*))
3816 (defun ses+ (&rest args)
3817 "Compute the sum of the arguments, ignoring blanks."
3818 (apply #'+ (apply #'ses-delete-blanks args)))
3820 (defun ses-average (list)
3821 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3822 are ignored. Result is always floating-point, even if all args are integers."
3823 (setq list (apply #'ses-delete-blanks list))
3824 (/ (float (apply #'+ list)) (length list)))
3826 (defmacro ses-select (fromrange test torange)
3827 "Select cells in FROMRANGE that are `equal' to TEST.
3828 For each match, return the corresponding cell from TORANGE.
3829 The ranges are macroexpanded but not evaluated so they should be
3830 either (ses-range BEG END) or (list ...). The TEST is evaluated."
3831 (setq fromrange (cdr (macroexpand fromrange))
3832 torange (cdr (macroexpand torange))
3834 (or (= (length fromrange) (length torange))
3835 (error "ses-select: Ranges not same length"))
3837 (dolist (x fromrange)
3838 (if (equal test (symbol-value x))
3839 (push (car torange) result))
3840 (setq torange (cdr torange)))
3841 (cons 'list result)))
3843 ;;All standard formulas are safe
3844 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3846 (put x 'side-effect-free t))
3849 ;;----------------------------------------------------------------------------
3850 ;; Standard print functions
3851 ;;----------------------------------------------------------------------------
3853 (defun ses-center (value &optional span fill printer)
3854 "Print VALUE, centered within column.
3855 FILL is the fill character for centering (default = space).
3856 SPAN indicates how many additional rightward columns to include
3857 in width (default = 0).
3858 PRINTER is the printer to use for printing the value, default is the
3859 column printer if any, or the spreadsheet the spreadsheet default
3861 (setq printer (or printer (ses-col-printer ses--col) ses--default-printer))
3862 (let ((width (ses-col-width ses--col))
3864 (or fill (setq fill ?\s))
3865 (or span (setq span 0))
3866 (setq value (ses-call-printer printer value))
3868 (setq width (+ width 1 (ses-col-width (+ ses--col span (- x))))))
3869 ;; Set column width.
3870 (setq width (- width (string-width value)))
3872 value ; Too large for field, anyway.
3873 (setq half (make-string (/ width 2) fill))
3874 (concat half value half
3875 (if (> (% width 2) 0) (char-to-string fill))))))
3877 (defun ses-center-span (value &optional fill printer)
3878 "Print VALUE, centered within the span that starts in the current column
3879 and continues until the next nonblank column.
3880 FILL specifies the fill character (default = space)."
3881 (let ((end (1+ ses--col)))
3882 (while (and (< end ses--numcols)
3883 (memq (ses-cell-value ses--row end) '(nil *skip*)))
3884 (setq end (1+ end)))
3885 (ses-center value (- end ses--col 1) fill printer)))
3887 (defun ses-dashfill (value &optional span printer)
3888 "Print VALUE centered using dashes.
3889 SPAN indicates how many rightward columns to include in width (default = 0)."
3890 (ses-center value span ?- printer))
3892 (defun ses-dashfill-span (value &optional printer)
3893 "Print VALUE, centered using dashes within the span that starts in the
3894 current column and continues until the next nonblank column."
3895 (ses-center-span value ?- printer))
3897 (defun ses-tildefill-span (value &optional printer)
3898 "Print VALUE, centered using tildes within the span that starts in the
3899 current column and continues until the next nonblank column."
3900 (ses-center-span value ?~ printer))
3902 (defun ses-prin1 (value)
3903 "Shorthand for '(prin1-to-string VALUE t)'.
3904 Useful to handle the default behavior in custom lambda based
3906 (prin1-to-string value t))
3908 (defun ses-unsafe (_value)
3909 "Substitute for an unsafe formula or printer."
3910 (error "Unsafe formula or printer"))
3912 ;;All standard printers are safe, including ses-unsafe!
3913 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3914 (put x 'side-effect-free t))
3916 (defun ses-unload-function ()
3917 "Unload the Simple Emacs Spreadsheet."
3918 (advice-remove 'yank #'ses--advice-yank)
3919 (advice-remove 'copy-region-as-kill #'ses--advice-copy-region-as-kill)
3920 ;; Continue standard unloading.
3925 ;;; ses.el ends here