1 ;;; ses.el -- Simple Emacs Spreadsheet -*- lexical-binding:t -*-
3 ;; Copyright (C) 2002-2015 Free Software Foundation, Inc.
5 ;; Author: Jonathan Yavner <jyavner@member.fsf.org>
6 ;; Maintainer: Vincent Belaïche <vincentb1@users.sourceforge.net>
7 ;; Keywords: spreadsheet Dijkstra
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
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
278 '(ses-center ses-center-span ses-dashfill ses-dashfill-span
280 "List of print functions to be included in initial history of printer
281 functions. None of these standard-printer functions is suitable for use as a
282 column printer or a global-default printer because they invoke the column or
283 default printer and then modify its output.")
286 ;;----------------------------------------------------------------------------
287 ;; Local variables and constants
288 ;;----------------------------------------------------------------------------
291 (defconst ses-localvars
292 '(ses--blank-line ses--cells ses--col-printers
293 ses--col-widths ses--curcell ses--curcell-overlay
295 (ses--local-printer-hashmap . :hashmap)
296 (ses--numlocprn . 0); count of local printers
297 ses--deferred-narrow ses--deferred-recalc
298 ses--deferred-write ses--file-format
299 ses--named-cell-hashmap
300 (ses--header-hscroll . -1) ; Flag for "initial recalc needed"
301 ses--header-row ses--header-string ses--linewidth
302 ses--numcols ses--numrows ses--symbolic-formulas
303 ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
304 ses--Dijkstra-weight-bound
305 ;; This list is useful to speed-up clean-up of symbols when
306 ;; an area containing renamed cell is deleted.
307 ses--renamed-cell-symb-list
308 ;; Global variables that we override
309 next-line-add-newlines transient-mark-mode)
310 "Buffer-local variables used by SES."))
312 (defmacro ses--metaprogramming (exp) (declare (debug t)) (eval exp t))
313 (ses--metaprogramming
314 `(progn ,@(mapcar (lambda (x) `(defvar ,(or (car-safe x) x))) ses-localvars)))
316 (defun ses-set-localvars ()
317 "Set buffer-local and initialize some SES variables."
318 (dolist (x ses-localvars)
321 (set (make-local-variable x) nil))
325 (set (make-local-variable (car x)) (cdr x)))
326 ((eq (cdr x) :hashmap)
327 (set (make-local-variable (car x)) (make-hash-table :test 'eq)))
328 (t (error "Unexpected initializer `%S' in list `ses-localvars' for entry %S"
329 (cdr x) (car x)) ) ))
330 (t (error "Unexpected elements `%S' in list `ses-localvars'" x)))))
332 ;;; This variable is documented as being permitted in file-locals:
333 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
335 (defconst ses-paramlines-plist
336 '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
337 ses--header-row -2 ses--file-format 1 ses--numrows 2
338 ses--numcols 3 ses--numlocprn 4)
339 "Offsets from 'Global parameters' line to various parameter lines in the
340 data area of a spreadsheet.")
342 (defconst ses-paramfmt-plist
343 '(ses--col-widths "(ses-column-widths %S)"
344 ses--col-printers "(ses-column-printers %S)"
345 ses--default-printer "(ses-default-printer %S)"
346 ses--header-row "(ses-header-row %S)"
347 ses--file-format " %S ;SES file-format"
348 ses--numrows " %S ;numrows"
349 ses--numcols " %S ;numcols"
350 ses--numlocprn " %S ;numlocprn")
351 "Formats of 'Global parameters' various parameters in the data
352 area of a spreadsheet.")
355 ;; "Side-effect variables". They are set in one function, altered in
356 ;; another as a side effect, then read back by the first, as a way of
357 ;; passing back more than one value. These declarations are just to make
358 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
359 ;; think the make-local-variable trick above is cleaner).
362 (defvar ses-relocate-return nil
363 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
364 `ses-relocate-all'. Set to 'delete if a cell-reference was deleted from a
365 formula--so the formula needs recalculation. Set to 'range if the size of a
366 `ses-range' was changed--so both the formula's value and list of dependents
367 need to be recalculated.")
369 (defvar ses-call-printer-return nil
370 "Set to t if last cell printer invoked by `ses-call-printer' requested
371 left-justification of the result. Set to error-signal if `ses-call-printer'
372 encountered an error during printing. Otherwise nil.")
374 (defvar ses-start-time nil
375 "Time when current operation started. Used by `ses-time-check' to decide
376 when to emit a progress message.")
379 ;;----------------------------------------------------------------------------
381 ;;----------------------------------------------------------------------------
383 (defmacro ses-get-cell (row col)
384 "Return the cell structure that stores information about cell (ROW,COL)."
386 `(aref (aref ses--cells ,row) ,col))
388 (cl-defstruct (ses-cell
390 (:constructor ses-make-cell
391 (&optional symbol formula printer references))
393 ;; This is treated as an 4-elem array in various places.
394 ;; Mostly in ses-set-cell.
395 (:type vector) ;Not named.
396 (:conc-name ses-cell--))
397 symbol formula printer references properties)
399 (cl-defstruct (ses--locprn
401 (:constructor ses-make-local-printer-info
402 (def &optional (compiled (ses-local-printer-compile def))
403 (number ses--numlocprn))))
409 (defmacro ses-cell-symbol (row &optional col)
410 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
412 `(ses-cell--symbol ,(if col `(ses-get-cell ,row ,col) row)))
413 (put 'ses-cell-symbol 'safe-function t)
415 (defmacro ses-cell-formula (row &optional col)
416 "From a CELL or a pair (ROW,COL), get the function that computes its value."
418 `(ses-cell--formula ,(if col `(ses-get-cell ,row ,col) row)))
420 (defmacro ses-cell-printer (row &optional col)
421 "From a CELL or a pair (ROW,COL), get the function that prints its value."
423 `(ses-cell--printer ,(if col `(ses-get-cell ,row ,col) row)))
425 (defmacro ses-cell-references (row &optional col)
426 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
427 functions refer to its value."
429 `(ses-cell--references ,(if col `(ses-get-cell ,row ,col) row)))
431 (defmacro ses-sym-rowcol (sym)
432 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0). Result
433 is nil if SYM is not a symbol that names a cell."
435 `(let ((rc (and (symbolp ,sym) (get ,sym 'ses-cell))))
436 (if (eq rc :ses-named)
437 (gethash ,sym ses--named-cell-hashmap)
440 (defun ses-cell-p (cell)
441 "Return non-nil if CELL is a cell of current buffer."
444 (eq cell (let ((rowcol (ses-sym-rowcol (ses-cell-symbol cell))))
446 (ses-get-cell (car rowcol) (cdr rowcol)))))))
449 (defmacro ses--letref (vars place &rest body)
450 (declare (indent 2) (debug (sexp form &rest body)))
451 (gv-letplace (getter setter) place
452 `(cl-macrolet ((,(nth 0 vars) () ',getter)
453 (,(nth 1 vars) (v) (funcall ',setter v)))
456 (defmacro ses-cell-property (property-name row &optional col)
457 "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
459 When COL is omitted, CELL=ROW is a cell object. When COL is
460 present ROW and COL are the integer coordinates of the cell of
463 `(alist-get ,property-name
464 (ses-cell--properties
465 ,(if col `(ses-get-cell ,row ,col) row))))
467 (defmacro ses-cell-property-pop (property-name row &optional col)
468 "From a CELL or a pair (ROW,COL), get and remove the property value of
469 the corresponding cell with name PROPERTY-NAME."
470 `(ses--letref (pget pset)
471 (alist-get ,property-name
472 (ses-cell--properties
473 ,(if col `(ses-get-cell ,row ,col) row))
475 (prog1 (pget) (pset nil))))
477 (defmacro ses-cell-value (row &optional col)
478 "From a CELL or a pair (ROW,COL), get the current value for that cell."
480 `(symbol-value (ses-cell-symbol ,row ,col)))
482 (defmacro ses-col-width (col)
483 "Return the width for column COL."
485 `(aref ses--col-widths ,col))
487 (defmacro ses-col-printer (col)
488 "Return the default printer for column COL."
490 `(aref ses--col-printers ,col))
492 (defun ses-is-cell-sym-p (sym)
493 "Check whether SYM point at a cell of this spread sheet."
494 (let ((rowcol (get sym 'ses-cell)))
496 (if (eq rowcol :ses-named)
497 (and ses--named-cell-hashmap (gethash sym ses--named-cell-hashmap))
498 (and (< (car rowcol) ses--numrows)
499 (< (cdr rowcol) ses--numcols)
500 (eq (ses-cell-symbol (car rowcol) (cdr rowcol)) sym))))))
502 (defun ses--cell (sym value formula printer references)
503 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
504 FORMULA, does not reprint using PRINTER, does not check REFERENCES.
505 Safety-checking for FORMULA and PRINTER are deferred until first use."
506 (let ((rowcol (ses-sym-rowcol sym)))
507 (ses-formula-record formula)
508 (ses-printer-record printer)
509 (unless (or formula (eq value '*skip*))
510 (setq formula (macroexp-quote value)))
512 (eq safe-functions t)
513 (setq formula `(ses-safe-formula ,formula)))
516 (eq safe-functions t)
517 (setq printer `(ses-safe-printer ,printer)))
518 (setf (ses-get-cell (car rowcol) (cdr rowcol))
519 (ses-make-cell sym formula printer references)))
522 (defun ses-local-printer-compile (printer)
523 "Convert local printer function into faster printer
526 ((functionp printer) printer)
528 `(lambda (x) (format ,printer x)))
529 (t (error "Invalid printer %S" printer))))
531 (defun ses--local-printer (name def)
532 "Define a local printer with name NAME and definition DEF.
533 Return the printer info."
536 (ses-printer-validate def))
537 (error "Invalid local printer definition"))
538 (and (gethash name ses--local-printer-hashmap)
539 (error "Duplicate printer definition %S" name))
540 (add-to-list 'ses-read-printer-history (symbol-name name))
542 (ses-make-local-printer-info (ses-safe-printer def))
543 ses--local-printer-hashmap))
545 (defmacro ses-column-widths (widths)
546 "Load the vector of column widths from the spreadsheet file. This is a
547 macro to prevent propagate-on-load viruses."
548 (or (and (vectorp widths) (= (length widths) ses--numcols))
549 (error "Bad column-width vector"))
550 ;;To save time later, we also calculate the total width of each line in the
551 ;;print area (excluding the terminating newline)
552 (setq ses--col-widths widths
553 ses--linewidth (apply #'+ -1 (mapcar #'1+ widths))
554 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
557 (defmacro ses-column-printers (printers)
558 "Load the vector of column printers from the spreadsheet file and checks
559 them for safety. This is a macro to prevent propagate-on-load viruses."
560 (or (and (vectorp printers) (= (length printers) ses--numcols))
561 (error "Bad column-printers vector"))
562 (dotimes (x ses--numcols)
563 (aset printers x (ses-safe-printer (aref printers x))))
564 (setq ses--col-printers printers)
565 (mapc #'ses-printer-record printers)
568 (defmacro ses-default-printer (def)
569 "Load the global default printer from the spreadsheet file and checks it
570 for safety. This is a macro to prevent propagate-on-load viruses."
571 (setq ses--default-printer (ses-safe-printer def))
572 (ses-printer-record def)
575 (defmacro ses-header-row (row)
576 "Load the header row from the spreadsheet file and checks it
577 for safety. This is a macro to prevent propagate-on-load viruses."
578 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
579 (error "Bad header-row"))
580 (setq ses--header-row row)
583 (defmacro ses-dorange (curcell &rest body)
584 "Execute BODY repeatedly, with the variables `row' and `col' set to each
585 cell in the range specified by CURCELL. The range is available in the
586 variables `minrow', `maxrow', `mincol', and `maxcol'."
587 (declare (indent defun) (debug (form body)))
588 (let ((cur (make-symbol "cur"))
589 (min (make-symbol "min"))
590 (max (make-symbol "max"))
591 (r (make-symbol "r"))
592 (c (make-symbol "c")))
593 `(let* ((,cur ,curcell)
594 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
595 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
596 (let ((minrow (car ,min))
600 (if (or (> minrow maxrow) (> mincol maxcol))
601 (error "Empty range"))
602 (dotimes (,r (- maxrow minrow -1))
603 (let ((row (+ ,r minrow)))
604 (dotimes (,c (- maxcol mincol -1))
605 (let ((col (+ ,c mincol)))
608 ;;Support for coverage testing.
609 (defmacro 1value (form)
610 "For code-coverage testing, indicate that FORM is expected to always have
614 (defmacro noreturn (form)
615 "For code-coverage testing, indicate that FORM will always signal an error."
620 ;;----------------------------------------------------------------------------
622 ;;----------------------------------------------------------------------------
624 (defun ses-vector-insert (array idx new)
625 "Create a new vector which is one larger than ARRAY and has NEW inserted
627 (let* ((len (length array))
628 (result (make-vector (1+ len) new)))
631 (if (< x idx) x (1+ x))
635 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
636 (defun ses-vector-delete (array idx count)
637 "Create a new vector which is a copy of ARRAY with COUNT objects removed
638 starting at element IDX. ARRAY is either a vector or a symbol whose value
639 is a vector--if a symbol, the new vector is assigned as the symbol's value."
640 (let* ((a (if (arrayp array) array (symbol-value array)))
641 (len (- (length a) count))
642 (result (make-vector len nil)))
644 (aset result x (aref a (if (< x idx) x (+ x count)))))
649 (defun ses-delete-line (count)
650 "Like `kill-line', but no kill ring."
653 (delete-region pos (point))))
655 (defun ses-printer-validate (printer)
656 "Signal an error if PRINTER is not a valid SES cell printer."
659 ;; printer is a local printer
660 (and (symbolp printer) (gethash printer ses--local-printer-hashmap))
662 (and (stringp (car-safe printer)) (not (cdr printer)))
663 (error "Invalid printer function %S" printer))
666 (defun ses-printer-record (printer)
667 "Add PRINTER to `ses-read-printer-history' if not already there, after first
668 checking that it is a valid printer function."
669 (ses-printer-validate printer)
670 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
672 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
674 (defun ses-formula-record (formula)
675 "If FORMULA is of the form 'symbol, add it to the list of symbolic formulas
676 for this spreadsheet."
677 (when (and (eq (car-safe formula) 'quote)
678 (symbolp (cadr formula)))
679 (add-to-list 'ses--symbolic-formulas
680 (list (symbol-name (cadr formula))))))
682 (defun ses-column-letter (col)
683 "Return the alphabetic name of column number COL.
684 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
685 (let ((units (char-to-string (+ ?A (% col 26)))))
688 (concat (ses-column-letter (1- (/ col 26))) units))))
690 (defun ses-create-cell-symbol (row col)
691 "Produce a symbol that names the cell (ROW,COL). (0,0) => 'A1."
692 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
694 (defun ses-decode-cell-symbol (str)
695 "Decode a symbol \"A1\" => (0,0). Return nil if STR is not a
696 canonical cell name."
697 (let (case-fold-search)
698 (and (string-match "\\`\\([A-Z]+\\)\\([0-9]+\\)\\'" str)
699 (let* ((col-str (match-string-no-properties 1 str))
702 (col-idx (1- (length col-str)))
703 (row (1- (string-to-number
704 (match-string-no-properties 2 str)))))
709 (setq col (+ col (* (- (aref col-str col-idx) ?A)
711 col-base (* col-base 26)
712 col-idx (1- col-idx))
714 (setq col (+ col col-base)))))
717 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
718 "Create buffer-local variables for cells. This is undoable."
719 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
722 (dotimes (row (1+ (- maxrow minrow)))
723 (dotimes (col (1+ (- maxcol mincol)))
724 (setq xrow (+ row minrow)
726 sym (ses-create-cell-symbol xrow xcol))
727 (put sym 'ses-cell (cons xrow xcol))
728 (make-local-variable sym)))))
730 (defun ses-create-cell-variable (sym row col)
731 "Create a buffer-local variable `SYM' for cell at position (ROW, COL).
733 SYM is the symbol for that variable, ROW and COL are integers for
734 row and column of the cell, with numbering starting from 0.
736 Return nil in case of failure."
737 (unless (local-variable-p sym)
738 (make-local-variable sym)
739 (if (let (case-fold-search) (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name sym)))
740 (put sym 'ses-cell (cons row col))
741 (put sym 'ses-cell :ses-named)
742 (setq ses--named-cell-hashmap (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
743 (puthash sym (cons row col) ses--named-cell-hashmap))))
745 ;; We do not delete the ses-cell properties for the cell-variables, in
746 ;; case a formula that refers to this cell is in the kill-ring and is
747 ;; later pasted back in.
748 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
749 "Destroy buffer-local variables for cells. This is undoable."
751 (dotimes (row (1+ (- maxrow minrow)))
752 (dotimes (col (1+ (- maxcol mincol)))
753 (let ((xrow (+ row minrow)) (xcol (+ col mincol)))
754 (setq sym (if (and (< xrow ses--numrows) (< xcol ses--numcols))
755 (ses-cell-symbol xrow xcol)
756 (ses-create-cell-symbol xrow xcol))))
758 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
760 (kill-local-variable sym))))
761 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
764 (defun ses-reset-header-string ()
765 "Flag the header string for update. Upon undo, the header string will be
767 (push '(apply ses-reset-header-string) buffer-undo-list)
768 (setq ses--header-hscroll -1))
770 ;;Split this code off into a function to avoid coverage-testing difficulties
771 (defmacro ses--time-check (format &rest args)
772 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
773 and ARGS and reset `ses-start-time' to the current time."
774 `(when (> (- (float-time) ses-start-time) 1.0)
775 (message ,format ,@args)
776 (setq ses-start-time (float-time))))
779 ;;----------------------------------------------------------------------------
781 ;;----------------------------------------------------------------------------
783 (defmacro ses-set-cell (row col field val)
784 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
785 cell (ROW,COL). This is undoable. The cell's data will be updated through
786 `post-command-hook'."
790 (let* ((cell (ses-get-cell row col))
792 ,(let ((field (progn (cl-assert (eq (car field) 'quote))
794 (if (eq field 'value)
795 `(ses-set-with-undo (ses-cell-symbol cell) val)
796 ;; (let* ((slots (get 'ses-cell 'cl-struct-slots))
797 ;; (slot (or (assq field slots)
798 ;; (error "Unknown field %S" field)))
799 ;; (idx (- (length slots)
800 ;; (length (memq slot slots)))))
801 ;; `(ses-aset-with-undo cell ,idx val))
802 (let ((getter (intern-soft (format "ses-cell--%s" field))))
803 `(ses-setter-with-undo
806 (lambda (newval cell)
807 (setf (,getter cell) newval))))
810 (add-to-list 'ses--deferred-write (cons row col))))
811 nil)) ; Make coverage-tester happy.
813 (defun ses-cell-set-formula (row col formula)
814 "Store a new formula for (ROW . COL) and enqueue the cell for
815 recalculation via `post-command-hook'. Updates the reference lists for the
816 cells that this cell refers to. Does not update cell value or reprint the
817 cell. To avoid inconsistencies, this function is not interruptible, which
818 means Emacs will crash if FORMULA contains a circular list."
819 (let* ((cell (ses-get-cell row col))
820 (old (ses-cell-formula cell)))
821 (let ((sym (ses-cell-symbol cell))
822 (oldref (ses-formula-references old))
823 (newref (ses-formula-references formula))
826 (cl-pushnew sym ses--deferred-recalc)
827 ;;Delete old references from this cell. Skip the ones that are also
830 (unless (memq ref newref)
831 (setq x (ses-sym-rowcol ref)
834 (ses-set-cell xrow xcol 'references
835 (delq sym (ses-cell-references xrow xcol)))))
836 ;;Add new ones. Skip ones left over from old list
838 (setq x (ses-sym-rowcol ref)
841 x (ses-cell-references xrow xcol))
843 (ses-set-cell xrow xcol 'references (cons sym x))))
844 (ses-formula-record formula)
845 (ses-set-cell row col 'formula formula))))
848 (defun ses-repair-cell-reference-all ()
849 "Repair cell reference and warn if there was some reference corruption."
852 ;; Step 1, reset :ses-repair-reference cell property in the whole sheet.
853 (dotimes (row ses--numrows)
854 (dotimes (col ses--numcols)
855 (let ((references (ses-cell-property-pop :ses-repair-reference
858 (push (list (ses-cell-symbol row col)
863 ;; Step 2, build new.
864 (dotimes (row ses--numrows)
865 (dotimes (col ses--numcols)
866 (let* ((cell (ses-get-cell row col))
867 (sym (ses-cell-symbol cell))
868 (formula (ses-cell-formula cell))
869 (new-ref (ses-formula-references formula)))
870 (dolist (ref new-ref)
871 (let ((rowcol (ses-sym-rowcol ref)))
872 (cl-pushnew sym (ses-cell-property :ses-repair-reference
876 ;; Step 3, overwrite with check.
877 (dotimes (row ses--numrows)
878 (dotimes (col ses--numcols)
879 (let* ((cell (ses-get-cell row col))
880 (irrelevant (ses-cell-references cell))
881 (new-ref (ses-cell-property-pop :ses-repair-reference cell))
883 (dolist (ref new-ref)
884 (if (memq ref irrelevant)
885 (setq irrelevant (delq ref irrelevant))
887 (ses-set-cell row col 'references new-ref)
888 (when (or missing irrelevant)
889 (push `( ,(ses-cell-symbol cell)
890 ,@(and missing (list :missing missing))
891 ,@(and irrelevant (list :irrelevant irrelevant)))
894 (warn "----------------------------------------------------------------
895 Some references were corrupted.
897 The following is a list where each element ELT is such
898 that (car ELT) is the reference of cell CELL with corruption,
899 and (cdr ELT) is a property list where
901 * property `:corrupt-property' means that
902 property `:ses-repair-reference' of cell CELL was initially non
905 * property `:missing' is a list of missing references
907 * property `:irrelevant' is a list of non needed references
910 (message "No reference corruption found"))))
912 (defun ses-calculate-cell (row col force)
913 "Calculate and print the value for cell (ROW,COL) using the cell's formula
914 function and print functions, if any. Result is nil for normal operation, or
915 the error signal if the formula or print function failed. The old value is
916 left unchanged if it was *skip* and the new value is nil.
917 Any cells that depend on this cell are queued for update after the end of
918 processing for the current keystroke, unless the new value is the same as
919 the old and FORCE is nil."
920 (let ((cell (ses-get-cell row col))
921 cycle-error formula-error printer-error)
922 (let ((oldval (ses-cell-value cell))
923 (formula (ses-cell-formula cell))
925 this-cell-Dijkstra-attempt+1)
926 (when (eq (car-safe formula) 'ses-safe-formula)
927 (setq formula (ses-safe-formula (cadr formula)))
928 (ses-set-cell row col 'formula formula))
930 (setq newval (eval formula t))
932 ;; Variable `sig' can't be nil.
933 (nconc sig (list (ses-cell-symbol cell)))
934 (setq formula-error sig
936 (if (and (not newval) (eq oldval '*skip*))
937 ;; Don't lose the *skip* --- previous field spans this one.
938 (setq newval '*skip*))
940 (when (or force (not (eq newval oldval)))
941 (cl-pushnew (cons row col) ses--deferred-write :test #'equal) ; In case force=t.
942 (ses--letref (pget pset)
943 (ses-cell-property :ses-Dijkstra-attempt cell)
944 (let ((this-cell-Dijkstra-attempt (pget)))
945 (if (null this-cell-Dijkstra-attempt)
947 (setq this-cell-Dijkstra-attempt
948 (cons ses--Dijkstra-attempt-nb 0)))
949 (unless (= ses--Dijkstra-attempt-nb
950 (car this-cell-Dijkstra-attempt))
951 (setcar this-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
952 (setcdr this-cell-Dijkstra-attempt 0)))
953 (setq this-cell-Dijkstra-attempt+1
954 (1+ (cdr this-cell-Dijkstra-attempt)))))
955 (ses-set-cell row col 'value newval)
956 (dolist (ref (ses-cell-references cell))
957 (cl-pushnew ref ses--deferred-recalc)
958 (ses--letref (pget pset)
959 (let ((ref-rowcol (ses-sym-rowcol ref)))
961 :ses-Dijkstra-attempt
962 (car ref-rowcol) (cdr ref-rowcol)))
963 (let ((ref-cell-Dijkstra-attempt (pget)))
965 (if (null ref-cell-Dijkstra-attempt)
967 (setq ref-cell-Dijkstra-attempt
968 (cons ses--Dijkstra-attempt-nb
969 this-cell-Dijkstra-attempt+1)))
970 (if (= (car ref-cell-Dijkstra-attempt) ses--Dijkstra-attempt-nb)
971 (setcdr ref-cell-Dijkstra-attempt
972 (max (cdr ref-cell-Dijkstra-attempt)
973 this-cell-Dijkstra-attempt+1))
974 (setcar ref-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
975 (setcdr ref-cell-Dijkstra-attempt
976 this-cell-Dijkstra-attempt+1)))))
978 (when (> this-cell-Dijkstra-attempt+1 ses--Dijkstra-weight-bound)
979 ;; Update print of this cell.
980 (throw 'cycle (setq formula-error
981 `(error ,(format "Found cycle on cells %S"
982 (ses-cell-symbol cell)))
983 cycle-error formula-error)))))))
984 (setq printer-error (ses-print-cell row col))
987 (error (error-message-string cycle-error)))
988 formula-error printer-error)))
990 (defun ses-clear-cell (row col)
991 "Delete formula and printer for cell (ROW,COL)."
992 (ses-set-cell row col 'printer nil)
993 (ses-cell-set-formula row col nil))
995 (defcustom ses-self-reference-early-detection nil
996 "True if cycle detection is early for cells that refer to themselves."
1001 (defun ses-update-cells (list &optional force)
1002 "Recalculate cells in LIST, checking for dependency loops. Prints
1003 progress messages every second. Dependent cells are not recalculated
1004 if the cell's value is unchanged and FORCE is nil."
1005 (let ((ses--deferred-recalc list)
1008 curlist prevlist this-sym this-rowcol formula)
1009 (with-temp-message " "
1010 (while ses--deferred-recalc
1011 ;; In each loop, recalculate cells that refer only to other cells that
1012 ;; have already been recalculated or aren't in the recalculation region.
1013 ;; Repeat until all cells have been processed or until the set of cells
1014 ;; being worked on stops changing.
1016 (message "Recalculating... (%d cells left)"
1017 (length ses--deferred-recalc)))
1018 (setq curlist ses--deferred-recalc
1019 ses--deferred-recalc nil
1022 ;; this-sym has to be popped from curlist *BEFORE* the check, and not
1023 ;; after because of the case of cells referring to themselves.
1024 (setq this-sym (pop curlist)
1025 this-rowcol (ses-sym-rowcol this-sym)
1026 formula (ses-cell-formula (car this-rowcol)
1029 (dolist (ref (ses-formula-references formula))
1030 (if (and ses-self-reference-early-detection (eq ref this-sym))
1031 (error "Cycle found: cell %S is self-referring" this-sym)
1032 (when (or (memq ref curlist)
1033 (memq ref ses--deferred-recalc))
1034 ;; This cell refers to another that isn't done yet
1035 (cl-pushnew this-sym ses--deferred-recalc :test #'equal)
1037 ;; ses-update-cells is called from post-command-hook, so
1038 ;; inhibit-quit is implicitly bound to t.
1040 ;; Abort the recalculation. User will probably undo now.
1042 (ses-calculate-cell (car this-rowcol) (cdr this-rowcol) force)))
1043 (dolist (ref ses--deferred-recalc)
1044 (cl-pushnew ref nextlist :test #'equal)))
1045 (when ses--deferred-recalc
1046 ;; Just couldn't finish these.
1047 (dolist (x ses--deferred-recalc)
1048 (let ((this-rowcol (ses-sym-rowcol x)))
1049 (ses-set-cell (car this-rowcol) (cdr this-rowcol) 'value '*error*)
1050 (1value (ses-print-cell (car this-rowcol) (cdr this-rowcol)))))
1051 (error "Circular references: %s" ses--deferred-recalc))
1053 ;; Can't use save-excursion here: if the cell under point is updated,
1054 ;; save-excursion's marker will move past the cell.
1058 ;;----------------------------------------------------------------------------
1060 ;;----------------------------------------------------------------------------
1062 (defun ses-in-print-area ()
1063 "Return t if point is in print area of spreadsheet."
1064 (<= (point) ses--data-marker))
1066 ;; We turn off point-motion-hooks and explicitly position the cursor, in case
1067 ;; the intangible properties have gotten screwed up (e.g., when ses-goto-print
1068 ;; is called during a recursive ses-print-cell).
1069 (defun ses-goto-print (row col)
1070 "Move point to print area for cell (ROW,COL)."
1072 (goto-char (point-min))
1074 ;; Calculate column position.
1076 (setq n (+ n (ses-col-width c) 1)))
1077 ;; Move to the position.
1078 (and (> n (move-to-column n))
1080 ;; Move point to the bol of next line (for TAB at the last cell).
1083 (defun ses--cell-at-pos (pos &optional object)
1084 (or (get-text-property pos 'cursor-intangible object)
1085 ;; (when (> pos (if object 0 (point-min)))
1086 ;; (get-text-property (1- pos) 'cursor-intangible object))
1089 (defun ses--curcell (&optional pos)
1090 "Return the current cell symbol, or a cons (BEG,END) for a
1091 region, or nil if cursor is not at a cell."
1092 (unless pos (setq pos (point)))
1093 (if (or (not mark-active)
1097 (ses--cell-at-pos pos)
1099 (let* ((re (max pos (mark t)))
1100 (bcell (ses--cell-at-pos (min pos (mark t))))
1101 (ecell (ses--cell-at-pos (1- re))))
1102 (when (= re ses--data-marker)
1103 ;; Correct for overflow.
1104 (setq ecell (ses--cell-at-pos (- (region-end) 2))))
1105 (if (and bcell ecell)
1109 (defun ses-set-curcell ()
1110 "Set `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
1111 region, or nil if cursor is not at a cell."
1112 (setq ses--curcell (ses--curcell))
1115 (defun ses-check-curcell (&rest args)
1116 "Signal an error if `ses--curcell' is inappropriate.
1117 The end marker is appropriate if some argument is 'end.
1118 A range is appropriate if some argument is 'range.
1119 A single cell is appropriate unless some argument is 'needrange."
1120 (if (eq ses--curcell t)
1121 ;; curcell recalculation was postponed, but user typed ahead.
1125 (or (memq 'end args)
1126 (error "Not at cell")))
1127 ((consp ses--curcell)
1128 (or (memq 'range args)
1129 (memq 'needrange args)
1130 (error "Can't use a range")))
1131 ((memq 'needrange args)
1132 (error "Need a range"))))
1137 (defun ses-print-cell (row col)
1138 "Format and print the value of cell (ROW,COL) to the print area.
1139 Use the cell's printer function. If the cell's new print form is too wide,
1140 it will spill over into the following cell, but will not run off the end of the
1141 row or overwrite the next non-nil field. Result is nil for normal operation,
1142 or the error signal if the printer function failed and the cell was formatted
1143 with \"%s\". If the cell's value is *skip*, nothing is printed because the
1144 preceding cell has spilled over."
1145 (catch 'ses-print-cell
1146 (let* ((cell (ses-get-cell row col))
1147 (value (ses-cell-value cell))
1148 (printer (ses-cell-printer cell))
1150 text sig startpos x)
1151 ;; Create the string to print.
1154 ;; Don't print anything.
1155 (throw 'ses-print-cell nil))
1156 ((eq value '*error*)
1157 (setq text (make-string (ses-col-width col) ?#)))
1159 ;; Deferred safety-check on printer.
1160 (if (eq (car-safe printer) 'ses-safe-printer)
1161 (ses-set-cell row col 'printer
1162 (setq printer (ses-safe-printer (cadr printer)))))
1165 (let ((ses--row row)
1167 (ses-call-printer (or printer
1168 (ses-col-printer col)
1169 ses--default-printer)
1171 (if (consp ses-call-printer-return)
1172 ;; Printer returned an error.
1173 (setq sig ses-call-printer-return))))
1174 ;; Adjust print width to match column width.
1175 (let ((width (ses-col-width col))
1176 (len (string-width text)))
1179 ;; Fill field to length with spaces.
1180 (setq len (make-string (- width len) ?\s)
1181 text (if (or (stringp value)
1182 (eq ses-call-printer-return t))
1184 (concat len text))))
1186 ;; Spill over into following cells, if possible.
1187 (let ((maxwidth width))
1188 (while (and (> len maxwidth)
1189 (< maxcol ses--numcols)
1190 (or (not (setq x (ses-cell-value row maxcol)))
1193 ;; Set this cell to '*skip* so it won't overwrite our spillover.
1194 (ses-set-cell row maxcol 'value '*skip*))
1195 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
1196 maxcol (1+ maxcol)))
1197 (if (<= len maxwidth)
1198 ;; Fill to complete width of all the fields spanned.
1199 (setq text (concat text (make-string (- maxwidth len) ?\s)))
1200 ;; Not enough room to end of line or next non-nil field. Truncate
1201 ;; if string or decimal; otherwise fill with error indicator.
1202 (setq sig `(error "Too wide" ,text))
1205 (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
1206 ((and (numberp value)
1207 (string-match "\\.[0-9]+" text)
1210 (- (match-end 0) (match-beginning 0))))))
1211 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
1212 (setq text (concat (substring text
1214 (- (match-beginning 0) width))
1215 (substring text (match-end 0)))))
1217 (setq text (make-string maxwidth ?#)))))))))
1218 ;; Substitute question marks for tabs and newlines. Newlines are used as
1219 ;; row-separators; tabs could confuse the reimport logic.
1220 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
1221 (ses-goto-print row col)
1222 (setq startpos (point))
1223 ;; Install the printed result. This is not interruptible.
1224 (let ((inhibit-read-only t)
1226 (delete-region (point) (progn
1227 (move-to-column (+ (current-column)
1228 (string-width text)))
1230 ;; We use concat instead of inserting separate strings in order to
1231 ;; reduce the number of cells in the undo list.
1232 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
1233 ;; We use set-text-properties to prevent a wacky print function from
1234 ;; inserting rogue properties, and to ensure that the keymap property is
1235 ;; inherited (is it a bug that only unpropertized strings actually
1236 ;; inherit from surrounding text?)
1237 (set-text-properties 0 (length x) nil x)
1238 (insert-and-inherit x)
1239 (put-text-property startpos (point) 'cursor-intangible
1240 (ses-cell-symbol cell))
1241 (when (and (zerop row) (zerop col))
1242 ;; Reconstruct special beginning-of-buffer attributes.
1243 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
1244 (put-text-property (point-min) (point) 'read-only 'ses)
1245 (put-text-property (point-min) (1+ (point-min))
1246 ;; `cursor-intangible' shouldn't be sticky at BOB.
1247 'front-sticky '(read-only keymap))))
1248 (if (= row (1- ses--header-row))
1249 ;; This line is part of the header --- force recalc.
1250 (ses-reset-header-string))
1251 ;; If this cell (or a preceding one on the line) previously spilled over
1252 ;; and has gotten shorter, redraw following cells on line recursively.
1253 (when (and (< maxcol ses--numcols)
1254 (eq (ses-cell-value row maxcol) '*skip*))
1255 (ses-set-cell row maxcol 'value nil)
1256 (ses-print-cell row maxcol))
1257 ;; Return to start of cell.
1258 (goto-char startpos)
1261 (defun ses-call-printer (printer &optional value)
1262 "Invoke PRINTER (a string or parenthesized string or function-symbol or
1263 lambda of one argument) on VALUE. Result is the printed cell as a string.
1264 The variable `ses-call-printer-return' is set to t if the printer used
1265 parenthesis to request left-justification, or the error-signal if the
1266 printer signaled one (and \"%s\" is used as the default printer), else nil."
1267 (setq ses-call-printer-return nil)
1268 (condition-case signal
1272 (format printer value)
1274 ((stringp (car-safe printer))
1275 (setq ses-call-printer-return t)
1277 (format (car printer) value)
1282 (or (and (symbolp printer)
1283 (let ((locprn (gethash printer
1284 ses--local-printer-hashmap)))
1286 (ses--locprn-compiled locprn))))
1291 (or (stringp (car-safe value))
1292 (error "Printer should return \"string\" or (\"string\")"))
1293 (setq ses-call-printer-return t)
1296 (setq ses-call-printer-return signal)
1297 (prin1-to-string value t))))
1299 (defun ses-adjust-print-width (col change)
1300 "Insert CHANGE spaces in front of column COL, or at end of line if
1301 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
1302 `inhibit-quit' to t."
1303 (let ((inhibit-read-only t)
1304 (blank (if (> change 0) (make-string change ?\s)))
1305 (at-end (= col ses--numcols)))
1306 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
1307 ;; ses-set-with-undo always returns t for strings.
1308 (1value (ses-set-with-undo 'ses--blank-line
1309 (concat (make-string ses--linewidth ?\s) "\n")))
1310 (dotimes (row ses--numrows)
1311 (ses-goto-print row col)
1313 ;; Insert new columns before newline.
1317 (delete-char (- change))))))
1319 (defun ses-print-cell-new-width (row col)
1320 "Same as `ses-print-cell', except if the cell's value is *skip*,
1321 the preceding nonskipped cell is reprinted. This function is used
1322 when the width of cell (ROW,COL) has changed."
1323 (if (not (eq (ses-cell-value row col) '*skip*))
1324 (ses-print-cell row col)
1325 ;;Cell was skipped over - reprint previous
1326 (ses-goto-print row col)
1328 (let ((rowcol (ses-sym-rowcol (ses--cell-at-pos (point)))))
1329 (ses-print-cell (car rowcol) (cdr rowcol)))))
1332 ;;----------------------------------------------------------------------------
1334 ;;----------------------------------------------------------------------------
1337 "Turn off narrowing, to be reenabled at end of command loop."
1338 (if (buffer-narrowed-p)
1339 (setq ses--deferred-narrow t))
1342 (defun ses-goto-data (def &optional col)
1343 "Move point to data area for (DEF,COL). If DEF is a row
1344 number, COL is the column number for a data cell -- otherwise DEF
1345 is one of the symbols ses--col-widths, ses--col-printers,
1346 ses--default-printer, ses--numrows, or ses--numcols."
1351 (goto-char ses--data-marker)
1352 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
1353 ;; Convert def-symbol to offset.
1354 (setq def (plist-get ses-paramlines-plist def))
1355 (or def (signal 'args-out-of-range nil))
1356 (goto-char ses--params-marker)
1357 (forward-line def)))
1359 (defun ses-file-format-extend-parameter-list (new-file-format)
1360 "Extend the global parameters list when file format is updated
1361 from 2 to 3. This happens when local printer function are added
1362 to a sheet that was created with SES version 2. This is not
1363 undoable. Return nil when there was no change, and non nil otherwise."
1366 ((and (= ses--file-format 2) (= 3 new-file-format))
1367 (ses-set-parameter 'ses--file-format 3)
1368 (message "Upgrading from SES-2 to SES-3 file format")
1370 (goto-char ses--params-marker)
1371 (forward-line (plist-get ses-paramlines-plist 'ses--numlocprn ))
1372 (insert (format (plist-get ses-paramfmt-plist 'ses--numlocprn)
1377 (defun ses-set-parameter (def value &optional elem)
1378 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1379 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1380 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
1382 ;; We call ses-goto-data early, using the old values of numrows and numcols
1383 ;; in case one of them is being changed.
1385 (let ((inhibit-read-only t)
1386 (fmt (plist-get ses-paramfmt-plist
1391 (setq oldval (aref (symbol-value def) elem))
1392 (aset (symbol-value def) elem value))
1393 (setq oldval (symbol-value def))
1395 ;; Special undo since it's outside the narrowed buffer.
1396 (let (buffer-undo-list)
1397 (delete-region (point) (line-end-position))
1398 (insert (format fmt (symbol-value def))))
1399 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1402 (defun ses-write-cells ()
1403 "Write cells in `ses--deferred-write' from local variables to data area.
1404 Newlines in the data are escaped."
1405 (let* ((inhibit-read-only t)
1406 (print-escape-newlines t)
1407 rowcol row col cell sym formula printer text)
1408 (setq ses-start-time (float-time))
1409 (with-temp-message " "
1411 (while ses--deferred-write
1412 (ses--time-check "Writing... (%d cells left)"
1413 (length ses--deferred-write))
1414 (setq rowcol (pop ses--deferred-write)
1417 cell (ses-get-cell row col)
1418 sym (ses-cell-symbol cell)
1419 formula (ses-cell-formula cell)
1420 printer (ses-cell-printer cell))
1421 (if (eq (car-safe formula) 'ses-safe-formula)
1422 (setq formula (cadr formula)))
1423 (if (eq (car-safe printer) 'ses-safe-printer)
1424 (setq printer (cadr printer)))
1425 (setq text (prin1-to-string
1426 ;; We could shorten it to (ses-cell SYM VAL) when
1427 ;; the other parameters are nil, but in practice most
1428 ;; cells have non-nil `references', so it's
1429 ;; rather pointless.
1432 ,(unless (equal formula (symbol-value sym))
1435 ,(ses-cell-references cell))))
1436 (ses-goto-data row col)
1437 (delete-region (point) (line-end-position))
1442 ;;----------------------------------------------------------------------------
1443 ;; Formula relocation
1444 ;;----------------------------------------------------------------------------
1446 (defun ses-formula-references (formula &optional result-so-far)
1447 "Produce a list of symbols for cells that this FORMULA's value
1448 refers to. For recursive calls, RESULT-SO-FAR is the list being
1449 constructed, or t to get a wrong-type-argument error when the
1450 first reference is found."
1451 (if (ses-sym-rowcol formula)
1452 ;; Entire formula is one symbol.
1453 (cl-pushnew formula result-so-far :test #'equal)
1456 ((eq (car formula) 'ses-range)
1458 (cdr (funcall 'macroexpand
1459 (list 'ses-range (nth 1 formula)
1461 (cl-pushnew cur result-so-far :test #'equal)))
1462 ((null (eq (car formula) 'quote))
1463 ;;Recursive call for subformulas
1464 (dolist (cur formula)
1465 (setq result-so-far (ses-formula-references cur result-so-far))))
1467 ;;Ignore other stuff
1469 ;; other type of atom are ignored
1473 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1474 "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
1475 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1476 by (ROWINCR,COLINCR)."
1477 (let ((row (car rowcol))
1479 (if (or (< row startrow) (< col startcol))
1481 (setq row (+ row rowincr)
1482 col (+ col colincr))
1483 (if (and (>= row startrow) (>= col startcol)
1484 (< row ses--numrows) (< col ses--numcols))
1485 ;;Relocate this variable
1486 (ses-create-cell-symbol row col)
1487 ;;Delete reference to a deleted cell
1490 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1491 "Produce a copy of FORMULA where all symbols that refer to cells in row
1492 STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
1493 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1494 (ses-relocate-formula \\='(+ A1 B2 D3) 1 2 1 -1)
1496 If ROWINCR or COLINCR is negative, references to cells being deleted are
1498 (ses-relocate-formula \\='(+ A1 B2 D3) 0 1 0 -1)
1500 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1501 (let (rowcol result)
1502 (if (or (atom formula) (eq (car formula) 'quote))
1503 (if (and (setq rowcol (ses-sym-rowcol formula))
1504 (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name formula)))
1505 (ses-relocate-symbol formula rowcol
1506 startrow startcol rowincr colincr)
1507 formula) ; Pass through as-is.
1508 (dolist (cur formula)
1509 (setq rowcol (ses-sym-rowcol cur))
1512 (setq cur (ses-relocate-symbol cur rowcol
1513 startrow startcol rowincr colincr))
1516 ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
1517 ;; don't change the flag if it's already 'range, since range implies
1519 (unless ses-relocate-return
1520 (setq ses-relocate-return 'delete))))
1521 ((eq (car-safe cur) 'ses-range)
1522 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1525 ((or (atom cur) (eq (car cur) 'quote))
1526 ;; Constants pass through unchanged.
1529 ;; Recursively copy and alter subformulas.
1530 (push (ses-relocate-formula cur startrow startcol
1533 (nreverse result))))
1535 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1536 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1537 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1538 new range, or nil if the entire range is deleted. If new rows are being added
1539 just beyond the end of a row range, or new columns just beyond a column range,
1540 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1541 if the range was altered."
1542 (let* ((minorig (cadr range))
1543 (minrowcol (ses-sym-rowcol minorig))
1544 (min (ses-relocate-symbol minorig minrowcol
1547 (maxorig (nth 2 range))
1548 (maxrowcol (ses-sym-rowcol maxorig))
1549 (max (ses-relocate-symbol maxorig maxrowcol
1554 ((and (not min) (not max))
1555 (setq range nil)) ; The entire range is deleted.
1557 ;; Inserting or deleting rows.
1560 ;; Chopped off beginning of range.
1561 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1562 ses-relocate-return 'range))
1565 ;; Trying to insert a nonexistent row.
1566 (setq max (ses-create-cell-symbol (1- ses--numrows)
1568 ;; End of range is being deleted.
1569 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1570 ses-relocate-return 'range))
1572 (= (car maxrowcol) (1- startrow))
1573 (= (cdr minrowcol) (cdr maxrowcol))
1574 ;; Insert after ending row of vertical range --- include it.
1575 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1576 (cdr maxrowcol))))))
1578 ;; Inserting or deleting columns.
1581 ;; Chopped off beginning of range.
1582 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1583 ses-relocate-return 'range))
1586 ;; Trying to insert a nonexistent column.
1587 (setq max (ses-create-cell-symbol (car maxrowcol)
1589 ;; End of range is being deleted.
1590 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1591 ses-relocate-return 'range))
1593 (= (cdr maxrowcol) (1- startcol))
1594 (= (car minrowcol) (car maxrowcol))
1595 ;; Insert after ending column of horizontal range --- include it.
1596 (setq max (ses-create-cell-symbol (car maxrowcol)
1597 (+ startcol colincr -1)))))))
1599 (if (/= (- (funcall field maxrowcol)
1600 (funcall field minrowcol))
1601 (- (funcall field (ses-sym-rowcol max))
1602 (funcall field (ses-sym-rowcol min))))
1603 ;; This range has changed size.
1604 (setq ses-relocate-return 'range))
1605 `(ses-range ,min ,max ,@(cl-cdddr range)))))
1607 (defun ses-relocate-all (minrow mincol rowincr colincr)
1608 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1609 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1612 (let (mycell newval xrow)
1613 (dotimes-with-progress-reporter
1614 (row ses--numrows) "Relocating formulas..."
1615 (dotimes (col ses--numcols)
1616 (setq ses-relocate-return nil
1617 mycell (ses-get-cell row col)
1618 newval (ses-relocate-formula (ses-cell-formula mycell)
1619 minrow mincol rowincr colincr)
1620 xrow (- row rowincr))
1621 (ses-set-cell row col 'formula newval)
1622 (if (eq ses-relocate-return 'range)
1623 ;; This cell contains a (ses-range X Y) where a cell has been
1624 ;; inserted or deleted in the middle of the range.
1625 (push (cons row col) reform))
1626 (if ses-relocate-return
1627 ;; This cell referred to a cell that's been deleted or is no
1628 ;; longer part of the range. We can't fix that now because
1629 ;; reference lists cells have been partially updated.
1630 (cl-pushnew (ses-create-cell-symbol row col)
1631 ses--deferred-recalc :test #'equal))
1632 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1633 minrow mincol rowincr colincr))
1634 (ses-set-cell row col 'references newval)
1635 (and (>= row minrow) (>= col mincol)
1636 (let ((sym (ses-cell-symbol row col))
1637 (xcol (- col colincr)))
1643 (ses-create-cell-symbol xrow xcol))))
1644 ;; This is a renamed cell, do not update the cell
1645 ;; name, but just update the coordinate property.
1646 (put sym 'ses-cell (cons row col))
1647 (ses-set-cell row col 'symbol
1648 (setq sym (ses-create-cell-symbol row col)))
1649 (unless (and (boundp sym) (local-variable-p sym))
1650 (set (make-local-variable sym) nil)
1651 (put sym 'ses-cell (cons row col)))))) )))
1652 ;; Relocate the cell values.
1653 (let (oldval myrow mycol xrow xcol)
1655 ((and (<= rowincr 0) (<= colincr 0))
1656 ;; Deletion of rows and/or columns.
1657 (dotimes-with-progress-reporter
1658 (row (- ses--numrows minrow)) "Relocating variables..."
1659 (setq myrow (+ row minrow))
1660 (dotimes (col (- ses--numcols mincol))
1661 (setq mycol (+ col mincol)
1662 xrow (- myrow rowincr)
1663 xcol (- mycol colincr))
1664 (let ((sym (ses-cell-symbol myrow mycol))
1665 (xsym (ses-create-cell-symbol xrow xcol)))
1666 ;; Make the value relocation only when if the cell is not
1667 ;; a renamed cell. Otherwise this is not needed.
1669 (ses-set-cell myrow mycol 'value
1670 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1671 (ses-cell-value xrow xcol)
1672 ;;Cell is off the end of the array
1673 (symbol-value xsym))))))))
1675 ((and (wholenump rowincr) (wholenump colincr))
1676 ;; Insertion of rows and/or columns. Run the loop backwards.
1677 (let ((disty (1- ses--numrows))
1678 (distx (1- ses--numcols))
1680 (dotimes-with-progress-reporter
1681 (row (- ses--numrows minrow)) "Relocating variables..."
1682 (setq myrow (- disty row))
1683 (dotimes (col (- ses--numcols mincol))
1684 (setq mycol (- distx col)
1685 xrow (- myrow rowincr)
1686 xcol (- mycol colincr))
1687 (if (or (< xrow minrow) (< xcol mincol))
1688 ;; Newly-inserted value.
1690 ;; Transfer old value.
1691 (setq oldval (ses-cell-value xrow xcol)))
1692 (ses-set-cell myrow mycol 'value oldval)))
1693 t)) ; Make testcover happy by returning non-nil here.
1695 (error "ROWINCR and COLINCR must have the same sign"))))
1696 ;; Reconstruct reference lists for cells that contain ses-ranges that have
1699 (message "Fixing ses-ranges...")
1701 (setq ses-start-time (float-time))
1703 (ses--time-check "Fixing ses-ranges... (%d left)" (length reform))
1704 (setq row (caar reform)
1706 reform (cdr reform))
1707 (ses-cell-set-formula row col (ses-cell-formula row col))))
1711 ;;----------------------------------------------------------------------------
1713 ;;----------------------------------------------------------------------------
1715 (defun ses-begin-change ()
1716 "For undo, remember point before we start changing hidden stuff."
1717 (let ((inhibit-read-only t))
1718 (insert-and-inherit "X")
1719 (delete-region (1- (point)) (point))))
1721 (defun ses-setter-with-undo (accessors newval &rest args)
1722 "Set a field/variable and record it so it can be undone.
1723 Result is non-nil if field/variable has changed."
1724 (let ((oldval (apply (car accessors) args)))
1725 (unless (equal-including-properties oldval newval)
1726 (push `(apply ses-setter-with-undo ,accessors ,oldval ,@args)
1728 (apply (cdr accessors) newval args)
1731 (defun ses-aset-with-undo (array idx newval)
1732 (ses-setter-with-undo (eval-when-compile
1734 (lambda (newval array idx) (aset array idx newval))))
1737 (defun ses-set-with-undo (sym newval)
1738 (ses-setter-with-undo
1740 (cons (lambda (sym) (if (boundp sym) (symbol-value sym) :ses--unbound))
1741 (lambda (newval sym) (if (eq newval :ses--unbound)
1743 (set sym newval)))))
1746 ;;----------------------------------------------------------------------------
1747 ;; Startup for major mode
1748 ;;----------------------------------------------------------------------------
1751 "Parse the current buffer and set up buffer-local variables.
1752 Does not execute cell formulas or print functions."
1754 ;; Read our global parameters, which should be a 3-element list.
1755 (goto-char (point-max))
1756 (search-backward ";; Local Variables:\n" nil t)
1758 (setq ses--params-marker (point-marker))
1759 (let* ((params (ignore-errors (read (current-buffer))))
1760 (params-len (safe-length params)))
1761 (or (and (>= params-len 3)
1763 (numberp (car params))
1764 (numberp (cadr params))
1765 (>= (cadr params) 0)
1766 (numberp (nth 2 params))
1767 (> (nth 2 params) 0)
1768 (or (<= params-len 3)
1769 (let ((numlocprn (nth 3 params)))
1770 (and (integerp numlocprn) (>= numlocprn 0)))))
1771 (error "Invalid SES file"))
1772 (setq ses--file-format (car params)
1773 ses--numrows (cadr params)
1774 ses--numcols (nth 2 params)
1775 ses--numlocprn (or (nth 3 params) 0))
1776 (when (= ses--file-format 1)
1777 (let (buffer-undo-list) ; This is not undoable.
1778 (ses-goto-data 'ses--header-row)
1779 (insert "(ses-header-row 0)\n")
1780 (ses-set-parameter 'ses--file-format 3)
1781 (message "Upgrading from SES-1 to SES-2 file format")))
1782 (or (<= ses--file-format 3)
1783 (error "This file needs a newer version of the SES library code"))
1784 ;; Initialize cell array.
1785 (setq ses--cells (make-vector ses--numrows nil))
1786 (dotimes (row ses--numrows)
1787 (aset ses--cells row (make-vector ses--numcols nil)))
1788 ;; initialize local printer map.
1789 (clrhash ses--local-printer-hashmap))
1791 ;; Skip over print area, which we assume is correct.
1792 (goto-char (point-min))
1793 (forward-line ses--numrows)
1794 (or (looking-at-p ses-print-data-boundary)
1795 (error "Missing marker between print and data areas"))
1797 (setq ses--data-marker (point-marker))
1798 (forward-char (1- (length ses-print-data-boundary)))
1799 ;; Initialize printer and symbol lists.
1800 (mapc #'ses-printer-record ses-standard-printer-functions)
1801 (setq ses--symbolic-formulas nil)
1803 ;; Load local printer definitions.
1804 ;; This must be loaded *BEFORE* cells and column printers because the latter
1807 (forward-line (* ses--numrows (1+ ses--numcols)))
1808 (let ((numlocprn ses--numlocprn))
1809 (setq ses--numlocprn 0)
1810 (dotimes (_ numlocprn)
1811 (let ((x (read (current-buffer))))
1812 (or (and (looking-at-p "\n")
1813 (eq (car-safe x) 'ses-local-printer)
1814 (apply #'ses--local-printer (cdr x)))
1815 (error "local printer-def error"))
1816 (setq ses--numlocprn (1+ ses--numlocprn))))))
1817 ;; Load cell definitions.
1818 (dotimes (row ses--numrows)
1819 (dotimes (col ses--numcols)
1820 (let* ((x (read (current-buffer)))
1821 (sym (car-safe (cdr-safe x))))
1822 (or (and (looking-at-p "\n")
1823 (eq (car-safe x) 'ses-cell)
1824 (ses-create-cell-variable sym row col))
1825 (error "Cell-def error"))
1826 (apply #'ses--cell (cdr x))))
1827 (or (looking-at-p "\n\n")
1828 (error "Missing blank line between rows")))
1829 ;; Skip local printer function declaration --- that were already loaded.
1830 (forward-line (+ 2 ses--numlocprn))
1831 ;; Load global parameters.
1832 (let ((widths (read (current-buffer)))
1833 (n1 (char-after (point)))
1834 (printers (read (current-buffer)))
1835 (n2 (char-after (point)))
1836 (def-printer (read (current-buffer)))
1837 (n3 (char-after (point)))
1838 (head-row (read (current-buffer)))
1839 (n4 (char-after (point))))
1840 (or (and (eq (car-safe widths) 'ses-column-widths)
1842 (eq (car-safe printers) 'ses-column-printers)
1844 (eq (car-safe def-printer) 'ses-default-printer)
1846 (eq (car-safe head-row) 'ses-header-row)
1848 (error "Invalid SES global parameters"))
1849 (1value (eval widths t))
1850 (1value (eval def-printer t))
1851 (1value (eval printers t))
1852 (1value (eval head-row t)))
1853 ;; Should be back at global-params.
1855 (or (looking-at-p ses-initial-global-parameters-re)
1856 (error "Problem with column-defs or global-params"))
1857 ;; Check for overall newline count in definitions area.
1859 (let ((start (point)))
1860 (ses-goto-data 'ses--numrows)
1861 (or (= (point) start)
1862 (error "Extraneous newlines someplace?"))))
1865 "Set up for display of only the printed cell values.
1867 Narrows the buffer to show only the print area. Gives it `read-only' and
1868 `intangible' properties. Sets up highlighting for current cell."
1870 (let ((end (point-min))
1872 (with-silent-modifications
1873 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1874 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1875 (mapc #'delete-overlay (overlays-in (point-min) (point-max)))
1876 ;; The print area is read-only (except for our special commands) and
1877 ;; uses a special keymap.
1878 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1879 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1880 ;; For the beginning of the buffer, we want the read-only and keymap
1881 ;; attributes to be inherited from the first character.
1882 (put-text-property (point-min) (1+ (point-min))
1883 ;; `cursor-intangible' shouldn't be sticky at BOB.
1884 'front-sticky '(read-only keymap))
1885 ;; Create intangible properties, which also indicate which cell the text
1887 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1888 (dotimes (col ses--numcols)
1890 sym (ses-cell-symbol row col))
1891 (unless (eq (symbol-value sym) '*skip*)
1892 ;; Include skipped cells following this one.
1893 (while (and (< col (1- ses--numcols))
1894 (eq (ses-cell-value row (1+ col)) '*skip*))
1895 (setq end (+ end (ses-col-width col) 1)
1896 ;; Beware: Modifying the iteration variable of `dotimes'
1897 ;; may or may not affect the iteration!
1899 (setq end (save-excursion
1901 (move-to-column (+ (current-column) (- end pos)
1902 (ses-col-width col)))
1904 (+ end (ses-col-width col) 1)
1907 (put-text-property pos end 'cursor-intangible sym))))))
1908 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1909 ;; because column A must be at least 1 column wide.
1910 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1911 (overlay-put ses--curcell-overlay 'face 'underline))
1913 (defun ses-cleanup ()
1914 "Cleanup when changing a buffer from SES mode to something else.
1915 Delete overlays, remove special text properties."
1917 (let ((inhibit-read-only t)
1918 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1919 ;; user "the file is modified, do you really want to make modifications
1920 ;; to this buffer", where the "modifications" refer to the irrelevant
1921 ;; set-text-properties below.
1922 (buffer-file-name nil)
1923 (was-modified (buffer-modified-p)))
1924 ;; Delete read-only, keymap, and intangible properties.
1925 (set-text-properties (point-min) (point-max) nil)
1927 (mapc #'delete-overlay (overlays-in (point-min) (point-max)))
1928 (unless was-modified
1929 (restore-buffer-modified-p nil))))
1933 "Major mode for Simple Emacs Spreadsheet.
1935 When you invoke SES in a new buffer, it is divided into cells
1936 that you can enter data into. You can navigate the cells with
1937 the arrow keys and add more cells with the tab key. The contents
1938 of these cells can be numbers, text, or Lisp expressions. (To
1939 enter text, enclose it in double quotes.)
1941 In an expression, you can use cell coordinates to refer to the
1942 contents of another cell. For example, you can sum a range of
1943 cells with `(+ A1 A2 A3)'. There are specialized functions like
1944 `ses+' (addition for ranges with empty cells), `ses-average' (for
1945 performing calculations on cells), and `ses-range' and `ses-select'
1946 \(for extracting ranges of cells).
1948 Each cell also has a print function that controls how it is
1951 Each SES buffer is divided into a print area and a data area.
1952 Normally, you can simply use SES to look at and manipulate the print
1953 area, and let SES manage the data area outside the visible region.
1955 See \"ses-example.ses\" (in `data-directory') for an example
1956 spreadsheet, and the Info node `(ses)Top.'
1958 In the following, note the separate keymaps for cell editing mode
1959 and print mode specifications. Key definitions:
1962 These key definitions are active only in the print area (the visible
1964 \\{ses-mode-print-map}
1965 These are active only in the minibuffer, when entering or editing a
1967 \\{ses-mode-edit-map}"
1969 (unless (and (boundp 'ses--deferred-narrow)
1970 (eq ses--deferred-narrow 'ses-mode))
1971 (kill-all-local-variables)
1973 (setq major-mode 'ses-mode
1975 next-line-add-newlines nil
1977 ;; SES deliberately puts lots of trailing whitespace in its buffer.
1978 show-trailing-whitespace nil
1979 ;; Cell ranges do not work reasonably without this.
1980 transient-mark-mode t
1981 ;; Not to use tab characters for safe (tabs may do bad for column
1983 indent-tabs-mode nil)
1984 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1985 ;; This makes revert impossible if the buffer is read-only.
1986 ;; (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1987 (setq header-line-format '(:eval (progn
1988 (when (/= (window-hscroll)
1989 ses--header-hscroll)
1990 ;; Reset ses--header-hscroll first,
1991 ;; to avoid recursion problems when
1992 ;; debugging ses-create-header-string
1993 (setq ses--header-hscroll
1995 (ses-create-header-string))
1996 ses--header-string)))
1997 (setq-local mode-line-process '(:eval (ses--mode-line-process)))
1998 (add-hook 'pre-redisplay-functions #'ses--cursor-sensor-highlight
1999 ;; Highlight the cell after moving cursor out of intangible.
2001 (cursor-intangible-mode 1)
2002 (let ((was-empty (zerop (buffer-size)))
2003 (was-modified (buffer-modified-p)))
2006 ;; Initialize buffer to contain one cell, for now.
2007 (insert ses-initial-file-contents))
2011 (unless (equal ses-initial-default-printer
2012 (1value ses--default-printer))
2013 (1value (ses-read-default-printer ses-initial-default-printer)))
2014 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
2015 (1value (ses-set-column-width 0 ses-initial-column-width)))
2017 (if (> (car ses-initial-size) (1value ses--numrows))
2018 (1value (ses-insert-row (1- (car ses-initial-size)))))
2019 (if (> (cdr ses-initial-size) (1value ses--numcols))
2020 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
2022 (restore-buffer-modified-p was-modified)
2023 (buffer-disable-undo)
2024 (buffer-enable-undo)
2025 (goto-char (point-min))))
2026 (use-local-map ses-mode-map)
2027 ;; Set the deferred narrowing flag (we can't narrow until after
2028 ;; after-find-file completes). If .ses is on the auto-load alist and the
2029 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
2030 ;; special flag to detect this (will be reset by ses-command-hook). For
2031 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
2032 ;; so use an idle timer to make sure.
2033 (setq ses--deferred-narrow 'ses-mode)
2034 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
2035 (run-with-idle-timer 0.01 nil 'ses-command-hook)
2036 (run-mode-hooks 'ses-mode-hook)))
2038 (put 'ses-mode 'mode-class 'special)
2040 (defun ses-command-hook ()
2041 "Invoked from `post-command-hook'. If point has moved to a different cell,
2042 moves the underlining overlay. Performs any recalculations or cell-data
2043 writes that have been deferred. If buffer-narrowing has been deferred,
2044 narrows the buffer now."
2046 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
2047 (when ses--deferred-recalc
2048 ;; We reset the deferred list before starting on the recalc --- in
2049 ;; case of error, we don't want to retry the recalc after every
2051 (ses-initialize-Dijkstra-attempt)
2052 (let ((old ses--deferred-recalc))
2053 (setq ses--deferred-recalc nil)
2054 (ses-update-cells old)))
2055 (when ses--deferred-write
2056 ;; We don't reset the deferred list before starting --- the most
2057 ;; likely error is keyboard-quit, and we do want to keep trying these
2058 ;; writes after a quit.
2060 (push '(apply ses-widen) buffer-undo-list))
2061 (when ses--deferred-narrow
2062 ;; We're not allowed to narrow the buffer until after-find-file has
2063 ;; read the local variables at the end of the file. Now it's safe to
2064 ;; do the narrowing.
2065 (narrow-to-region (point-min) ses--data-marker)
2066 (setq ses--deferred-narrow nil)))
2067 ;; Prevent errors in this post-command-hook from silently erasing the hook!
2069 (unless executing-kbd-macro
2071 (message "%s" (error-message-string err))))
2072 nil) ; Make coverage-tester happy.
2074 (defun ses--mode-line-process ()
2075 (let ((cmlp (window-parameter nil 'ses--mode-line-process))
2076 (curcell (ses--curcell (window-point))))
2077 (if (equal curcell (car cmlp))
2082 ((atom curcell) (list " cell " (symbol-name curcell)))
2085 (symbol-name (car curcell))
2087 (symbol-name (cdr curcell)))))))
2088 (set-window-parameter nil 'ses--mode-line-process (cons curcell mlp))
2091 (defun ses--cursor-sensor-highlight (window)
2092 (let ((curcell (ses--curcell))
2093 (ol (window-parameter window 'ses--curcell-overlay)))
2095 (setq ol (make-overlay (point) (point)))
2096 (overlay-put ol 'window window)
2097 (overlay-put ol 'face 'underline)
2098 (set-window-parameter window 'ses--curcell-overlay ol))
2099 ;; Use underline overlay for single-cells only, turn off otherwise.
2102 (let* ((pos (window-point window))
2103 (next (next-single-property-change pos 'cursor-intangible)))
2104 (move-overlay ol pos (1- next))))))
2106 (defun ses-create-header-string ()
2107 "Set up `ses--header-string' as the buffer's header line.
2108 Based on the current set of columns and `window-hscroll' position."
2109 (let ((totwidth (- (window-hscroll)))
2111 ;; Leave room for the left-side fringe and scrollbar.
2112 (push (propertize " " 'display '((space :align-to 0))) result)
2113 (dotimes (col ses--numcols)
2114 (setq width (ses-col-width col)
2115 totwidth (+ totwidth width 1))
2117 ;; Scrolled so intercolumn space is leftmost.
2119 (when (> totwidth 1)
2120 (if (> ses--header-row 0)
2122 (ses-goto-print (1- ses--header-row) col)
2123 (setq x (buffer-substring-no-properties (point)
2125 ;; Strip trailing space.
2126 (if (string-match "[ \t]+\\'" x)
2127 (setq x (substring x 0 (match-beginning 0))))
2128 ;; Cut off excess text.
2129 (if (>= (length x) totwidth)
2130 (setq x (substring x 0 (- totwidth -1)))))
2131 (setq x (ses-column-letter col)))
2132 (push (propertize x 'face ses-box-prop) result)
2133 (push (propertize "."
2134 'display `((space :align-to ,(1- totwidth)))
2137 ;; Allow the following space to be squished to make room for the 3-D box
2138 ;; Coverage test ignores properties, thinks this is always a space!
2139 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2141 (if (> ses--header-row 0)
2142 (push (propertize (format " [row %d]" ses--header-row)
2143 'display '((height (- 1))))
2145 (setq ses--header-string (apply #'concat (nreverse result)))))
2148 ;;----------------------------------------------------------------------------
2149 ;; Redisplay and recalculation
2150 ;;----------------------------------------------------------------------------
2152 (defun ses-jump (sym)
2153 "Move point to cell SYM."
2154 (interactive "SJump to cell: ")
2155 (let ((rowcol (ses-sym-rowcol sym)))
2156 (or rowcol (error "Invalid cell name"))
2157 (if (eq (symbol-value sym) '*skip*)
2158 (error "Cell is covered by preceding cell"))
2159 (ses-goto-print (car rowcol) (cdr rowcol))))
2161 (defun ses-jump-safe (cell)
2162 "Like `ses-jump', but no error if invalid cell."
2166 (defun ses-reprint-all (&optional nonarrow)
2167 "Recreate the display area. Calls all printer functions. Narrows to
2168 print area if NONARROW is nil."
2172 (setq ses--deferred-narrow t))
2173 (let ((startcell (ses--cell-at-pos (point)))
2174 (inhibit-read-only t))
2176 (goto-char (point-min))
2177 (search-forward ses-print-data-boundary)
2178 (backward-char (length ses-print-data-boundary))
2179 (delete-region (point-min) (point))
2180 ;; Insert all blank lines before printing anything, so ses-print-cell can
2181 ;; find the data area when inserting or deleting *skip* values for cells.
2182 (dotimes (_ ses--numrows)
2183 (insert-and-inherit ses--blank-line))
2184 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2185 (if (eq (ses-cell-value row 0) '*skip*)
2186 ;; Column deletion left a dangling skip.
2187 (ses-set-cell row 0 'value nil))
2188 (dotimes (col ses--numcols)
2189 (ses-print-cell row col))
2190 (beginning-of-line 2))
2191 (ses-jump-safe startcell)))
2193 (defun ses-initialize-Dijkstra-attempt ()
2194 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2195 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2197 ;; These functions use the variables 'row' and 'col' that are dynamically bound
2198 ;; by ses-print-cell. We define these variables at compile-time to make the
2205 (defun ses-recalculate-cell ()
2206 "Recalculate and reprint the current cell or range.
2208 For an individual cell, shows the error if the formula or printer
2209 signals one, or otherwise shows the cell's complete value. For a range, the
2210 cells are recalculated in \"natural\" order, so cells that other cells refer
2211 to are recalculated first."
2213 (ses-check-curcell 'range)
2215 (ses-initialize-Dijkstra-attempt)
2216 (let (sig cur-rowcol)
2217 (setq ses-start-time (float-time))
2218 (if (atom ses--curcell)
2220 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2222 (setf (ses-cell-property :ses-Dijkstra-attempt
2225 (cons ses--Dijkstra-attempt-nb 0))
2226 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2227 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2228 (cdr cur-rowcol)))))
2229 ;; First, recalculate all cells that don't refer to other cells and
2230 ;; produce a list of cells with references.
2231 (ses-dorange ses--curcell
2232 (ses--time-check "Recalculating... %s" (ses-cell-symbol row col))
2235 ;; The t causes an error if the cell has references. If no
2236 ;; references, the t will be the result value.
2237 (1value (ses-formula-references (ses-cell-formula row col) t))
2238 (setf (ses-cell-property :ses-Dijkstra-attempt row col)
2239 (cons ses--Dijkstra-attempt-nb 0))
2240 (when (setq sig (ses-calculate-cell row col t))
2241 (nconc sig (list (ses-cell-symbol row col)))))
2242 (wrong-type-argument
2243 ;; The formula contains a reference.
2244 (cl-pushnew (ses-cell-symbol row col) ses--deferred-recalc
2246 ;; Do the update now, so we can force recalculation.
2247 (let ((x ses--deferred-recalc))
2248 (setq ses--deferred-recalc nil)
2249 (condition-case hold
2250 (ses-update-cells x t)
2251 (error (setq sig hold))))
2254 (message "%s" (error-message-string sig)))
2255 ((consp ses--curcell)
2258 (princ (symbol-value ses--curcell))))))
2260 (defun ses-recalculate-all ()
2261 "Recalculate and reprint all cells."
2263 (let ((startcell (ses--cell-at-pos (point)))
2264 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2265 (1- ses--numcols)))))
2266 (ses-recalculate-cell)
2267 (ses-jump-safe startcell)))
2269 (defun ses-truncate-cell ()
2270 "Reprint current cell, but without spillover into any following blank cells."
2273 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2276 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
2277 (eq (ses-cell-value row (1+ col)) '*skip*))
2278 ;; This cell has spill-over. We'll momentarily pretend the following cell
2281 (list (ses-cell-symbol row (1+ col)))
2283 (ses-print-cell row col))
2284 ;; Now remove the *skip*. ses-print-cell is always nil here.
2285 (ses-set-cell row (1+ col) 'value nil)
2286 (1value (ses-print-cell row (1+ col))))))
2288 (defun ses-reconstruct-all ()
2289 "Reconstruct buffer based on cell data stored in Emacs variables."
2292 ;;Reconstruct reference lists.
2294 ;;Delete old reference lists
2295 (dotimes-with-progress-reporter
2296 (row ses--numrows) "Deleting references..."
2297 (dotimes (col ses--numcols)
2298 (ses-set-cell row col 'references nil)))
2299 ;;Create new reference lists
2300 (dotimes-with-progress-reporter
2301 (row ses--numrows) "Computing references..."
2302 (dotimes (col ses--numcols)
2303 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2304 (setq x (ses-sym-rowcol ref)
2307 (ses-set-cell yrow ycol 'references
2308 (cons (ses-cell-symbol row col)
2309 (ses-cell-references yrow ycol)))))))
2310 ;; Delete everything and reconstruct basic data area.
2312 (let ((inhibit-read-only t))
2313 (goto-char (point-max))
2314 (if (search-backward ";; Local Variables:\n" nil t)
2315 (delete-region (point-min) (point))
2316 ;; Buffer is quite screwed up --- can't even save the user-specified
2318 (delete-region (point-min) (point-max))
2319 (insert ses-initial-file-trailer)
2320 (goto-char (point-min)))
2321 ;; Create a blank display area.
2322 (dotimes (_ ses--numrows)
2323 (insert ses--blank-line))
2324 (insert ses-print-data-boundary)
2325 (backward-char (1- (length ses-print-data-boundary)))
2326 (setq ses--data-marker (point-marker))
2327 (forward-char (1- (length ses-print-data-boundary)))
2328 ;; Placeholders for cell data.
2329 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2330 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
2332 (insert ses-initial-global-parameters)
2333 (backward-char (1- (length ses-initial-global-parameters)))
2334 (setq ses--params-marker (point-marker))
2335 (forward-char (1- (length ses-initial-global-parameters))))
2336 (ses-set-parameter 'ses--col-widths ses--col-widths)
2337 (ses-set-parameter 'ses--col-printers ses--col-printers)
2338 (ses-set-parameter 'ses--default-printer ses--default-printer)
2339 (ses-set-parameter 'ses--header-row ses--header-row)
2340 (ses-set-parameter 'ses--numrows ses--numrows)
2341 (ses-set-parameter 'ses--numcols ses--numcols)
2342 ;;Keep our old narrowing
2344 (ses-recalculate-all)
2345 (goto-char (point-min)))
2348 ;;----------------------------------------------------------------------------
2349 ;; Input of cell formulas
2350 ;;----------------------------------------------------------------------------
2352 (defun ses-edit-cell (row col newval)
2353 "Display current cell contents in minibuffer, for editing. Returns nil if
2354 cell formula was unsafe and user declined confirmation."
2357 (barf-if-buffer-read-only)
2359 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2362 (formula (ses-cell-formula row col))
2364 (if (eq (car-safe formula) 'ses-safe-formula)
2365 (setq formula (cadr formula)))
2366 (if (eq (car-safe formula) 'quote)
2367 (setq initial (format "'%S" (cadr formula)))
2368 (setq initial (prin1-to-string formula)))
2369 (if (stringp formula)
2370 ;; Position cursor inside close-quote.
2371 (setq initial (cons initial (length initial))))
2373 (read-from-minibuffer (format "Cell %s: " ses--curcell)
2376 t ; Convert to Lisp object.
2377 'ses-read-cell-history)))))
2378 (when (ses-warn-unsafe newval 'unsafep)
2380 (ses-cell-set-formula row col newval)
2383 (defun ses-read-cell (row col newval)
2384 "Self-insert for initial character of cell function."
2386 (let* ((initial (this-command-keys))
2387 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2388 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
2389 (barf-if-buffer-read-only)
2392 (if (equal initial "\"")
2394 (if (not (stringp curval)) (setq curval nil))
2395 (read-string (if curval
2396 (format "String Cell %s (default %s): "
2397 ses--curcell curval)
2398 (format "String Cell %s: " ses--curcell))
2399 nil 'ses-read-string-history curval))
2400 (read-from-minibuffer
2401 (format "Cell %s: " ses--curcell)
2402 (cons (if (equal initial "(") "()" initial) 2)
2404 t ; Convert to Lisp object.
2405 'ses-read-cell-history
2406 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2409 (when (ses-edit-cell row col newval)
2410 (ses-command-hook) ; Update cell widths before movement.
2411 (dolist (x ses-after-entry-functions)
2414 (defun ses-read-symbol (row col symb)
2415 "Self-insert for a symbol as a cell formula. The set of all symbols that
2416 have been used as formulas in this spreadsheet is available for completions."
2418 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2420 (barf-if-buffer-read-only)
2421 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2422 ses--symbolic-formulas))
2425 (if (string= newval "")
2426 nil ; Don't create zero-length symbols!
2427 (list 'quote (intern newval))))))
2428 (when (ses-edit-cell row col symb)
2429 (ses-command-hook) ; Update cell widths before movement.
2430 (dolist (x ses-after-entry-functions)
2433 (defun ses-clear-cell-forward (count)
2434 "Delete formula and printer for current cell and then move to next cell.
2435 With prefix, deletes several cells."
2438 (1value (ses-clear-cell-backward (- count)))
2443 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2444 (or rowcol (signal 'end-of-buffer nil))
2445 (ses-clear-cell (car rowcol) (cdr rowcol)))
2448 (defun ses-clear-cell-backward (count)
2449 "Move to previous cell and then delete it. With prefix, deletes several
2453 (1value (ses-clear-cell-forward (- count)))
2454 (ses-check-curcell 'end)
2457 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
2459 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2460 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2463 ;;----------------------------------------------------------------------------
2464 ;; Input of cell-printer functions
2465 ;;----------------------------------------------------------------------------
2467 (defun ses-read-printer (prompt default)
2468 "Common code for functions `ses-read-cell-printer', `ses-read-column-printer',
2469 `ses-read-default-printer' and `ses-define-local-printer'.
2470 PROMPT should end with \": \". Result is t if operation was
2472 (barf-if-buffer-read-only)
2475 (setq prompt (format "%s (default %S): "
2476 (substring prompt 0 -2)
2478 (let ((new (read-from-minibuffer prompt
2479 nil ; Initial contents.
2481 t ; Evaluate the result.
2482 'ses-read-printer-history
2483 (prin1-to-string default))))
2484 (if (equal new default)
2485 ;; User changed mind, decided not to change printer.
2487 (ses-printer-validate new)
2490 (stringp (car-safe new))
2491 (and (symbolp new) (gethash new ses--local-printer-hashmap))
2492 (ses-warn-unsafe new 'unsafep-function)
2496 (defun ses-read-cell-printer (newval)
2497 "Set the printer function for the current cell or range.
2499 A printer function is either a string (a format control-string with one
2500 %-sequence -- result from format will be right-justified), or a list of one
2501 string (result from format will be left-justified), or a lambda-expression of
2502 one argument, or a symbol that names a function of one argument. In the
2503 latter two cases, the function's result should be either a string (will be
2504 right-justified) or a list of one string (will be left-justified)."
2507 (ses-check-curcell 'range)
2508 ;;Default is none if not all cells in range have same printer
2509 (catch 'ses-read-cell-printer
2510 (ses-dorange ses--curcell
2511 (let ((x (ses-cell-printer row col)))
2512 (if (eq (car-safe x) 'ses-safe-printer)
2516 (unless (equal default x)
2517 ;;Range contains differing printer functions
2519 (throw 'ses-read-cell-printer t))))))
2520 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2522 (unless (eq newval t)
2524 (ses-dorange ses--curcell
2525 (ses-set-cell row col 'printer newval)
2526 (ses-print-cell row col))))
2528 (defun ses-read-column-printer (col newval)
2529 "Set the printer function for the current column.
2530 See `ses-read-cell-printer' for input forms."
2532 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2534 (list col (ses-read-printer (format "Column %s printer: "
2535 (ses-column-letter col))
2536 (ses-col-printer col)))))
2538 (unless (eq newval t)
2540 (ses-set-parameter 'ses--col-printers newval col)
2542 (dotimes (row ses--numrows)
2543 (ses-print-cell row col)))))
2545 (defun ses-read-default-printer (newval)
2546 "Set the default printer function for cells that have no other.
2547 See `ses-read-cell-printer' for input forms."
2549 (list (ses-read-printer "Default printer: " ses--default-printer)))
2550 (unless (eq newval t)
2552 (ses-set-parameter 'ses--default-printer newval)
2553 (ses-reprint-all t)))
2556 ;;----------------------------------------------------------------------------
2557 ;; Spreadsheet size adjustments
2558 ;;----------------------------------------------------------------------------
2560 (defun ses-insert-row (count)
2561 "Insert a new row before the current one.
2562 With prefix, insert COUNT rows before current one."
2564 (ses-check-curcell 'end)
2565 (or (> count 0) (signal 'args-out-of-range nil))
2567 (let ((inhibit-quit t)
2568 (inhibit-read-only t)
2569 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2571 ;;Create a new set of cell-variables
2572 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2573 0 (1- ses--numcols))
2574 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2576 (ses-goto-print row 0)
2577 (dotimes-with-progress-reporter (x count) "Inserting row..."
2578 ;;Create a row of empty cells. The `symbol' fields will be set by
2579 ;;the call to ses-relocate-all.
2580 (setq newrow (make-vector ses--numcols nil))
2581 (dotimes (col ses--numcols)
2582 (aset newrow col (ses-make-cell)))
2583 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2584 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2585 (insert ses--blank-line))
2586 ;;Insert empty lines in cell data area (will be replaced by
2588 (ses-goto-data row 0)
2589 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2590 (ses-relocate-all row 0 count 0)
2591 ;;If any cell printers insert constant text, insert that text
2593 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2594 (global (ses-call-printer ses--default-printer)))
2595 (if (or (> (length cols) 0) (> (length global) 0))
2597 (dotimes (col ses--numcols)
2598 ;;These cells are always nil, only constant formatting printed
2599 (1value (ses-print-cell (+ x row) col))))))
2600 (when (> ses--header-row row)
2601 ;;Inserting before header
2602 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2603 (ses-reset-header-string)))
2604 ;;Reconstruct text attributes
2607 (push '(apply ses-widen) buffer-undo-list)
2608 ;;Return to current cell
2610 (ses-jump-safe ses--curcell)
2611 (ses-goto-print (1- ses--numrows) 0)))
2613 (defun ses-delete-row (count)
2614 "Delete the current row.
2615 With prefix, deletes COUNT rows starting from the current one."
2618 (or (> count 0) (signal 'args-out-of-range nil))
2619 (let ((inhibit-quit t)
2620 (inhibit-read-only t)
2621 (row (car (ses-sym-rowcol ses--curcell))))
2622 (setq count (min count (- ses--numrows row)))
2624 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2625 ;;Delete lines from print area
2626 (ses-goto-print row 0)
2627 (ses-delete-line count)
2628 ;;Delete lines from cell data area
2629 (ses-goto-data row 0)
2630 (ses-delete-line (* count (1+ ses--numcols)))
2631 ;;Relocate variables and formulas
2632 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2633 (ses-relocate-all row 0 (- count) 0)
2634 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2635 0 (1- ses--numcols))
2636 (when (> ses--header-row row)
2637 (if (<= ses--header-row (+ row count))
2638 ;;Deleting the header row
2639 (ses-set-parameter 'ses--header-row 0)
2640 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2641 (ses-reset-header-string)))
2642 ;;Reconstruct attributes
2645 (push '(apply ses-widen) buffer-undo-list)
2646 (ses-jump-safe ses--curcell))
2648 (defun ses-insert-column (count &optional col width printer)
2649 "Insert a new column before COL (default is the current one).
2650 With prefix, insert COUNT columns before current one.
2651 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2652 \(otherwise they're taken from the current column)."
2655 (or (> count 0) (signal 'args-out-of-range nil))
2657 (setq col (cdr (ses-sym-rowcol ses--curcell))
2658 width (ses-col-width col)
2659 printer (ses-col-printer col)))
2661 (let ((inhibit-quit t)
2662 (inhibit-read-only t)
2663 (widths ses--col-widths)
2664 (printers ses--col-printers)
2666 ;;Create a new set of cell-variables
2667 (ses-create-cell-variable-range 0 (1- ses--numrows)
2668 ses--numcols (+ ses--numcols count -1))
2669 ;;Insert each column.
2670 (dotimes-with-progress-reporter (x count) "Inserting column..."
2671 ;;Create a column of empty cells. The `symbol' fields will be set by
2672 ;;the call to ses-relocate-all.
2673 (ses-adjust-print-width col (1+ width))
2674 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2675 (dotimes (row ses--numrows)
2676 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2677 ;;Inserting in the middle of a spill-over
2679 (ses-aset-with-undo ses--cells row
2680 (ses-vector-insert (aref ses--cells row)
2681 col (ses-make-cell)))
2682 ;;Insert empty lines in cell data area (will be replaced by
2684 (ses-goto-data row col)
2686 ;; Insert column width and printer.
2687 (setq widths (ses-vector-insert widths col width)
2688 printers (ses-vector-insert printers col printer)))
2689 (ses-set-parameter 'ses--col-widths widths)
2690 (ses-set-parameter 'ses--col-printers printers)
2691 (ses-reset-header-string)
2692 (ses-relocate-all 0 col 0 count)
2695 (when (or (> (length (ses-call-printer printer)) 0)
2696 (> (length (ses-call-printer ses--default-printer)) 0))
2697 ;; Either column printer or global printer inserts some constant text.
2698 ;; Reprint the new columns to insert that text.
2699 (dotimes (x ses--numrows)
2701 ;; Always nil here --- this is a blank column.
2702 (1value (ses-print-cell-new-width x (+ y col))))))
2704 (ses-jump-safe ses--curcell))
2706 (defun ses-delete-column (count)
2707 "Delete the current column.
2708 With prefix, deletes COUNT columns starting from the current one."
2711 (or (> count 0) (signal 'args-out-of-range nil))
2712 (let ((inhibit-quit t)
2713 (inhibit-read-only t)
2714 (rowcol (ses-sym-rowcol ses--curcell))
2716 col origrow has-skip)
2717 (setq origrow (car rowcol)
2719 count (min count (- ses--numcols col)))
2720 (if (= count ses--numcols)
2721 (error "Can't delete all columns!"))
2722 ;;Determine width of column(s) being deleted
2724 (setq width (+ width (ses-col-width (+ col x)) 1)))
2726 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2727 (ses-adjust-print-width col (- width))
2728 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2729 ;;Delete lines from cell data area
2730 (ses-goto-data row col)
2731 (ses-delete-line count)
2732 ;;Delete cells. Check if deletion area begins or ends with a skip.
2733 (if (or (eq (ses-cell-value row col) '*skip*)
2734 (and (< col ses--numcols)
2735 (eq (ses-cell-value row (+ col count)) '*skip*)))
2737 (ses-aset-with-undo ses--cells row
2738 (ses-vector-delete (aref ses--cells row) col count)))
2740 (ses-set-parameter 'ses--col-widths
2741 (ses-vector-delete ses--col-widths col count))
2742 (ses-set-parameter 'ses--col-printers
2743 (ses-vector-delete ses--col-printers col count))
2744 (ses-reset-header-string)
2745 ;;Relocate variables and formulas
2746 (ses-relocate-all 0 col 0 (- count))
2747 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2748 ses--numcols (+ ses--numcols count -1))
2752 (if (>= col ses--numcols)
2753 (setq col (1- col)))
2754 (ses-goto-print origrow col)))
2756 (defun ses-forward-or-insert (&optional count)
2757 "Move to next cell in row, or inserts a new cell if already in last one, or
2758 inserts a new row if at bottom of print area. Repeat COUNT times."
2760 (ses-check-curcell 'end)
2761 (setq deactivate-mark t) ; Doesn't combine well with ranges.
2764 (if (not ses--curcell)
2765 (progn ; At bottom of print area.
2766 (barf-if-buffer-read-only)
2768 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2770 (char-before (next-single-property-change (point)
2771 'cursor-intangible)))
2772 ;; We're already in last nonskipped cell on line. Need to create a
2774 (barf-if-buffer-read-only)
2775 (ses-insert-column (- count x)
2778 (ses-col-printer col)))))
2781 (defun ses-append-row-jump-first-column ()
2782 "Insert a new row after current one and jump to its first column."
2786 (beginning-of-line 2)
2790 (defun ses-set-column-width (col newwidth)
2791 "Set the width of the current column."
2793 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2794 (barf-if-buffer-read-only)
2796 (if current-prefix-arg
2797 (prefix-numeric-value current-prefix-arg)
2798 (read-from-minibuffer (format "Column %s width (default %d): "
2799 (ses-column-letter col)
2800 (ses-col-width col))
2801 nil ; No initial contents.
2802 nil ; No override keymap.
2803 t ; Convert to Lisp object.
2806 (ses-col-width col))))))) ; Default value.
2808 (error "Invalid column width"))
2810 (ses-reset-header-string)
2812 (let ((inhibit-quit t))
2813 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2814 (ses-set-parameter 'ses--col-widths newwidth col))
2815 (dotimes (row ses--numrows)
2816 (ses-print-cell-new-width row col))))
2819 ;;----------------------------------------------------------------------------
2820 ;; Cut and paste, import and export
2821 ;;----------------------------------------------------------------------------
2823 (defun ses--advice-copy-region-as-kill (crak-fun beg end &rest args)
2824 ;; FIXME: Why doesn't it make sense to copy read-only or
2825 ;; intangible attributes? They're removed upon yank!
2826 "It doesn't make sense to copy read-only or intangible attributes into the
2827 kill ring. It probably doesn't make sense to copy keymap properties.
2828 We'll assume copying front-sticky properties doesn't make sense, either.
2830 This advice also includes some SES-specific code because otherwise it's too
2831 hard to override how mouse-1 works."
2836 (if (not (and (derived-mode-p 'ses-mode)
2837 (eq (get-text-property beg 'read-only) 'ses)
2838 (eq (get-text-property (1- end) 'read-only) 'ses)))
2839 (apply crak-fun beg end args) ; Normal copy-region-as-kill.
2840 (kill-new (ses-copy-region beg end))
2841 (if transient-mark-mode
2842 (setq deactivate-mark t))
2844 (advice-add 'copy-region-as-kill :around #'ses--advice-copy-region-as-kill)
2846 (defun ses-copy-region (beg end)
2847 "Treat the region as rectangular. Convert the intangible attributes to
2848 SES attributes recording the contents of the cell as of the time of copying."
2849 (when (= end ses--data-marker)
2850 ;;Avoid overflow situation
2851 (setq end (1- ses--data-marker)))
2852 (let* ((x (mapconcat #'ses-copy-region-helper
2853 (extract-rectangle beg (1- end)) "\n")))
2854 (remove-text-properties 0 (length x)
2862 (defun ses-copy-region-helper (line)
2863 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2864 external form by attaching to each print cell a 'ses attribute that records
2865 the corresponding data cell."
2866 (or (> (length line) 1)
2867 (error "Empty range"))
2868 (let ((inhibit-read-only t)
2870 mycell next sym rowcol)
2872 (setq sym (ses--cell-at-pos pos line)
2873 next (next-single-property-change pos 'cursor-intangible line)
2874 rowcol (ses-sym-rowcol sym)
2875 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2876 (put-text-property pos (or next (length line))
2878 (list (ses-cell-symbol mycell)
2879 (ses-cell-formula mycell)
2880 (ses-cell-printer mycell))
2885 (defun ses-kill-override (beg end)
2886 "Generic override for any commands that kill text.
2887 We clear the killed cells instead of deleting them."
2889 (ses-check-curcell 'needrange)
2890 ;; For some reason, the text-read-only error is not caught by `delete-region',
2891 ;; so we have to use subterfuge.
2892 (let ((buffer-read-only t))
2893 (1value (condition-case nil
2894 (noreturn (funcall (lookup-key (current-global-map)
2895 (this-command-keys))
2897 (buffer-read-only nil)))) ; The expected error.
2898 ;; Because the buffer was marked read-only, the kill command turned itself
2899 ;; into a copy. Now we clear the cells or signal the error. First we check
2900 ;; whether the buffer really is read-only.
2901 (barf-if-buffer-read-only)
2903 (ses-dorange ses--curcell
2904 (ses-clear-cell row col))
2905 (ses-jump (car ses--curcell)))
2907 (defun ses--advice-yank (yank-fun &optional arg &rest args)
2908 "In SES mode, the yanked text is inserted as cells.
2910 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2911 SES buffer), the formulas and print functions are restored for the cells. If
2912 the text contains tabs, this is an insertion of tab-separated formulas.
2913 Otherwise the text is inserted as the formula for the current cell.
2915 When inserting cells, the formulas are usually relocated to keep the same
2916 relative references to neighboring cells. This is best if the formulas
2917 generally refer to other cells within the yanked text. You can use the C-u
2918 prefix to specify insertion without relocation, which is best when the
2919 formulas refer to cells outside the yanked text.
2921 When inserting formulas, the text is treated as a string constant if it doesn't
2922 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2923 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2925 (if (not (and (derived-mode-p 'ses-mode)
2926 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2927 (apply yank-fun arg args) ; Normal non-SES yank.
2928 (ses-check-curcell 'end)
2930 (let ((text (current-kill (cond
2934 (or (ses-yank-cells text arg)
2935 (ses-yank-tsf text arg)
2936 (ses-yank-one (ses-yank-resize 1 1)
2939 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2940 ;; Just one cell --- delete final tab or newline.
2944 (exchange-point-and-mark))))
2945 (advice-add 'yank :around #'ses--advice-yank)
2947 (defun ses-yank-pop (arg)
2948 "Replace just-yanked stretch of killed text with a different stretch.
2949 This command is allowed only immediately after a `yank' or a `yank-pop',
2950 when the region contains a stretch of reinserted previously-killed text.
2951 We replace it with a different stretch of killed text.
2952 Unlike standard `yank-pop', this function uses `undo' to delete the
2953 previous insertion."
2955 (or (eq last-command 'yank)
2956 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2958 (noreturn (error "Previous command was not a yank")))
2961 (yank (1+ (or arg 1)))
2962 (setq this-command 'yank))
2964 (defun ses-yank-cells (text arg)
2965 "If the TEXT has a proper set of 'ses attributes, insert the text as
2966 cells, else return nil. The cells are reprinted--the supplied text is
2967 ignored because the column widths, default printer, etc. at yank time might
2968 be different from those at kill-time. ARG is a list to indicate that
2969 formulas are to be inserted without relocation."
2970 (let ((first (get-text-property 0 'ses text))
2971 (last (get-text-property (1- (length text)) 'ses text)))
2972 (when (and first last) ;;Otherwise not proper set of attributes
2973 (setq first (ses-sym-rowcol (car first))
2974 last (ses-sym-rowcol (car last)))
2975 (let* ((needrows (- (car last) (car first) -1))
2976 (needcols (- (cdr last) (cdr first) -1))
2977 (rowcol (ses-yank-resize needrows needcols))
2978 (rowincr (- (car rowcol) (car first)))
2979 (colincr (- (cdr rowcol) (cdr first)))
2982 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2983 (setq myrow (+ row (car rowcol)))
2984 (dotimes (col needcols)
2985 (setq mycol (+ col (cdr rowcol))
2986 last (get-text-property pos 'ses text)
2987 pos (next-single-property-change pos 'ses text)
2988 x (ses-sym-rowcol (car last)))
2990 ;; Newline --- all remaining cells on row are skipped.
2991 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2992 last (list nil nil nil)
2994 (if (/= (car x) (- myrow rowincr))
2995 (error "Cell row error"))
2996 (if (< (- mycol colincr) (cdr x))
2997 ;; Some columns were skipped.
2998 (let ((oldcol mycol))
2999 (while (< (- mycol colincr) (cdr x))
3000 (ses-clear-cell myrow mycol)
3003 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
3004 (when (car last) ; Skip this for *skip* cells.
3005 (setq x (nth 2 last))
3006 (unless (equal x (ses-cell-printer myrow mycol))
3009 (eq (car-safe x) 'ses-safe-printer)
3010 (setq x `(ses-safe-printer ,x)))
3011 (ses-set-cell myrow mycol 'printer x))
3012 (setq x (cadr last))
3014 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
3016 (eq (car-safe x) 'ses-safe-formula)
3017 (setq x `(ses-safe-formula ,x)))
3018 (ses-cell-set-formula myrow mycol x)))
3020 (if (get-text-property pos 'ses text)
3021 (error "Missing newline between rows"))
3022 (setq pos (next-single-property-change pos 'ses text))))
3025 (defun ses-yank-one (rowcol text from to arg)
3026 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
3027 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
3028 (let ((val (condition-case nil
3029 (read-from-string text from to)
3030 (error (cons nil from)))))
3032 ((< (cdr val) (or to (length text)))
3033 ;; Invalid sexp --- leave it as a string.
3034 (setq val (substring text from to)))
3035 ((and (car val) (symbolp (car val)))
3036 (setq val (if (consp arg)
3037 (list 'quote (car val)) ; Keep symbol.
3038 (substring text from to)))) ; Treat symbol as text.
3040 (setq val (car val))))
3041 (let ((row (car rowcol))
3044 (setq val `(ses-safe-formula ,val)))
3045 (ses-cell-set-formula row col val))))
3047 (defun ses-yank-tsf (text arg)
3048 "If TEXT contains tabs and/or newlines, treat the tabs as
3049 column-separators and the newlines as row-separators and insert the text as
3050 cell formulas--else return nil. Treat plain symbols as strings unless ARG
3051 is a list. Ignore a final newline."
3052 (if (or (not (string-match "[\t\n]" text))
3053 (= (match-end 0) (length text)))
3056 (if (/= (aref text (1- (length text))) ?\n)
3057 (setq text (concat text "\n")))
3063 ;;Find all the tabs and newlines
3064 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
3066 (setq cols (1+ cols))
3067 (when (eq (aref text pos) ?\n)
3069 (setq needcols cols)
3070 (or (= needcols cols)
3071 (error "Inconsistent row lengths")))
3073 needrows (1+ needrows))))
3074 ;;Insert the formulas
3075 (setq rowcol (ses-yank-resize needrows needcols))
3076 (dotimes (row needrows)
3077 (dotimes (col needcols)
3078 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
3079 (+ (cdr rowcol) needcols (- col) -1))
3080 text (1+ (cadr spots)) (car spots) arg)
3081 (setq spots (cdr spots))))
3082 (ses-goto-print (+ (car rowcol) needrows -1)
3083 (+ (cdr rowcol) needcols -1))
3086 (defun ses-yank-resize (needrows needcols)
3087 "If this yank will require inserting rows and/or columns, ask for
3088 confirmation and then insert them. Result is (row,col) for top left of yank
3089 spot, or error signal if user requests cancel."
3091 (let ((rowcol (if ses--curcell
3092 (ses-sym-rowcol ses--curcell)
3093 (cons ses--numrows 0)))
3095 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
3096 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
3097 rowbool (> needrows 0)
3098 colbool (> needcols 0))
3099 (when (or rowbool colbool)
3100 ;;Need to insert. Get confirm
3101 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
3102 (if rowbool (format "%d rows" needrows) "")
3103 (if (and rowbool colbool) " and " "")
3104 (if colbool (format "%d columns" needcols) "")))
3109 (ses-goto-print ses--numrows 0)
3110 (ses-insert-row needrows))))
3112 (ses-insert-column needcols
3114 (ses-col-width (1- ses--numcols))
3115 (ses-col-printer (1- ses--numcols)))))
3118 (defun ses-export-tsv (_beg _end)
3119 "Export values from the current range, with tabs between columns and
3120 newlines between rows. Result is placed in kill ring."
3122 (ses-export-tab nil))
3124 (defun ses-export-tsf (_beg _end)
3125 "Export formulas from the current range, with tabs between columns and
3126 newlines between rows. Result is placed in kill ring."
3130 (defun ses-export-tab (want-formulas)
3131 "Export the current range with tabs between columns and newlines between rows.
3132 Result is placed in kill ring. The export is values unless WANT-FORMULAS
3133 is non-nil. Newlines and tabs in the export text are escaped."
3134 (ses-check-curcell 'needrange)
3135 (let ((print-escape-newlines t)
3137 (ses-dorange ses--curcell
3138 (setq item (if want-formulas
3139 (ses-cell-formula row col)
3140 (ses-cell-value row col)))
3141 (if (eq (car-safe item) 'ses-safe-formula)
3142 ;;Hide our deferred safety-check marker
3143 (setq item (cadr item)))
3144 (if (or (not item) (eq item '*skip*))
3146 (when (eq (car-safe item) 'quote)
3148 (setq item (cadr item)))
3149 (setq item (prin1-to-string item t))
3150 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
3156 (push "\n" result))))
3157 (setq result (apply #'concat (nreverse result)))
3161 ;;----------------------------------------------------------------------------
3162 ;; Other user commands
3163 ;;----------------------------------------------------------------------------
3165 (defun ses-unset-header-row ()
3166 "Select the default header row."
3168 (ses-set-header-row 0))
3170 (defun ses-set-header-row (row)
3171 "Set the ROW to display in the header-line.
3172 With a numerical prefix arg, use that row.
3173 With no prefix arg, use the current row.
3174 With a \\[universal-argument] prefix arg, prompt the user.
3175 The top row is row 1. Selecting row 0 displays the default header row."
3177 (list (if (numberp current-prefix-arg) current-prefix-arg
3178 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3179 (if current-prefix-arg
3180 (read-number "Header row: " currow)
3182 (if (or (< row 0) (> row ses--numrows))
3183 (error "Invalid header-row"))
3185 (let ((oldval ses--header-row))
3186 (let (buffer-undo-list)
3187 (ses-set-parameter 'ses--header-row row))
3188 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
3189 (ses-reset-header-string))
3191 (defun ses-mark-row ()
3192 "Mark the entirety of current row as a range."
3194 (ses-check-curcell 'range)
3195 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
3197 (ses-goto-print (1+ row) 0)
3198 (push-mark (point) nil t)
3199 (ses-goto-print row 0)))
3201 (defun ses-mark-column ()
3202 "Mark the entirety of current column as a range."
3204 (ses-check-curcell 'range)
3205 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
3208 (ses-goto-print (1- ses--numrows) col)
3210 (push-mark (point) nil t)
3211 (while (eq '*skip* (ses-cell-value row col))
3212 ;;Skip over initial cells in column that can't be selected
3213 (setq row (1+ row)))
3214 (ses-goto-print row col)))
3216 (defun ses-end-of-line ()
3217 "Move point to last cell on line."
3219 (ses-check-curcell 'end 'range)
3220 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3222 (let ((col (1- ses--numcols))
3224 (if (symbolp ses--curcell)
3226 (setq row (car (ses-sym-rowcol ses--curcell)))
3227 ;; Range --- use whichever end of the range the point is at.
3228 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
3230 (cdr ses--curcell))))
3231 ;; If range already includes the last cell in a row, point is actually
3232 ;; in the following row.
3233 (if (<= (cdr rowcol) (1- col))
3234 (setq row (car rowcol))
3235 (setq row (1+ (car rowcol)))
3236 (if (= row ses--numrows)
3237 ;;Already at end - can't go anywhere
3239 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
3240 (while (eq (ses-cell-value row col) '*skip*)
3241 ;; Back to beginning of multi-column cell.
3242 (setq col (1- col)))
3243 (ses-goto-print row col)))))
3245 (defun ses-renarrow-buffer ()
3246 "Narrow the buffer so only the print area is visible.
3247 Use after \\[widen]."
3249 (setq ses--deferred-narrow t))
3251 (defun ses-sort-column (sorter &optional reverse)
3252 "Sort the range by a specified column.
3253 With prefix, sorts in REVERSE order."
3254 (interactive "*sSort column: \nP")
3255 (ses-check-curcell 'needrange)
3256 (let ((min (ses-sym-rowcol (car ses--curcell)))
3257 (max (ses-sym-rowcol (cdr ses--curcell))))
3258 (let ((minrow (car min))
3263 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3264 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3265 (error "Invalid sort column"))
3266 ;;Get key columns and sort them
3267 (dotimes (x (- maxrow minrow -1))
3268 (ses-goto-print (+ minrow x) sorter)
3269 (setq end (next-single-property-change (point) 'cursor-intangible))
3270 (push (cons (buffer-substring-no-properties (point) end)
3273 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3274 ;;Extract the lines in reverse sorted order
3276 (setq keys (nreverse keys)))
3278 (ses-goto-print (cdr x) (1+ maxcol))
3280 (ses-goto-print (cdr x) mincol)
3281 (push (ses-copy-region (point) end) extracts))
3283 ;;Paste the lines sequentially
3284 (dotimes (x (- maxrow minrow -1))
3285 (ses-goto-print (+ minrow x) mincol)
3287 (ses-yank-cells (pop extracts) nil)))))
3289 (defun ses-sort-column-click (event reverse)
3290 "Mouse version of `ses-sort-column'."
3291 (interactive "*e\nP")
3292 (setq event (event-end event))
3293 (select-window (posn-window event))
3294 (setq event (car (posn-col-row event))) ; Click column.
3296 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3297 (setq event (- event (ses-col-width col) 1)
3299 (if (>= col ses--numcols)
3301 (ses-sort-column (ses-column-letter col) reverse))))
3303 (defun ses-insert-range ()
3304 "Insert into minibuffer the list of cells currently highlighted in the
3308 (with-current-buffer (window-buffer minibuffer-scroll-window)
3309 (ses-command-hook) ; For ses-coverage.
3310 (ses-check-curcell 'needrange)
3311 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3312 ,(cdr ses--curcell))))))
3313 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3315 (defun ses-insert-ses-range ()
3316 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
3317 highlighted range in the spreadsheet."
3320 (with-current-buffer (window-buffer minibuffer-scroll-window)
3321 (ses-command-hook) ; For ses-coverage.
3322 (ses-check-curcell 'needrange)
3323 (setq x (format "(ses-range %S %S)"
3325 (cdr ses--curcell))))
3328 (defun ses-insert-range-click (event)
3329 "Mouse version of `ses-insert-range'."
3331 (mouse-set-point event)
3334 (defun ses-insert-ses-range-click (event)
3335 "Mouse version of `ses-insert-ses-range'."
3337 (mouse-set-point event)
3338 (ses-insert-ses-range))
3340 (defun ses-replace-name-in-formula (formula old-name new-name)
3341 (let ((new-formula formula))
3342 (unless (and (consp formula)
3343 (eq (car-safe formula) 'quote))
3345 (let ((elt (car-safe formula)))
3348 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3350 (eq (car-safe formula) old-name))
3351 (setcar formula new-name))))
3352 (setq formula (cdr formula))))
3355 (defun ses-rename-cell (new-name &optional cell)
3356 "Rename current cell."
3357 (interactive "*SEnter new name: ")
3359 (and (local-variable-p new-name)
3360 (ses-is-cell-sym-p new-name)
3361 (error "Already a cell name"))
3362 (and (boundp new-name)
3365 "`%S' is already bound outside this buffer, continue? "
3367 (error "Already a bound cell name")))
3369 (sym (if (ses-cell-p cell)
3370 (ses-cell-symbol cell)
3375 (rowcol (ses-sym-rowcol sym))
3378 new-rowcol old-name)
3379 (setq cell (or cell (ses-get-cell row col))
3380 old-name (ses-cell-symbol cell)
3381 new-rowcol (ses-decode-cell-symbol (symbol-name new-name)))
3383 (if (equal new-rowcol rowcol)
3384 (put new-name 'ses-cell rowcol)
3385 (error "Not a valid name for this cell location"))
3386 (setq ses--named-cell-hashmap
3387 (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
3388 (put new-name 'ses-cell :ses-named)
3389 (puthash new-name rowcol ses--named-cell-hashmap))
3390 (push `(ses-rename-cell ,old-name ,cell) buffer-undo-list)
3391 ;; Replace name by new name in formula of cells refering to renamed cell.
3392 (dolist (ref (ses-cell-references cell))
3393 (let* ((x (ses-sym-rowcol ref))
3394 (xcell (ses-get-cell (car x) (cdr x))))
3395 (setf (ses-cell-formula xcell)
3396 (ses-replace-name-in-formula
3397 (ses-cell-formula xcell)
3400 ;; Replace name by new name in reference list of cells to which renamed
3402 (dolist (ref (ses-formula-references (ses-cell-formula cell)))
3403 (let* ((x (ses-sym-rowcol ref))
3404 (xcell (ses-get-cell (car x) (cdr x))))
3405 (setf (ses-cell-references xcell)
3406 (cons new-name (delq sym
3407 (ses-cell-references xcell))))))
3408 (push new-name ses--renamed-cell-symb-list)
3409 (set new-name (symbol-value sym))
3410 (setf (ses-cell--symbol cell) new-name)
3412 (and curcell (setq ses--curcell new-name))
3413 (let* ((pos (point))
3414 (inhibit-read-only t)
3415 (col (current-column))
3416 (end (save-excursion
3417 (move-to-column (1+ col))
3419 (+ pos (ses-col-width col) 1)
3421 (put-text-property pos end 'cursor-intangible new-name))
3422 ;; Update the cell name in the mode-line.
3423 (force-mode-line-update)))
3425 (defun ses-refresh-local-printer (name _compiled-value) ;FIXME: unused arg?
3426 "Refresh printout for all cells which use printer NAME.
3427 NAME should be the name of a locally defined printer.
3428 Uses the value COMPILED-VALUE for this printer."
3429 (message "Refreshing cells using printer %S" name)
3431 (dotimes (row ses--numrows)
3432 (dotimes (col ses--numcols)
3433 (let ((cell-printer (ses-cell-printer row col)))
3434 (when (eq cell-printer name)
3438 (ses-print-cell row col)))))))
3440 (defun ses-define-local-printer (name)
3441 "Define a local printer with name NAME."
3442 (interactive "*SEnter printer name: ")
3443 (let* ((cur-printer (gethash name ses--local-printer-hashmap))
3444 (default (and (vectorp cur-printer) (ses--locprn-def cur-printer)))
3447 (ses-read-printer (format "Enter definition of printer %S: " name)
3450 ;; cancelled operation => do nothing
3452 ;; no change => do nothing
3453 ((and (vectorp cur-printer) (equal new-def default)))
3454 ;; re-defined printer
3455 ((vectorp cur-printer)
3456 (setq create-printer 0)
3457 (setf (ses--locprn-def cur-printer) new-def)
3458 (ses-refresh-local-printer
3460 (setf (ses--locprn-compiled cur-printer)
3461 (ses-local-printer-compile new-def))))
3464 (setq create-printer 1)
3467 (ses-make-local-printer-info new-def))
3468 ses--local-printer-hashmap)))
3469 (when create-printer
3470 (let ((printer-def-text
3472 "(ses-local-printer "
3475 (prin1-to-string (ses--locprn-def cur-printer))
3478 (ses-goto-data ses--numrows
3479 (ses--locprn-number cur-printer))
3480 (let ((inhibit-read-only t))
3481 ;; Special undo since it's outside the narrowed buffer.
3482 (let (buffer-undo-list)
3483 (if (= create-printer 0)
3484 (delete-region (point) (line-end-position))
3487 (insert printer-def-text)
3488 (when (= create-printer 1)
3489 (ses-file-format-extend-parameter-list 3)
3490 (ses-set-parameter 'ses--numlocprn
3491 (+ ses--numlocprn create-printer))))))))))
3494 ;;----------------------------------------------------------------------------
3495 ;; Checking formulas for safety
3496 ;;----------------------------------------------------------------------------
3498 (defun ses-safe-printer (printer)
3499 "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
3500 (if (or (stringp printer)
3501 (stringp (car-safe printer))
3503 (and (symbolp printer) (gethash printer ses--local-printer-hashmap))
3504 (ses-warn-unsafe printer 'unsafep-function))
3508 (defun ses-safe-formula (formula)
3509 "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
3510 (if (ses-warn-unsafe formula 'unsafep)
3512 `(ses-unsafe ',formula)))
3514 (defun ses-warn-unsafe (formula checker)
3515 "Apply CHECKER to FORMULA.
3516 If result is non-nil, asks user for confirmation about FORMULA,
3517 which might be unsafe. Returns t if formula is safe or user allows
3518 execution anyway. Always returns t if `safe-functions' is t."
3519 (if (eq safe-functions t)
3521 (setq checker (funcall checker formula))
3524 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3525 formula checker)))))
3528 ;;----------------------------------------------------------------------------
3529 ;; Standard formulas
3530 ;;----------------------------------------------------------------------------
3532 (defun ses--clean-! (&rest x)
3533 "Clean by `delq' list X from any occurrence of nil or `*skip*'."
3534 (delq nil (delq '*skip* x)))
3536 (defun ses--clean-_ (x y)
3537 "Clean list X by replacing by Y any occurrence of nil or `*skip*'.
3539 This will change X by making `setcar' on its cons cells."
3540 (let ((ret x) ret-elt)
3542 (setq ret-elt (car ret))
3543 (when (memq ret-elt '(nil *skip*))
3545 (setq ret (cdr ret))))
3548 (defmacro ses-range (from to &rest rest)
3549 "Expand to a list of cell-symbols for the range going from
3550 FROM up to TO. The range automatically expands to include any
3551 new row or column inserted into its middle. The SES library code
3552 specifically looks for the symbol `ses-range', so don't create an
3553 alias for this macro!
3555 By passing in REST some flags one can configure the way the range
3556 is read and how it is formatted.
3558 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3561 Readout direction is specified by a `>v', '`>^', `<v', `<^',
3562 `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3563 of such a flag, a default direction of `^<' is assumed. This
3564 way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3565 while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3567 If the range is one row, then `>' can be used as a shorthand to
3568 `>v' or `>^', and `<' to `<v' or `<^'.
3570 If the range is one column, then `v' can be used as a shorthand to
3571 `v>' or `v<', and `^' to `^>' or `v<'.
3573 A `!' flag will remove all cells whose value is nil or `*skip*'.
3575 A `_' flag will replace nil or `*skip*' by the value following
3576 the `_' flag. If the `_' flag is the last argument, then they are
3577 replaced by integer 0.
3579 A `*', `*1' or `*2' flag will vectorize the range in the sense of
3580 Calc. See info node `(Calc) Top'. Flag `*' will output either a
3581 vector or a matrix depending on the number of rows, `*1' will
3582 flatten the result to a one row vector, and `*2' will make a
3583 matrix whatever the number of rows.
3585 Warning: interaction with Calc is experimental and may produce
3586 confusing results if you are not aware of Calc data format.
3587 Use `math-format-value' as a printer for Calc objects."
3595 (ses-dorange (cons from to)
3596 (when (/= prev-row row)
3597 (push result-row result)
3598 (setq result-row nil))
3599 (push (ses-cell-symbol row col) result-row)
3600 (setq prev-row row))
3601 (push result-row result)
3603 (let ((x (pop rest)))
3605 (`>v (setq transpose nil reorient-x nil reorient-y nil))
3606 (`>^ (setq transpose nil reorient-x nil reorient-y t))
3607 (`<^ (setq transpose nil reorient-x t reorient-y t))
3608 (`<v (setq transpose nil reorient-x t reorient-y nil))
3609 (`v> (setq transpose t reorient-x nil reorient-y t))
3610 (`^> (setq transpose t reorient-x nil reorient-y nil))
3611 (`^< (setq transpose t reorient-x t reorient-y nil))
3612 (`v< (setq transpose t reorient-x t reorient-y t))
3613 ((or `* `*2 `*1) (setq vectorize x))
3614 (`! (setq clean 'ses--clean-!))
3615 (`_ (setq clean `(lambda (&rest x)
3616 (ses--clean-_ x ,(if rest (pop rest) 0)))))
3619 ; shorthands one row
3620 ((and (null (cddr result)) (memq x '(> <)))
3621 (push (intern (concat (symbol-name x) "v")) rest))
3622 ; shorthands one col
3623 ((and (null (cdar result)) (memq x '(v ^)))
3624 (push (intern (concat (symbol-name x) ">")) rest))
3625 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3627 (setcdr (last result 2) nil)
3628 (setq result (cdr (nreverse result))))
3630 (setq result (mapcar #'nreverse result)))
3632 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3635 (dolist (elt (pop result))
3636 (setcar iter (cons elt (car iter)))
3637 (setq iter (cdr iter))))
3640 (cl-flet ((vectorize-*1
3642 (cons clean (cons (quote 'vec) (apply #'append result))))
3645 (cons clean (cons (quote 'vec)
3647 (cons clean (cons (quote 'vec) x)))
3650 (`nil (cons clean (apply #'append result)))
3651 (`*1 (vectorize-*1 clean result))
3652 (`*2 (vectorize-*2 clean result))
3653 (`* (funcall (if (cdr result)
3658 (defun ses-delete-blanks (&rest args)
3659 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3662 (unless (memq cur '(nil *skip* *error*))
3666 (defun ses+ (&rest args)
3667 "Compute the sum of the arguments, ignoring blanks."
3668 (apply #'+ (apply #'ses-delete-blanks args)))
3670 (defun ses-average (list)
3671 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3672 are ignored. Result is always floating-point, even if all args are integers."
3673 (setq list (apply #'ses-delete-blanks list))
3674 (/ (float (apply #'+ list)) (length list)))
3676 (defmacro ses-select (fromrange test torange)
3677 "Select cells in FROMRANGE that are `equal' to TEST.
3678 For each match, return the corresponding cell from TORANGE.
3679 The ranges are macroexpanded but not evaluated so they should be
3680 either (ses-range BEG END) or (list ...). The TEST is evaluated."
3681 (setq fromrange (cdr (macroexpand fromrange))
3682 torange (cdr (macroexpand torange))
3684 (or (= (length fromrange) (length torange))
3685 (error "ses-select: Ranges not same length"))
3687 (dolist (x fromrange)
3688 (if (equal test (symbol-value x))
3689 (push (car torange) result))
3690 (setq torange (cdr torange)))
3691 (cons 'list result)))
3693 ;;All standard formulas are safe
3694 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3696 (put x 'side-effect-free t))
3699 ;;----------------------------------------------------------------------------
3700 ;; Standard print functions
3701 ;;----------------------------------------------------------------------------
3703 (defun ses-center (value &optional span fill)
3704 "Print VALUE, centered within column.
3705 FILL is the fill character for centering (default = space).
3706 SPAN indicates how many additional rightward columns to include
3707 in width (default = 0)."
3708 (let ((printer (or (ses-col-printer ses--col) ses--default-printer))
3709 (width (ses-col-width ses--col))
3711 (or fill (setq fill ?\s))
3712 (or span (setq span 0))
3713 (setq value (ses-call-printer printer value))
3715 (setq width (+ width 1 (ses-col-width (+ ses--col span (- x))))))
3716 ;; Set column width.
3717 (setq width (- width (string-width value)))
3719 value ; Too large for field, anyway.
3720 (setq half (make-string (/ width 2) fill))
3721 (concat half value half
3722 (if (> (% width 2) 0) (char-to-string fill))))))
3724 (defun ses-center-span (value &optional fill)
3725 "Print VALUE, centered within the span that starts in the current column
3726 and continues until the next nonblank column.
3727 FILL specifies the fill character (default = space)."
3728 (let ((end (1+ ses--col)))
3729 (while (and (< end ses--numcols)
3730 (memq (ses-cell-value ses--row end) '(nil *skip*)))
3731 (setq end (1+ end)))
3732 (ses-center value (- end ses--col 1) fill)))
3734 (defun ses-dashfill (value &optional span)
3735 "Print VALUE centered using dashes.
3736 SPAN indicates how many rightward columns to include in width (default = 0)."
3737 (ses-center value span ?-))
3739 (defun ses-dashfill-span (value)
3740 "Print VALUE, centered using dashes within the span that starts in the
3741 current column and continues until the next nonblank column."
3742 (ses-center-span value ?-))
3744 (defun ses-tildefill-span (value)
3745 "Print VALUE, centered using tildes within the span that starts in the
3746 current column and continues until the next nonblank column."
3747 (ses-center-span value ?~))
3749 (defun ses-unsafe (_value)
3750 "Substitute for an unsafe formula or printer."
3751 (error "Unsafe formula or printer"))
3753 ;;All standard printers are safe, including ses-unsafe!
3754 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3755 (put x 'side-effect-free t))
3757 (defun ses-unload-function ()
3758 "Unload the Simple Emacs Spreadsheet."
3759 (advice-remove 'yank #'ses--advice-yank)
3760 (advice-remove 'copy-region-as-kill #'ses--advice-copy-region-as-kill)
3761 ;; Continue standard unloading.
3766 ;;; ses.el ends here