1 ;;; ses.el -- Simple Emacs Spreadsheet -*- lexical-binding:t -*-
3 ;; Copyright (C) 2002-2014 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 ;; * split (catch 'cycle ...) call back into one or more functions
29 ;; * Use $ or … for truncated fields
30 ;; * Add command to make a range of columns be temporarily invisible.
31 ;; * Allow paste of one cell to a range of cells -- copy formula to each.
32 ;; * Do something about control characters & octal codes in cell print
33 ;; areas. Use string-width?
34 ;; * Input validation functions. How specified?
35 ;; * Faces (colors & styles) in print cells.
36 ;; * Move a column by dragging its letter in the header line.
37 ;; * Left-margin column for row number.
38 ;; * Move a row by dragging its number in the left-margin.
42 ;; Cycles used to be detected by stationarity of ses--deferred-recalc. This was
43 ;; working fine in most cases, however failed in some cases of several path
46 ;; The current algorithm is based on Dijkstra's algorithm. The cycle length is
47 ;; stored in some cell property. In order not to reset in all cells such
48 ;; property at each update, the cycle length is stored in this property along
49 ;; with some update attempt id that is incremented at each update. The current
50 ;; update id is ses--Dijkstra-attempt-nb. In case there is a cycle the cycle
51 ;; length diverge to infinite so it will exceed ses--Dijkstra-weight-bound at
52 ;; some point of time that allows detection. Otherwise it converges to the
53 ;; longest path length in the update tree.
59 (eval-when-compile (require 'cl-lib
))
62 ;;----------------------------------------------------------------------------
63 ;; User-customizable variables
64 ;;----------------------------------------------------------------------------
67 "Simple Emacs Spreadsheet."
70 :link
'(custom-manual "(ses) Top")
74 (defcustom ses-initial-size
'(1 .
1)
75 "Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
77 :type
'(cons (integer :tag
"numrows") (integer :tag
"numcols")))
79 (defcustom ses-initial-column-width
7
80 "Initial width of columns in a new spreadsheet."
82 :type
'(integer :match
(lambda (widget value
) (> value
0))))
84 (defcustom ses-initial-default-printer
"%.7g"
85 "Initial default printer for a new spreadsheet."
88 (list :tag
"Parenthesized string" string
)
91 (defcustom ses-after-entry-functions
'(forward-char)
92 "Things to do after entering a value into a cell.
93 An abnormal hook that usually runs a cursor-movement function.
94 Each function is called with ARG=1."
97 :options
'(forward-char backward-char next-line previous-line
))
99 (defcustom ses-mode-hook nil
100 "Hook functions to be run upon entering SES mode."
105 ;;----------------------------------------------------------------------------
106 ;; Global variables and constants
107 ;;----------------------------------------------------------------------------
109 (defvar ses-read-cell-history nil
110 "List of formulas that have been typed in.")
112 (defvar ses-read-printer-history nil
113 "List of printer functions that have been typed in.")
115 (easy-menu-define ses-header-line-menu nil
116 "Context menu when mouse-3 is used on the header-line in an SES buffer."
118 ["Set current row" ses-set-header-row t
]
119 ["Unset row" ses-unset-header-row
(> ses--header-row
0)]))
121 (defconst ses-mode-map
122 (let ((keys `("\C-c\M-\C-l" ses-reconstruct-all
123 "\C-c\C-l" ses-recalculate-all
124 "\C-c\C-n" ses-renarrow-buffer
125 "\C-c\C-c" ses-recalculate-cell
126 "\C-c\M-\C-s" ses-sort-column
127 "\C-c\M-\C-h" ses-set-header-row
128 "\C-c\C-t" ses-truncate-cell
130 "\C-c\C-p" ses-read-default-printer
131 "\M-\C-l" ses-reprint-all
132 [?\S-\C-l
] ses-reprint-all
133 [header-line down-mouse-3
] ,ses-header-line-menu
134 [header-line mouse-2
] ses-sort-column-click
))
135 (newmap (make-sparse-keymap)))
137 (define-key (1value newmap
) (car keys
) (cadr keys
))
138 (setq keys
(cddr keys
)))
140 "Local keymap for Simple Emacs Spreadsheet.")
142 (easy-menu-define ses-menu ses-mode-map
143 "Menu bar menu for SES."
145 ["Insert row" ses-insert-row
(ses-in-print-area)]
146 ["Delete row" ses-delete-row
(ses-in-print-area)]
147 ["Insert column" ses-insert-column
(ses-in-print-area)]
148 ["Delete column" ses-delete-column
(ses-in-print-area)]
149 ["Set column printer" ses-read-column-printer t
]
150 ["Set column width" ses-set-column-width t
]
151 ["Set default printer" ses-read-default-printer t
]
152 ["Jump to cell" ses-jump t
]
153 ["Set cell printer" ses-read-cell-printer t
]
154 ["Recalculate cell" ses-recalculate-cell t
]
155 ["Truncate cell display" ses-truncate-cell t
]
156 ["Export values" ses-export-tsv t
]
157 ["Export formulas" ses-export-tsf t
]))
159 (defconst ses-mode-edit-map
160 (let ((keys '("\C-c\C-r" ses-insert-range
161 "\C-c\C-s" ses-insert-ses-range
162 [S-mouse-3
] ses-insert-range-click
163 [C-S-mouse-3
] ses-insert-ses-range-click
164 "\M-\C-i" lisp-complete-symbol
))
165 (newmap (make-sparse-keymap)))
166 (set-keymap-parent newmap minibuffer-local-map
)
168 (define-key newmap
(pop keys
) (pop keys
)))
170 "Local keymap for SES minibuffer cell-editing.")
172 ;Local keymap for SES print area
173 (defalias 'ses-mode-print-map
174 (let ((keys '([backtab] backward-char
175 [tab] ses-forward-or-insert
176 "\C-i" ses-forward-or-insert ; Needed for ses-coverage.el?
177 "\M-o" ses-insert-column
178 "\C-o" ses-insert-row
180 "\M-k" ses-delete-column
182 "\C-k" ses-delete-row
183 "\C-j" ses-append-row-jump-first-column
185 "\M-H" ses-mark-column
186 "\C-d" ses-clear-cell-forward
187 "\C-?" ses-clear-cell-backward
192 "c" ses-recalculate-cell
194 "p" ses-read-cell-printer
195 "t" ses-truncate-cell
196 "w" ses-set-column-width
197 "x" ses-export-keymap
198 "\M-p" ses-read-column-printer))
199 (repl '(;;We'll replace these wherever they appear in the keymap
200 clipboard-kill-region ses-kill-override
201 end-of-line ses-end-of-line
202 kill-line ses-delete-row
203 kill-region ses-kill-override
204 open-line ses-insert-row))
205 (numeric "0123456789.-")
206 (newmap (make-keymap)))
207 ;;Get rid of printables
208 (suppress-keymap newmap t)
209 ;;These keys insert themselves as the beginning of a numeric value
210 (dotimes (x (length numeric))
211 (define-key newmap (substring numeric x (1+ x)) 'ses-read-cell))
212 ;;Override these global functions wherever they're bound
214 (substitute-key-definition (car repl) (cadr repl) newmap
215 (current-global-map))
216 (setq repl (cddr repl)))
217 ;;Apparently substitute-key-definition doesn't catch this?
218 (define-key newmap [(menu-bar) edit cut] 'ses-kill-override)
219 ;;Define our other local keys
221 (define-key newmap (car keys) (cadr keys))
222 (setq keys (cddr keys)))
225 ;;Helptext for ses-mode wants keymap as variable, not function
226 (defconst ses-mode-print-map (symbol-function 'ses-mode-print-map))
228 ;;Key map used for 'x' key.
229 (defalias 'ses-export-keymap
230 (let ((map (make-sparse-keymap "SES export")))
231 (define-key map "T" (cons " tab-formulas" 'ses-export-tsf))
232 (define-key map "t" (cons " tab-values" 'ses-export-tsv))
235 (defconst ses-print-data-boundary "\n\014\n"
236 "Marker string denoting the boundary between print area and data area.")
238 (defconst ses-initial-global-parameters
239 "\n( ;Global parameters (these are read first)\n 2 ;SES file-format\n 1 ;numrows\n 1 ;numcols\n)\n\n"
240 "Initial contents for the three-element list at the bottom of the data area.")
242 (defconst ses-initial-global-parameters-re
243 "\n( ;Global parameters (these are read first)\n [23] ;SES file-format\n [0-9]+ ;numrows\n [0-9]+ ;numcols\n\\( [0-9]+ ;numlocprn\n\\)?)\n\n"
244 "Match Global parameters for .")
246 (defconst ses-initial-file-trailer
247 ";; Local Variables:\n;; mode: ses\n;; End:\n"
248 "Initial contents for the file-trailer area at the bottom of the file.")
250 (defconst ses-initial-file-contents
251 (concat " \n" ; One blank cell in print area.
252 ses-print-data-boundary
253 "(ses-cell A1 nil nil nil nil)\n" ; One blank cell in data area.
254 "\n" ; End-of-row terminator for the one row in data area.
255 "(ses-column-widths [7])\n"
256 "(ses-column-printers [nil])\n"
257 "(ses-default-printer \"%.7g\")\n"
258 "(ses-header-row 0)\n"
259 ses-initial-global-parameters
260 ses-initial-file-trailer)
261 "The initial contents of an empty spreadsheet.")
263 (defconst ses-box-prop '(:box (:line-width 2 :style released-button))
264 "Display properties to create a raised box for cells in the header line.")
266 (defconst ses-standard-printer-functions
267 '(ses-center ses-center-span ses-dashfill ses-dashfill-span
269 "List of print functions to be included in initial history of printer
270 functions. None of these standard-printer functions is suitable for use as a
271 column printer or a global-default printer because they invoke the column or
272 default printer and then modify its output.")
275 ;;----------------------------------------------------------------------------
276 ;; Local variables and constants
277 ;;----------------------------------------------------------------------------
280 (defconst ses-localvars
281 '(ses--blank-line ses--cells ses--col-printers
282 ses--col-widths ses--curcell ses--curcell-overlay
284 (ses--local-printer-hashmap . :hashmap)
285 (ses--numlocprn . 0); count of local printers
286 ses--deferred-narrow ses--deferred-recalc
287 ses--deferred-write ses--file-format
288 ses--named-cell-hashmap
289 (ses--header-hscroll . -1) ; Flag for "initial recalc needed"
290 ses--header-row ses--header-string ses--linewidth
291 ses--numcols ses--numrows ses--symbolic-formulas
292 ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
293 ses--Dijkstra-weight-bound
294 ;; This list is useful to speed-up clean-up of symbols when
295 ;; an area containing renamed cell is deleted.
296 ses--renamed-cell-symb-list
297 ;; Global variables that we override
298 mode-line-process next-line-add-newlines transient-mark-mode)
299 "Buffer-local variables used by SES."))
301 (defmacro ses--metaprogramming (exp) (declare (debug t)) (eval exp t))
302 (ses--metaprogramming
303 `(progn ,@(mapcar (lambda (x) `(defvar ,(or (car-safe x) x))) ses-localvars)))
305 (defun ses-set-localvars ()
306 "Set buffer-local and initialize some SES variables."
307 (dolist (x ses-localvars)
310 (set (make-local-variable x) nil))
314 (set (make-local-variable (car x)) (cdr x)))
315 ((eq (cdr x) :hashmap)
316 (set (make-local-variable (car x)) (make-hash-table :test 'eq)))
317 (t (error "Unexpected initializer `%S' in list `ses-localvars' for entry %S"
318 (cdr x) (car x)) ) ))
319 (t (error "Unexpected elements `%S' in list `ses-localvars'" x)))))
321 ;;; This variable is documented as being permitted in file-locals:
322 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
324 (defconst ses-paramlines-plist
325 '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
326 ses--header-row -2 ses--file-format 1 ses--numrows 2
327 ses--numcols 3 ses--numlocprn 4)
328 "Offsets from 'Global parameters' line to various parameter lines in the
329 data area of a spreadsheet.")
331 (defconst ses-paramfmt-plist
332 '(ses--col-widths "(ses-column-widths %S)"
333 ses--col-printers "(ses-column-printers %S)"
334 ses--default-printer "(ses-default-printer %S)"
335 ses--header-row "(ses-header-row %S)"
336 ses--file-format " %S ;SES file-format"
337 ses--numrows " %S ;numrows"
338 ses--numcols " %S ;numcols"
339 ses--numlocprn " %S ;numlocprn")
340 "Formats of 'Global parameters' various parameters in the data
341 area of a spreadsheet.")
344 ;; "Side-effect variables". They are set in one function, altered in
345 ;; another as a side effect, then read back by the first, as a way of
346 ;; passing back more than one value. These declarations are just to make
347 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
348 ;; think the make-local-variable trick above is cleaner).
351 (defvar ses-relocate-return nil
352 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
353 `ses-relocate-all'. Set to 'delete if a cell-reference was deleted from a
354 formula--so the formula needs recalculation. Set to 'range if the size of a
355 `ses-range' was changed--so both the formula's value and list of dependents
356 need to be recalculated.")
358 (defvar ses-call-printer-return nil
359 "Set to t if last cell printer invoked by `ses-call-printer' requested
360 left-justification of the result. Set to error-signal if `ses-call-printer'
361 encountered an error during printing. Otherwise nil.")
363 (defvar ses-start-time nil
364 "Time when current operation started. Used by `ses-time-check' to decide
365 when to emit a progress message.")
368 ;;----------------------------------------------------------------------------
370 ;;----------------------------------------------------------------------------
372 (defmacro ses-get-cell (row col)
373 "Return the cell structure that stores information about cell (ROW,COL)."
375 `(aref (aref ses--cells ,row) ,col))
377 (cl-defstruct (ses-cell
379 (:constructor ses-make-cell
380 (&optional symbol formula printer references))
382 ;; This is treated as an 4-elem array in various places.
383 ;; Mostly in ses-set-cell.
384 (:type vector) ;Not named.
385 (:conc-name ses-cell--))
386 symbol formula printer references properties)
388 (cl-defstruct (ses--locprn
390 (:constructor ses-make-local-printer-info
391 (def &optional (compiled (ses-local-printer-compile def))
392 (number ses--numlocprn))))
398 (defmacro ses-cell-symbol (row &optional col)
399 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
401 `(ses-cell--symbol ,(if col `(ses-get-cell ,row ,col) row)))
402 (put 'ses-cell-symbol 'safe-function t)
404 (defmacro ses-cell-formula (row &optional col)
405 "From a CELL or a pair (ROW,COL), get the function that computes its value."
407 `(ses-cell--formula ,(if col `(ses-get-cell ,row ,col) row)))
409 (defmacro ses-cell-printer (row &optional col)
410 "From a CELL or a pair (ROW,COL), get the function that prints its value."
412 `(ses-cell--printer ,(if col `(ses-get-cell ,row ,col) row)))
414 (defmacro ses-cell-references (row &optional col)
415 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
416 functions refer to its value."
418 `(ses-cell--references ,(if col `(ses-get-cell ,row ,col) row)))
420 (defun ses-cell-p (cell)
421 "Return non-nil if CELL is a cell of current buffer."
424 (eq cell (let ((rowcol (ses-sym-rowcol (ses-cell-symbol cell))))
426 (ses-get-cell (car rowcol) (cdr rowcol)))))))
429 (defmacro ses--letref (vars place &rest body)
430 (declare (indent 2) (debug (sexp form &rest body)))
431 (gv-letplace (getter setter) place
432 `(cl-macrolet ((,(nth 0 vars) () ',getter)
433 (,(nth 1 vars) (v) (funcall ',setter v)))
436 (defmacro ses-cell-property (property-name row &optional col)
437 "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
439 When COL is omitted, CELL=ROW is a cell object. When COL is
440 present ROW and COL are the integer coordinates of the cell of
443 `(alist-get ,property-name
444 (ses-cell--properties
445 ,(if col `(ses-get-cell ,row ,col) row))))
447 (defmacro ses-cell-property-pop (property-name row &optional col)
448 "From a CELL or a pair (ROW,COL), get and remove the property value of
449 the corresponding cell with name PROPERTY-NAME."
450 `(ses--letref (pget pset)
451 (alist-get ,property-name
452 (ses-cell--properties
453 ,(if col `(ses-get-cell ,row ,col) row))
455 (prog1 (pget) (pset nil))))
457 (defmacro ses-cell-value (row &optional col)
458 "From a CELL or a pair (ROW,COL), get the current value for that cell."
459 `(symbol-value (ses-cell-symbol ,row ,col)))
461 (defmacro ses-col-width (col)
462 "Return the width for column COL."
463 `(aref ses--col-widths ,col))
465 (defmacro ses-col-printer (col)
466 "Return the default printer for column COL."
467 `(aref ses--col-printers ,col))
469 (defmacro ses-sym-rowcol (sym)
470 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0). Result
471 is nil if SYM is not a symbol that names a cell."
472 `(let ((rc (and (symbolp ,sym) (get ,sym 'ses-cell))))
473 (if (eq rc :ses-named)
474 (gethash ,sym ses--named-cell-hashmap)
477 (defun ses-is-cell-sym-p (sym)
478 "Check whether SYM point at a cell of this spread sheet."
479 (let ((rowcol (get sym 'ses-cell)))
481 (if (eq rowcol :ses-named)
482 (and ses--named-cell-hashmap (gethash sym ses--named-cell-hashmap))
483 (and (< (car rowcol) ses--numrows)
484 (< (cdr rowcol) ses--numcols)
485 (eq (ses-cell-symbol (car rowcol) (cdr rowcol)) sym))))))
487 (defun ses--cell (sym value formula printer references)
488 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
489 FORMULA, does not reprint using PRINTER, does not check REFERENCES.
490 Safety-checking for FORMULA and PRINTER are deferred until first use."
491 (let ((rowcol (ses-sym-rowcol sym)))
492 (ses-formula-record formula)
493 (ses-printer-record printer)
494 (unless formula (setq formula value))
496 (eq safe-functions t)
497 (setq formula `(ses-safe-formula ,formula)))
500 (eq safe-functions t)
501 (setq printer `(ses-safe-printer ,printer)))
502 (setf (ses-get-cell (car rowcol) (cdr rowcol))
503 (ses-make-cell sym formula printer references)))
506 (defun ses-local-printer-compile (printer)
507 "Convert local printer function into faster printer
510 ((functionp printer) printer)
512 `(lambda (x) (format ,printer x)))
513 (t (error "Invalid printer %S" printer))))
515 (defun ses--local-printer (name def)
516 "Define a local printer with name NAME and definition DEF.
517 Return the printer info."
520 (ses-printer-validate def))
521 (error "Invalid local printer definition"))
522 (and (gethash name ses--local-printer-hashmap)
523 (error "Duplicate printer definition %S" name))
524 (add-to-list 'ses-read-printer-history (symbol-name name))
526 (ses-make-local-printer-info (ses-safe-printer def))
527 ses--local-printer-hashmap))
529 (defmacro ses-column-widths (widths)
530 "Load the vector of column widths from the spreadsheet file. This is a
531 macro to prevent propagate-on-load viruses."
532 (or (and (vectorp widths) (= (length widths) ses--numcols))
533 (error "Bad column-width vector"))
534 ;;To save time later, we also calculate the total width of each line in the
535 ;;print area (excluding the terminating newline)
536 (setq ses--col-widths widths
537 ses--linewidth (apply #'+ -1 (mapcar #'1+ widths))
538 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
541 (defmacro ses-column-printers (printers)
542 "Load the vector of column printers from the spreadsheet file and checks
543 them for safety. This is a macro to prevent propagate-on-load viruses."
544 (or (and (vectorp printers) (= (length printers) ses--numcols))
545 (error "Bad column-printers vector"))
546 (dotimes (x ses--numcols)
547 (aset printers x (ses-safe-printer (aref printers x))))
548 (setq ses--col-printers printers)
549 (mapc #'ses-printer-record printers)
552 (defmacro ses-default-printer (def)
553 "Load the global default printer from the spreadsheet file and checks it
554 for safety. This is a macro to prevent propagate-on-load viruses."
555 (setq ses--default-printer (ses-safe-printer def))
556 (ses-printer-record def)
559 (defmacro ses-header-row (row)
560 "Load the header row from the spreadsheet file and checks it
561 for safety. This is a macro to prevent propagate-on-load viruses."
562 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
563 (error "Bad header-row"))
564 (setq ses--header-row row)
567 (defmacro ses-dorange (curcell &rest body)
568 "Execute BODY repeatedly, with the variables `row' and `col' set to each
569 cell in the range specified by CURCELL. The range is available in the
570 variables `minrow', `maxrow', `mincol', and `maxcol'."
571 (declare (indent defun) (debug (form body)))
572 (let ((cur (make-symbol "cur"))
573 (min (make-symbol "min"))
574 (max (make-symbol "max"))
575 (r (make-symbol "r"))
576 (c (make-symbol "c")))
577 `(let* ((,cur ,curcell)
578 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
579 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
580 (let ((minrow (car ,min))
584 (if (or (> minrow maxrow) (> mincol maxcol))
585 (error "Empty range"))
586 (dotimes (,r (- maxrow minrow -1))
587 (let ((row (+ ,r minrow)))
588 (dotimes (,c (- maxcol mincol -1))
589 (let ((col (+ ,c mincol)))
592 ;;Support for coverage testing.
593 (defmacro 1value (form)
594 "For code-coverage testing, indicate that FORM is expected to always have
598 (defmacro noreturn (form)
599 "For code-coverage testing, indicate that FORM will always signal an error."
604 ;;----------------------------------------------------------------------------
606 ;;----------------------------------------------------------------------------
608 (defun ses-vector-insert (array idx new)
609 "Create a new vector which is one larger than ARRAY and has NEW inserted
611 (let* ((len (length array))
612 (result (make-vector (1+ len) new)))
615 (if (< x idx) x (1+ x))
619 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
620 (defun ses-vector-delete (array idx count)
621 "Create a new vector which is a copy of ARRAY with COUNT objects removed
622 starting at element IDX. ARRAY is either a vector or a symbol whose value
623 is a vector--if a symbol, the new vector is assigned as the symbol's value."
624 (let* ((a (if (arrayp array) array (symbol-value array)))
625 (len (- (length a) count))
626 (result (make-vector len nil)))
628 (aset result x (aref a (if (< x idx) x (+ x count)))))
633 (defun ses-delete-line (count)
634 "Like `kill-line', but no kill ring."
637 (delete-region pos (point))))
639 (defun ses-printer-validate (printer)
640 "Signal an error if PRINTER is not a valid SES cell printer."
643 ;; printer is a local printer
644 (and (symbolp printer) (gethash printer ses--local-printer-hashmap))
646 (and (stringp (car-safe printer)) (not (cdr printer)))
647 (error "Invalid printer function %S" printer))
650 (defun ses-printer-record (printer)
651 "Add PRINTER to `ses-read-printer-history' if not already there, after first
652 checking that it is a valid printer function."
653 (ses-printer-validate printer)
654 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
656 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
658 (defun ses-formula-record (formula)
659 "If FORMULA is of the form 'symbol, add it to the list of symbolic formulas
660 for this spreadsheet."
661 (when (and (eq (car-safe formula) 'quote)
662 (symbolp (cadr formula)))
663 (add-to-list 'ses--symbolic-formulas
664 (list (symbol-name (cadr formula))))))
666 (defun ses-column-letter (col)
667 "Return the alphabetic name of column number COL.
668 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
669 (let ((units (char-to-string (+ ?A (% col 26)))))
672 (concat (ses-column-letter (1- (/ col 26))) units))))
674 (defun ses-create-cell-symbol (row col)
675 "Produce a symbol that names the cell (ROW,COL). (0,0) => 'A1."
676 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
678 (defun ses-decode-cell-symbol (str)
679 "Decode a symbol \"A1\" => (0,0). Return nil if STR is not a
680 canonical cell name."
681 (let (case-fold-search)
682 (and (string-match "\\`\\([A-Z]+\\)\\([0-9]+\\)\\'" str)
683 (let* ((col-str (match-string-no-properties 1 str))
686 (col-idx (1- (length col-str)))
687 (row (1- (string-to-number
688 (match-string-no-properties 2 str)))))
693 (setq col (+ col (* (- (aref col-str col-idx) ?A)
695 col-base (* col-base 26)
696 col-idx (1- col-idx))
698 (setq col (+ col col-base)))))
701 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
702 "Create buffer-local variables for cells. This is undoable."
703 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
706 (dotimes (row (1+ (- maxrow minrow)))
707 (dotimes (col (1+ (- maxcol mincol)))
708 (setq xrow (+ row minrow)
710 sym (ses-create-cell-symbol xrow xcol))
711 (put sym 'ses-cell (cons xrow xcol))
712 (make-local-variable sym)))))
714 (defun ses-create-cell-variable (sym row col)
715 "Create a buffer-local variable `SYM' for cell at position (ROW, COL).
717 SYM is the symbol for that variable, ROW and COL are integers for
718 row and column of the cell, with numbering starting from 0.
720 Return nil in case of failure."
721 (unless (local-variable-p sym)
722 (make-local-variable sym)
723 (if (let (case-fold-search) (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name sym)))
724 (put sym 'ses-cell (cons row col))
725 (put sym 'ses-cell :ses-named)
726 (setq ses--named-cell-hashmap (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
727 (puthash sym (cons row col) ses--named-cell-hashmap))))
729 ;; We do not delete the ses-cell properties for the cell-variables, in
730 ;; case a formula that refers to this cell is in the kill-ring and is
731 ;; later pasted back in.
732 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
733 "Destroy buffer-local variables for cells. This is undoable."
735 (dotimes (row (1+ (- maxrow minrow)))
736 (dotimes (col (1+ (- maxcol mincol)))
737 (let ((xrow (+ row minrow)) (xcol (+ col mincol)))
738 (setq sym (if (and (< xrow ses--numrows) (< xcol ses--numcols))
739 (ses-cell-symbol xrow xcol)
740 (ses-create-cell-symbol xrow xcol))))
742 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
744 (kill-local-variable sym))))
745 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
748 (defun ses-reset-header-string ()
749 "Flag the header string for update. Upon undo, the header string will be
751 (push '(apply ses-reset-header-string) buffer-undo-list)
752 (setq ses--header-hscroll -1))
754 ;;Split this code off into a function to avoid coverage-testing difficulties
755 (defmacro ses--time-check (format &rest args)
756 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
757 and ARGS and reset `ses-start-time' to the current time."
758 `(when (> (- (float-time) ses-start-time) 1.0)
759 (message ,format ,@args)
760 (setq ses-start-time (float-time))))
763 ;;----------------------------------------------------------------------------
765 ;;----------------------------------------------------------------------------
767 (defmacro ses-set-cell (row col field val)
768 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
769 cell (ROW,COL). This is undoable. The cell's data will be updated through
770 `post-command-hook'."
774 (let* ((cell (ses-get-cell row col))
776 ,(let ((field (progn (cl-assert (eq (car field) 'quote))
778 (if (eq field 'value)
779 `(ses-set-with-undo (ses-cell-symbol cell) val)
780 ;; (let* ((slots (get 'ses-cell 'cl-struct-slots))
781 ;; (slot (or (assq field slots)
782 ;; (error "Unknown field %S" field)))
783 ;; (idx (- (length slots)
784 ;; (length (memq slot slots)))))
785 ;; `(ses-aset-with-undo cell ,idx val))
786 (let ((getter (intern-soft (format "ses-cell--%s" field))))
787 `(ses-setter-with-undo
790 (lambda (newval cell)
791 (setf (,getter cell) newval))))
794 (add-to-list 'ses--deferred-write (cons row col))))
795 nil)) ; Make coverage-tester happy.
797 (defun ses-cell-set-formula (row col formula)
798 "Store a new formula for (ROW . COL) and enqueue the cell for
799 recalculation via `post-command-hook'. Updates the reference lists for the
800 cells that this cell refers to. Does not update cell value or reprint the
801 cell. To avoid inconsistencies, this function is not interruptible, which
802 means Emacs will crash if FORMULA contains a circular list."
803 (let* ((cell (ses-get-cell row col))
804 (old (ses-cell-formula cell)))
805 (let ((sym (ses-cell-symbol cell))
806 (oldref (ses-formula-references old))
807 (newref (ses-formula-references formula))
810 (cl-pushnew sym ses--deferred-recalc)
811 ;;Delete old references from this cell. Skip the ones that are also
814 (unless (memq ref newref)
815 (setq x (ses-sym-rowcol ref)
818 (ses-set-cell xrow xcol 'references
819 (delq sym (ses-cell-references xrow xcol)))))
820 ;;Add new ones. Skip ones left over from old list
822 (setq x (ses-sym-rowcol ref)
825 x (ses-cell-references xrow xcol))
827 (ses-set-cell xrow xcol 'references (cons sym x))))
828 (ses-formula-record formula)
829 (ses-set-cell row col 'formula formula))))
832 (defun ses-repair-cell-reference-all ()
833 "Repair cell reference and warn if there was some reference corruption."
836 ;; Step 1, reset :ses-repair-reference cell property in the whole sheet.
837 (dotimes (row ses--numrows)
838 (dotimes (col ses--numcols)
839 (let ((references (ses-cell-property-pop :ses-repair-reference
842 (push (list (ses-cell-symbol row col)
847 ;; Step 2, build new.
848 (dotimes (row ses--numrows)
849 (dotimes (col ses--numcols)
850 (let* ((cell (ses-get-cell row col))
851 (sym (ses-cell-symbol cell))
852 (formula (ses-cell-formula cell))
853 (new-ref (ses-formula-references formula)))
854 (dolist (ref new-ref)
855 (let ((rowcol (ses-sym-rowcol ref)))
856 (cl-pushnew sym (ses-cell-property :ses-repair-reference
860 ;; Step 3, overwrite with check.
861 (dotimes (row ses--numrows)
862 (dotimes (col ses--numcols)
863 (let* ((cell (ses-get-cell row col))
864 (irrelevant (ses-cell-references cell))
865 (new-ref (ses-cell-property-pop :ses-repair-reference cell))
867 (dolist (ref new-ref)
868 (if (memq ref irrelevant)
869 (setq irrelevant (delq ref irrelevant))
871 (ses-set-cell row col 'references new-ref)
872 (when (or missing irrelevant)
873 (push `( ,(ses-cell-symbol cell)
874 ,@(and missing (list :missing missing))
875 ,@(and irrelevant (list :irrelevant irrelevant)))
878 (warn "----------------------------------------------------------------
879 Some references were corrupted.
881 The following is a list where each element ELT is such
882 that (car ELT) is the reference of cell CELL with corruption,
883 and (cdr ELT) is a property list where
885 * property `:corrupt-property' means that
886 property `:ses-repair-reference' of cell CELL was initially non
889 * property `:missing' is a list of missing references
891 * property `:irrelevant' is a list of non needed references
894 (message "No reference corruption found"))))
896 (defun ses-calculate-cell (row col force)
897 "Calculate and print the value for cell (ROW,COL) using the cell's formula
898 function and print functions, if any. Result is nil for normal operation, or
899 the error signal if the formula or print function failed. The old value is
900 left unchanged if it was *skip* and the new value is nil.
901 Any cells that depend on this cell are queued for update after the end of
902 processing for the current keystroke, unless the new value is the same as
903 the old and FORCE is nil."
904 (let ((cell (ses-get-cell row col))
905 cycle-error formula-error printer-error)
906 (let ((oldval (ses-cell-value cell))
907 (formula (ses-cell-formula cell))
909 this-cell-Dijkstra-attempt+1)
910 (when (eq (car-safe formula) 'ses-safe-formula)
911 (setq formula (ses-safe-formula (cadr formula)))
912 (ses-set-cell row col 'formula formula))
914 (setq newval (eval formula t))
916 ;; Variable `sig' can't be nil.
917 (nconc sig (list (ses-cell-symbol cell)))
918 (setq formula-error sig
920 (if (and (not newval) (eq oldval '*skip*))
921 ;; Don't lose the *skip* --- previous field spans this one.
922 (setq newval '*skip*))
924 (when (or force (not (eq newval oldval)))
925 (cl-pushnew (cons row col) ses--deferred-write :test #'equal) ; In case force=t.
926 (ses--letref (pget pset)
927 (ses-cell-property :ses-Dijkstra-attempt cell)
928 (let ((this-cell-Dijkstra-attempt (pget)))
929 (if (null this-cell-Dijkstra-attempt)
931 (setq this-cell-Dijkstra-attempt
932 (cons ses--Dijkstra-attempt-nb 0)))
933 (unless (= ses--Dijkstra-attempt-nb
934 (car this-cell-Dijkstra-attempt))
935 (setcar this-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
936 (setcdr this-cell-Dijkstra-attempt 0)))
937 (setq this-cell-Dijkstra-attempt+1
938 (1+ (cdr this-cell-Dijkstra-attempt)))))
939 (ses-set-cell row col 'value newval)
940 (dolist (ref (ses-cell-references cell))
941 (cl-pushnew ref ses--deferred-recalc)
942 (ses--letref (pget pset)
943 (let ((ref-rowcol (ses-sym-rowcol ref)))
945 :ses-Dijkstra-attempt
946 (car ref-rowcol) (cdr ref-rowcol)))
947 (let ((ref-cell-Dijkstra-attempt (pget)))
949 (if (null ref-cell-Dijkstra-attempt)
951 (setq ref-cell-Dijkstra-attempt
952 (cons ses--Dijkstra-attempt-nb
953 this-cell-Dijkstra-attempt+1)))
954 (if (= (car ref-cell-Dijkstra-attempt) ses--Dijkstra-attempt-nb)
955 (setcdr ref-cell-Dijkstra-attempt
956 (max (cdr ref-cell-Dijkstra-attempt)
957 this-cell-Dijkstra-attempt+1))
958 (setcar ref-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
959 (setcdr ref-cell-Dijkstra-attempt
960 this-cell-Dijkstra-attempt+1)))))
962 (when (> this-cell-Dijkstra-attempt+1 ses--Dijkstra-weight-bound)
963 ;; Update print of this cell.
964 (throw 'cycle (setq formula-error
965 `(error ,(format "Found cycle on cells %S"
966 (ses-cell-symbol cell)))
967 cycle-error formula-error)))))))
968 (setq printer-error (ses-print-cell row col))
971 (error (error-message-string cycle-error)))
972 formula-error printer-error)))
974 (defun ses-clear-cell (row col)
975 "Delete formula and printer for cell (ROW,COL)."
976 (ses-set-cell row col 'printer nil)
977 (ses-cell-set-formula row col nil))
979 (defcustom ses-self-reference-early-detection nil
980 "True if cycle detection is early for cells that refer to themselves."
985 (defun ses-update-cells (list &optional force)
986 "Recalculate cells in LIST, checking for dependency loops. Prints
987 progress messages every second. Dependent cells are not recalculated
988 if the cell's value is unchanged and FORCE is nil."
989 (let ((ses--deferred-recalc list)
992 curlist prevlist this-sym this-rowcol formula)
993 (with-temp-message " "
994 (while ses--deferred-recalc
995 ;; In each loop, recalculate cells that refer only to other cells that
996 ;; have already been recalculated or aren't in the recalculation region.
997 ;; Repeat until all cells have been processed or until the set of cells
998 ;; being worked on stops changing.
1000 (message "Recalculating... (%d cells left)"
1001 (length ses--deferred-recalc)))
1002 (setq curlist ses--deferred-recalc
1003 ses--deferred-recalc nil
1006 ;; this-sym has to be popped from curlist *BEFORE* the check, and not
1007 ;; after because of the case of cells referring to themselves.
1008 (setq this-sym (pop curlist)
1009 this-rowcol (ses-sym-rowcol this-sym)
1010 formula (ses-cell-formula (car this-rowcol)
1013 (dolist (ref (ses-formula-references formula))
1014 (if (and ses-self-reference-early-detection (eq ref this-sym))
1015 (error "Cycle found: cell %S is self-referring" this-sym)
1016 (when (or (memq ref curlist)
1017 (memq ref ses--deferred-recalc))
1018 ;; This cell refers to another that isn't done yet
1019 (cl-pushnew this-sym ses--deferred-recalc :test #'equal)
1021 ;; ses-update-cells is called from post-command-hook, so
1022 ;; inhibit-quit is implicitly bound to t.
1024 ;; Abort the recalculation. User will probably undo now.
1026 (ses-calculate-cell (car this-rowcol) (cdr this-rowcol) force)))
1027 (dolist (ref ses--deferred-recalc)
1028 (cl-pushnew ref nextlist :test #'equal)))
1029 (when ses--deferred-recalc
1030 ;; Just couldn't finish these.
1031 (dolist (x ses--deferred-recalc)
1032 (let ((this-rowcol (ses-sym-rowcol x)))
1033 (ses-set-cell (car this-rowcol) (cdr this-rowcol) 'value '*error*)
1034 (1value (ses-print-cell (car this-rowcol) (cdr this-rowcol)))))
1035 (error "Circular references: %s" ses--deferred-recalc))
1037 ;; Can't use save-excursion here: if the cell under point is updated,
1038 ;; save-excursion's marker will move past the cell.
1042 ;;----------------------------------------------------------------------------
1044 ;;----------------------------------------------------------------------------
1046 (defun ses-in-print-area ()
1047 "Return t if point is in print area of spreadsheet."
1048 (<= (point) ses--data-marker))
1050 ;; We turn off point-motion-hooks and explicitly position the cursor, in case
1051 ;; the intangible properties have gotten screwed up (e.g., when ses-goto-print
1052 ;; is called during a recursive ses-print-cell).
1053 (defun ses-goto-print (row col)
1054 "Move point to print area for cell (ROW,COL)."
1055 (let ((inhibit-point-motion-hooks t)
1057 (goto-char (point-min))
1059 ;; Calculate column position.
1061 (setq n (+ n (ses-col-width c) 1)))
1062 ;; Move to the position.
1063 (and (> n (move-to-column n))
1065 ;; Move point to the bol of next line (for TAB at the last cell).
1068 (defun ses-set-curcell ()
1069 "Set `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
1070 region, or nil if cursor is not at a cell."
1071 (if (or (not mark-active)
1073 (= (region-beginning) (region-end)))
1075 (setq ses--curcell (get-text-property (point) 'intangible))
1077 (let ((bcell (get-text-property (region-beginning) 'intangible))
1078 (ecell (get-text-property (1- (region-end)) 'intangible)))
1079 (when (= (region-end) ses--data-marker)
1080 ;; Correct for overflow.
1081 (setq ecell (get-text-property (- (region-end) 2) 'intangible)))
1082 (setq ses--curcell (if (and bcell ecell)
1087 (defun ses-check-curcell (&rest args)
1088 "Signal an error if `ses--curcell' is inappropriate.
1089 The end marker is appropriate if some argument is 'end.
1090 A range is appropriate if some argument is 'range.
1091 A single cell is appropriate unless some argument is 'needrange."
1092 (if (eq ses--curcell t)
1093 ;; curcell recalculation was postponed, but user typed ahead.
1097 (or (memq 'end args)
1098 (error "Not at cell")))
1099 ((consp ses--curcell)
1100 (or (memq 'range args)
1101 (memq 'needrange args)
1102 (error "Can't use a range")))
1103 ((memq 'needrange args)
1104 (error "Need a range"))))
1109 (defun ses-print-cell (row col)
1110 "Format and print the value of cell (ROW,COL) to the print area.
1111 Use the cell's printer function. If the cell's new print form is too wide,
1112 it will spill over into the following cell, but will not run off the end of the
1113 row or overwrite the next non-nil field. Result is nil for normal operation,
1114 or the error signal if the printer function failed and the cell was formatted
1115 with \"%s\". If the cell's value is *skip*, nothing is printed because the
1116 preceding cell has spilled over."
1117 (catch 'ses-print-cell
1118 (let* ((cell (ses-get-cell row col))
1119 (value (ses-cell-value cell))
1120 (printer (ses-cell-printer cell))
1122 text sig startpos x)
1123 ;; Create the string to print.
1126 ;; Don't print anything.
1127 (throw 'ses-print-cell nil))
1128 ((eq value '*error*)
1129 (setq text (make-string (ses-col-width col) ?#)))
1131 ;; Deferred safety-check on printer.
1132 (if (eq (car-safe printer) 'ses-safe-printer)
1133 (ses-set-cell row col 'printer
1134 (setq printer (ses-safe-printer (cadr printer)))))
1137 (let ((ses--row row)
1139 (ses-call-printer (or printer
1140 (ses-col-printer col)
1141 ses--default-printer)
1143 (if (consp ses-call-printer-return)
1144 ;; Printer returned an error.
1145 (setq sig ses-call-printer-return))))
1146 ;; Adjust print width to match column width.
1147 (let ((width (ses-col-width col))
1148 (len (string-width text)))
1151 ;; Fill field to length with spaces.
1152 (setq len (make-string (- width len) ?\s)
1153 text (if (or (stringp value)
1154 (eq ses-call-printer-return t))
1156 (concat len text))))
1158 ;; Spill over into following cells, if possible.
1159 (let ((maxwidth width))
1160 (while (and (> len maxwidth)
1161 (< maxcol ses--numcols)
1162 (or (not (setq x (ses-cell-value row maxcol)))
1165 ;; Set this cell to '*skip* so it won't overwrite our spillover.
1166 (ses-set-cell row maxcol 'value '*skip*))
1167 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
1168 maxcol (1+ maxcol)))
1169 (if (<= len maxwidth)
1170 ;; Fill to complete width of all the fields spanned.
1171 (setq text (concat text (make-string (- maxwidth len) ?\s)))
1172 ;; Not enough room to end of line or next non-nil field. Truncate
1173 ;; if string or decimal; otherwise fill with error indicator.
1174 (setq sig `(error "Too wide" ,text))
1177 (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
1178 ((and (numberp value)
1179 (string-match "\\.[0-9]+" text)
1182 (- (match-end 0) (match-beginning 0))))))
1183 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
1184 (setq text (concat (substring text
1186 (- (match-beginning 0) width))
1187 (substring text (match-end 0)))))
1189 (setq text (make-string maxwidth ?#)))))))))
1190 ;; Substitute question marks for tabs and newlines. Newlines are used as
1191 ;; row-separators; tabs could confuse the reimport logic.
1192 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
1193 (ses-goto-print row col)
1194 (setq startpos (point))
1195 ;; Install the printed result. This is not interruptible.
1196 (let ((inhibit-read-only t)
1198 (let ((inhibit-point-motion-hooks t))
1199 (delete-region (point) (progn
1200 (move-to-column (+ (current-column)
1201 (string-width text)))
1203 ;; We use concat instead of inserting separate strings in order to
1204 ;; reduce the number of cells in the undo list.
1205 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
1206 ;; We use set-text-properties to prevent a wacky print function from
1207 ;; inserting rogue properties, and to ensure that the keymap property is
1208 ;; inherited (is it a bug that only unpropertized strings actually
1209 ;; inherit from surrounding text?)
1210 (set-text-properties 0 (length x) nil x)
1211 (insert-and-inherit x)
1212 (put-text-property startpos (point) 'intangible
1213 (ses-cell-symbol cell))
1214 (when (and (zerop row) (zerop col))
1215 ;; Reconstruct special beginning-of-buffer attributes.
1216 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
1217 (put-text-property (point-min) (point) 'read-only 'ses)
1218 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)))
1219 (if (= row (1- ses--header-row))
1220 ;; This line is part of the header --- force recalc.
1221 (ses-reset-header-string))
1222 ;; If this cell (or a preceding one on the line) previously spilled over
1223 ;; and has gotten shorter, redraw following cells on line recursively.
1224 (when (and (< maxcol ses--numcols)
1225 (eq (ses-cell-value row maxcol) '*skip*))
1226 (ses-set-cell row maxcol 'value nil)
1227 (ses-print-cell row maxcol))
1228 ;; Return to start of cell.
1229 (goto-char startpos)
1232 (defun ses-call-printer (printer &optional value)
1233 "Invoke PRINTER (a string or parenthesized string or function-symbol or
1234 lambda of one argument) on VALUE. Result is the printed cell as a string.
1235 The variable `ses-call-printer-return' is set to t if the printer used
1236 parenthesis to request left-justification, or the error-signal if the
1237 printer signaled one (and \"%s\" is used as the default printer), else nil."
1238 (setq ses-call-printer-return nil)
1239 (condition-case signal
1243 (format printer value)
1245 ((stringp (car-safe printer))
1246 (setq ses-call-printer-return t)
1248 (format (car printer) value)
1253 (or (and (symbolp printer)
1254 (let ((locprn (gethash printer
1255 ses--local-printer-hashmap)))
1257 (ses--locprn-compiled locprn))))
1262 (or (stringp (car-safe value))
1263 (error "Printer should return \"string\" or (\"string\")"))
1264 (setq ses-call-printer-return t)
1267 (setq ses-call-printer-return signal)
1268 (prin1-to-string value t))))
1270 (defun ses-adjust-print-width (col change)
1271 "Insert CHANGE spaces in front of column COL, or at end of line if
1272 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
1273 `inhibit-quit' to t."
1274 (let ((inhibit-read-only t)
1275 (blank (if (> change 0) (make-string change ?\s)))
1276 (at-end (= col ses--numcols)))
1277 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
1278 ;; ses-set-with-undo always returns t for strings.
1279 (1value (ses-set-with-undo 'ses--blank-line
1280 (concat (make-string ses--linewidth ?\s) "\n")))
1281 (dotimes (row ses--numrows)
1282 (ses-goto-print row col)
1284 ;; Insert new columns before newline.
1285 (let ((inhibit-point-motion-hooks t))
1289 (delete-char (- change))))))
1291 (defun ses-print-cell-new-width (row col)
1292 "Same as `ses-print-cell', except if the cell's value is *skip*,
1293 the preceding nonskipped cell is reprinted. This function is used
1294 when the width of cell (ROW,COL) has changed."
1295 (if (not (eq (ses-cell-value row col) '*skip*))
1296 (ses-print-cell row col)
1297 ;;Cell was skipped over - reprint previous
1298 (ses-goto-print row col)
1300 (let ((rowcol (ses-sym-rowcol (get-text-property (point) 'intangible))))
1301 (ses-print-cell (car rowcol) (cdr rowcol)))))
1304 ;;----------------------------------------------------------------------------
1306 ;;----------------------------------------------------------------------------
1309 "Turn off narrowing, to be reenabled at end of command loop."
1310 (if (buffer-narrowed-p)
1311 (setq ses--deferred-narrow t))
1314 (defun ses-goto-data (def &optional col)
1315 "Move point to data area for (DEF,COL). If DEF is a row
1316 number, COL is the column number for a data cell -- otherwise DEF
1317 is one of the symbols ses--col-widths, ses--col-printers,
1318 ses--default-printer, ses--numrows, or ses--numcols."
1320 (let ((inhibit-point-motion-hooks t)) ; In case intangible attrs are wrong.
1324 (goto-char ses--data-marker)
1325 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
1326 ;; Convert def-symbol to offset.
1327 (setq def (plist-get ses-paramlines-plist def))
1328 (or def (signal 'args-out-of-range nil))
1329 (goto-char ses--params-marker)
1330 (forward-line def))))
1332 (defun ses-file-format-extend-parameter-list (new-file-format)
1333 "Extend the global parameters list when file format is updated
1334 from 2 to 3. This happens when local printer function are added
1335 to a sheet that was created with SES version 2. This is not
1336 undoable. Return nil when there was no change, and non nil otherwise."
1339 ((and (= ses--file-format 2) (= 3 new-file-format))
1340 (ses-set-parameter 'ses--file-format 3)
1341 (message "Upgrading from SES-2 to SES-3 file format")
1343 (goto-char ses--params-marker)
1344 (forward-line (plist-get ses-paramlines-plist 'ses--numlocprn ))
1345 (insert (format (plist-get ses-paramfmt-plist 'ses--numlocprn)
1350 (defun ses-set-parameter (def value &optional elem)
1351 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1352 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1353 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
1355 ;; We call ses-goto-data early, using the old values of numrows and numcols
1356 ;; in case one of them is being changed.
1358 (let ((inhibit-read-only t)
1359 (fmt (plist-get ses-paramfmt-plist
1364 (setq oldval (aref (symbol-value def) elem))
1365 (aset (symbol-value def) elem value))
1366 (setq oldval (symbol-value def))
1368 ;; Special undo since it's outside the narrowed buffer.
1369 (let (buffer-undo-list)
1370 (delete-region (point) (line-end-position))
1371 (insert (format fmt (symbol-value def))))
1372 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1375 (defun ses-write-cells ()
1376 "Write cells in `ses--deferred-write' from local variables to data area.
1377 Newlines in the data are escaped."
1378 (let* ((inhibit-read-only t)
1379 (print-escape-newlines t)
1380 rowcol row col cell sym formula printer text)
1381 (setq ses-start-time (float-time))
1382 (with-temp-message " "
1384 (while ses--deferred-write
1385 (ses--time-check "Writing... (%d cells left)"
1386 (length ses--deferred-write))
1387 (setq rowcol (pop ses--deferred-write)
1390 cell (ses-get-cell row col)
1391 sym (ses-cell-symbol cell)
1392 formula (ses-cell-formula cell)
1393 printer (ses-cell-printer cell))
1394 (if (eq (car-safe formula) 'ses-safe-formula)
1395 (setq formula (cadr formula)))
1396 (if (eq (car-safe printer) 'ses-safe-printer)
1397 (setq printer (cadr printer)))
1398 (setq text (prin1-to-string
1399 ;; We could shorten it to (ses-cell SYM VAL) when
1400 ;; the other parameters are nil, but in practice most
1401 ;; cells have non-nil `references', so it's
1402 ;; rather pointless.
1405 ,(unless (equal formula (symbol-value sym))
1408 ,(ses-cell-references cell))))
1409 (ses-goto-data row col)
1410 (delete-region (point) (line-end-position))
1415 ;;----------------------------------------------------------------------------
1416 ;; Formula relocation
1417 ;;----------------------------------------------------------------------------
1419 (defun ses-formula-references (formula &optional result-so-far)
1420 "Produce a list of symbols for cells that this FORMULA's value
1421 refers to. For recursive calls, RESULT-SO-FAR is the list being
1422 constructed, or t to get a wrong-type-argument error when the
1423 first reference is found."
1424 (if (ses-sym-rowcol formula)
1425 ;; Entire formula is one symbol.
1426 (cl-pushnew formula result-so-far :test #'equal)
1429 ((eq (car formula) 'ses-range)
1431 (cdr (funcall 'macroexpand
1432 (list 'ses-range (nth 1 formula)
1434 (cl-pushnew cur result-so-far :test #'equal)))
1435 ((null (eq (car formula) 'quote))
1436 ;;Recursive call for subformulas
1437 (dolist (cur formula)
1438 (setq result-so-far (ses-formula-references cur result-so-far))))
1440 ;;Ignore other stuff
1442 ;; other type of atom are ignored
1446 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1447 "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
1448 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1449 by (ROWINCR,COLINCR)."
1450 (let ((row (car rowcol))
1452 (if (or (< row startrow) (< col startcol))
1454 (setq row (+ row rowincr)
1455 col (+ col colincr))
1456 (if (and (>= row startrow) (>= col startcol)
1457 (< row ses--numrows) (< col ses--numcols))
1458 ;;Relocate this variable
1459 (ses-create-cell-symbol row col)
1460 ;;Delete reference to a deleted cell
1463 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1464 "Produce a copy of FORMULA where all symbols that refer to cells in row
1465 STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
1466 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1467 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1469 If ROWINCR or COLINCR is negative, references to cells being deleted are
1471 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1473 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1474 (let (rowcol result)
1475 (if (or (atom formula) (eq (car formula) 'quote))
1476 (if (and (setq rowcol (ses-sym-rowcol formula))
1477 (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name formula)))
1478 (ses-relocate-symbol formula rowcol
1479 startrow startcol rowincr colincr)
1480 formula) ; Pass through as-is.
1481 (dolist (cur formula)
1482 (setq rowcol (ses-sym-rowcol cur))
1485 (setq cur (ses-relocate-symbol cur rowcol
1486 startrow startcol rowincr colincr))
1489 ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
1490 ;; don't change the flag if it's already 'range, since range implies
1492 (unless ses-relocate-return
1493 (setq ses-relocate-return 'delete))))
1494 ((eq (car-safe cur) 'ses-range)
1495 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1498 ((or (atom cur) (eq (car cur) 'quote))
1499 ;; Constants pass through unchanged.
1502 ;; Recursively copy and alter subformulas.
1503 (push (ses-relocate-formula cur startrow startcol
1506 (nreverse result))))
1508 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1509 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1510 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1511 new range, or nil if the entire range is deleted. If new rows are being added
1512 just beyond the end of a row range, or new columns just beyond a column range,
1513 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1514 if the range was altered."
1515 (let* ((minorig (cadr range))
1516 (minrowcol (ses-sym-rowcol minorig))
1517 (min (ses-relocate-symbol minorig minrowcol
1520 (maxorig (nth 2 range))
1521 (maxrowcol (ses-sym-rowcol maxorig))
1522 (max (ses-relocate-symbol maxorig maxrowcol
1527 ((and (not min) (not max))
1528 (setq range nil)) ; The entire range is deleted.
1530 ;; Inserting or deleting rows.
1533 ;; Chopped off beginning of range.
1534 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1535 ses-relocate-return 'range))
1538 ;; Trying to insert a nonexistent row.
1539 (setq max (ses-create-cell-symbol (1- ses--numrows)
1541 ;; End of range is being deleted.
1542 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1543 ses-relocate-return 'range))
1545 (= (car maxrowcol) (1- startrow))
1546 (= (cdr minrowcol) (cdr maxrowcol))
1547 ;; Insert after ending row of vertical range --- include it.
1548 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1549 (cdr maxrowcol))))))
1551 ;; Inserting or deleting columns.
1554 ;; Chopped off beginning of range.
1555 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1556 ses-relocate-return 'range))
1559 ;; Trying to insert a nonexistent column.
1560 (setq max (ses-create-cell-symbol (car maxrowcol)
1562 ;; End of range is being deleted.
1563 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1564 ses-relocate-return 'range))
1566 (= (cdr maxrowcol) (1- startcol))
1567 (= (car minrowcol) (car maxrowcol))
1568 ;; Insert after ending column of horizontal range --- include it.
1569 (setq max (ses-create-cell-symbol (car maxrowcol)
1570 (+ startcol colincr -1)))))))
1572 (if (/= (- (funcall field maxrowcol)
1573 (funcall field minrowcol))
1574 (- (funcall field (ses-sym-rowcol max))
1575 (funcall field (ses-sym-rowcol min))))
1576 ;; This range has changed size.
1577 (setq ses-relocate-return 'range))
1578 `(ses-range ,min ,max ,@(cl-cdddr range)))))
1580 (defun ses-relocate-all (minrow mincol rowincr colincr)
1581 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1582 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1585 (let (mycell newval xrow)
1586 (dotimes-with-progress-reporter
1587 (row ses--numrows) "Relocating formulas..."
1588 (dotimes (col ses--numcols)
1589 (setq ses-relocate-return nil
1590 mycell (ses-get-cell row col)
1591 newval (ses-relocate-formula (ses-cell-formula mycell)
1592 minrow mincol rowincr colincr)
1593 xrow (- row rowincr))
1594 (ses-set-cell row col 'formula newval)
1595 (if (eq ses-relocate-return 'range)
1596 ;; This cell contains a (ses-range X Y) where a cell has been
1597 ;; inserted or deleted in the middle of the range.
1598 (push (cons row col) reform))
1599 (if ses-relocate-return
1600 ;; This cell referred to a cell that's been deleted or is no
1601 ;; longer part of the range. We can't fix that now because
1602 ;; reference lists cells have been partially updated.
1603 (cl-pushnew (ses-create-cell-symbol row col)
1604 ses--deferred-recalc :test #'equal))
1605 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1606 minrow mincol rowincr colincr))
1607 (ses-set-cell row col 'references newval)
1608 (and (>= row minrow) (>= col mincol)
1609 (let ((sym (ses-cell-symbol row col))
1610 (xcol (- col colincr)))
1616 (ses-create-cell-symbol xrow xcol))))
1617 ;; This is a renamed cell, do not update the cell
1618 ;; name, but just update the coordinate property.
1619 (put sym 'ses-cell (cons row col))
1620 (ses-set-cell row col 'symbol
1621 (setq sym (ses-create-cell-symbol row col)))
1622 (unless (and (boundp sym) (local-variable-p sym))
1623 (set (make-local-variable sym) nil)
1624 (put sym 'ses-cell (cons row col)))))) )))
1625 ;; Relocate the cell values.
1626 (let (oldval myrow mycol xrow xcol)
1628 ((and (<= rowincr 0) (<= colincr 0))
1629 ;; Deletion of rows and/or columns.
1630 (dotimes-with-progress-reporter
1631 (row (- ses--numrows minrow)) "Relocating variables..."
1632 (setq myrow (+ row minrow))
1633 (dotimes (col (- ses--numcols mincol))
1634 (setq mycol (+ col mincol)
1635 xrow (- myrow rowincr)
1636 xcol (- mycol colincr))
1637 (let ((sym (ses-cell-symbol myrow mycol))
1638 (xsym (ses-create-cell-symbol xrow xcol)))
1639 ;; Make the value relocation only when if the cell is not
1640 ;; a renamed cell. Otherwise this is not needed.
1642 (ses-set-cell myrow mycol 'value
1643 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1644 (ses-cell-value xrow xcol)
1645 ;;Cell is off the end of the array
1646 (symbol-value xsym))))))))
1648 ((and (wholenump rowincr) (wholenump colincr))
1649 ;; Insertion of rows and/or columns. Run the loop backwards.
1650 (let ((disty (1- ses--numrows))
1651 (distx (1- ses--numcols))
1653 (dotimes-with-progress-reporter
1654 (row (- ses--numrows minrow)) "Relocating variables..."
1655 (setq myrow (- disty row))
1656 (dotimes (col (- ses--numcols mincol))
1657 (setq mycol (- distx col)
1658 xrow (- myrow rowincr)
1659 xcol (- mycol colincr))
1660 (if (or (< xrow minrow) (< xcol mincol))
1661 ;; Newly-inserted value.
1663 ;; Transfer old value.
1664 (setq oldval (ses-cell-value xrow xcol)))
1665 (ses-set-cell myrow mycol 'value oldval)))
1666 t)) ; Make testcover happy by returning non-nil here.
1668 (error "ROWINCR and COLINCR must have the same sign"))))
1669 ;; Reconstruct reference lists for cells that contain ses-ranges that have
1672 (message "Fixing ses-ranges...")
1674 (setq ses-start-time (float-time))
1676 (ses--time-check "Fixing ses-ranges... (%d left)" (length reform))
1677 (setq row (caar reform)
1679 reform (cdr reform))
1680 (ses-cell-set-formula row col (ses-cell-formula row col))))
1684 ;;----------------------------------------------------------------------------
1686 ;;----------------------------------------------------------------------------
1688 (defun ses-begin-change ()
1689 "For undo, remember point before we start changing hidden stuff."
1690 (let ((inhibit-read-only t))
1691 (insert-and-inherit "X")
1692 (delete-region (1- (point)) (point))))
1694 (defun ses-setter-with-undo (accessors newval &rest args)
1695 "Set a field/variable and record it so it can be undone.
1696 Result is non-nil if field/variable has changed."
1697 (let ((oldval (apply (car accessors) args)))
1698 (unless (equal-including-properties oldval newval)
1699 (push `(apply ses-setter-with-undo ,accessors ,oldval ,@args)
1701 (apply (cdr accessors) newval args)
1704 (defun ses-aset-with-undo (array idx newval)
1705 (ses-setter-with-undo (eval-when-compile
1707 (lambda (newval array idx) (aset array idx newval))))
1710 (defun ses-set-with-undo (sym newval)
1711 (ses-setter-with-undo
1713 (cons (lambda (sym) (if (boundp sym) (symbol-value sym) :ses--unbound))
1714 (lambda (newval sym) (if (eq newval :ses--unbound)
1716 (set sym newval)))))
1719 ;;----------------------------------------------------------------------------
1720 ;; Startup for major mode
1721 ;;----------------------------------------------------------------------------
1724 "Parse the current buffer and set up buffer-local variables.
1725 Does not execute cell formulas or print functions."
1727 ;; Read our global parameters, which should be a 3-element list.
1728 (goto-char (point-max))
1729 (search-backward ";; Local Variables:\n" nil t)
1731 (setq ses--params-marker (point-marker))
1732 (let* ((params (ignore-errors (read (current-buffer))))
1733 (params-len (safe-length params)))
1734 (or (and (>= params-len 3)
1736 (numberp (car params))
1737 (numberp (cadr params))
1738 (>= (cadr params) 0)
1739 (numberp (nth 2 params))
1740 (> (nth 2 params) 0)
1741 (or (<= params-len 3)
1742 (let ((numlocprn (nth 3 params)))
1743 (and (integerp numlocprn) (>= numlocprn 0)))))
1744 (error "Invalid SES file"))
1745 (setq ses--file-format (car params)
1746 ses--numrows (cadr params)
1747 ses--numcols (nth 2 params)
1748 ses--numlocprn (or (nth 3 params) 0))
1749 (when (= ses--file-format 1)
1750 (let (buffer-undo-list) ; This is not undoable.
1751 (ses-goto-data 'ses--header-row)
1752 (insert "(ses-header-row 0)\n")
1753 (ses-set-parameter 'ses--file-format 3)
1754 (message "Upgrading from SES-1 to SES-2 file format")))
1755 (or (<= ses--file-format 3)
1756 (error "This file needs a newer version of the SES library code"))
1757 ;; Initialize cell array.
1758 (setq ses--cells (make-vector ses--numrows nil))
1759 (dotimes (row ses--numrows)
1760 (aset ses--cells row (make-vector ses--numcols nil)))
1761 ;; initialize local printer map.
1762 (clrhash ses--local-printer-hashmap))
1764 ;; Skip over print area, which we assume is correct.
1765 (goto-char (point-min))
1766 (forward-line ses--numrows)
1767 (or (looking-at-p ses-print-data-boundary)
1768 (error "Missing marker between print and data areas"))
1770 (setq ses--data-marker (point-marker))
1771 (forward-char (1- (length ses-print-data-boundary)))
1772 ;; Initialize printer and symbol lists.
1773 (mapc #'ses-printer-record ses-standard-printer-functions)
1774 (setq ses--symbolic-formulas nil)
1776 ;; Load local printer definitions.
1777 ;; This must be loaded *BEFORE* cells and column printers because the latter
1780 (forward-line (* ses--numrows (1+ ses--numcols)))
1781 (let ((numlocprn ses--numlocprn))
1782 (setq ses--numlocprn 0)
1783 (dotimes (_ numlocprn)
1784 (let ((x (read (current-buffer))))
1785 (or (and (looking-at-p "\n")
1786 (eq (car-safe x) 'ses-local-printer)
1787 (apply #'ses--local-printer (cdr x)))
1788 (error "local printer-def error"))
1789 (setq ses--numlocprn (1+ ses--numlocprn))))))
1790 ;; Load cell definitions.
1791 (dotimes (row ses--numrows)
1792 (dotimes (col ses--numcols)
1793 (let* ((x (read (current-buffer)))
1794 (sym (car-safe (cdr-safe x))))
1795 (or (and (looking-at-p "\n")
1796 (eq (car-safe x) 'ses-cell)
1797 (ses-create-cell-variable sym row col))
1798 (error "Cell-def error"))
1799 (apply #'ses--cell (cdr x))))
1800 (or (looking-at-p "\n\n")
1801 (error "Missing blank line between rows")))
1802 ;; Skip local printer function declaration --- that were already loaded.
1803 (forward-line (+ 2 ses--numlocprn))
1804 ;; Load global parameters.
1805 (let ((widths (read (current-buffer)))
1806 (n1 (char-after (point)))
1807 (printers (read (current-buffer)))
1808 (n2 (char-after (point)))
1809 (def-printer (read (current-buffer)))
1810 (n3 (char-after (point)))
1811 (head-row (read (current-buffer)))
1812 (n4 (char-after (point))))
1813 (or (and (eq (car-safe widths) 'ses-column-widths)
1815 (eq (car-safe printers) 'ses-column-printers)
1817 (eq (car-safe def-printer) 'ses-default-printer)
1819 (eq (car-safe head-row) 'ses-header-row)
1821 (error "Invalid SES global parameters"))
1822 (1value (eval widths t))
1823 (1value (eval def-printer t))
1824 (1value (eval printers t))
1825 (1value (eval head-row t)))
1826 ;; Should be back at global-params.
1828 (or (looking-at-p ses-initial-global-parameters-re)
1829 (error "Problem with column-defs or global-params"))
1830 ;; Check for overall newline count in definitions area.
1832 (let ((start (point)))
1833 (ses-goto-data 'ses--numrows)
1834 (or (= (point) start)
1835 (error "Extraneous newlines someplace?"))))
1838 "Set up for display of only the printed cell values.
1840 Narrows the buffer to show only the print area. Gives it `read-only' and
1841 `intangible' properties. Sets up highlighting for current cell."
1843 (let ((end (point-min))
1844 (inhibit-point-motion-hooks t)
1846 (with-silent-modifications
1847 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1848 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1849 (mapc #'delete-overlay (overlays-in (point-min) (point-max)))
1850 ;; The print area is read-only (except for our special commands) and
1851 ;; uses a special keymap.
1852 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1853 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1854 ;; For the beginning of the buffer, we want the read-only and keymap
1855 ;; attributes to be inherited from the first character.
1856 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1857 ;; Create intangible properties, which also indicate which cell the text
1859 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1860 (dotimes (col ses--numcols)
1862 sym (ses-cell-symbol row col))
1863 (unless (eq (symbol-value sym) '*skip*)
1864 ;; Include skipped cells following this one.
1865 (while (and (< col (1- ses--numcols))
1866 (eq (ses-cell-value row (1+ col)) '*skip*))
1867 (setq end (+ end (ses-col-width col) 1)
1868 ;; Beware: Modifying the iteration variable of `dotimes'
1869 ;; may or may not affect the iteration!
1871 (setq end (save-excursion
1873 (move-to-column (+ (current-column) (- end pos)
1874 (ses-col-width col)))
1876 (+ end (ses-col-width col) 1)
1879 (put-text-property pos end 'intangible sym))))))
1880 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1881 ;; because column A must be at least 1 column wide.
1882 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1883 (overlay-put ses--curcell-overlay 'face 'underline))
1885 (defun ses-cleanup ()
1886 "Cleanup when changing a buffer from SES mode to something else.
1887 Delete overlays, remove special text properties."
1889 (let ((inhibit-read-only t)
1890 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1891 ;; user "the file is modified, do you really want to make modifications
1892 ;; to this buffer", where the "modifications" refer to the irrelevant
1893 ;; set-text-properties below.
1894 (buffer-file-name nil)
1895 (was-modified (buffer-modified-p)))
1896 ;; Delete read-only, keymap, and intangible properties.
1897 (set-text-properties (point-min) (point-max) nil)
1899 (mapc #'delete-overlay (overlays-in (point-min) (point-max)))
1900 (unless was-modified
1901 (restore-buffer-modified-p nil))))
1905 "Major mode for Simple Emacs Spreadsheet.
1907 When you invoke SES in a new buffer, it is divided into cells
1908 that you can enter data into. You can navigate the cells with
1909 the arrow keys and add more cells with the tab key. The contents
1910 of these cells can be numbers, text, or Lisp expressions. (To
1911 enter text, enclose it in double quotes.)
1913 In an expression, you can use cell coordinates to refer to the
1914 contents of another cell. For example, you can sum a range of
1915 cells with `(+ A1 A2 A3)'. There are specialized functions like
1916 `ses+' (addition for ranges with empty cells), `ses-average' (for
1917 performing calculations on cells), and `ses-range' and `ses-select'
1918 \(for extracting ranges of cells).
1920 Each cell also has a print function that controls how it is
1923 Each SES buffer is divided into a print area and a data area.
1924 Normally, you can simply use SES to look at and manipulate the print
1925 area, and let SES manage the data area outside the visible region.
1927 See \"ses-example.ses\" (in `data-directory') for an example
1928 spreadsheet, and the Info node `(ses)Top.'
1930 In the following, note the separate keymaps for cell editing mode
1931 and print mode specifications. Key definitions:
1934 These key definitions are active only in the print area (the visible
1936 \\{ses-mode-print-map}
1937 These are active only in the minibuffer, when entering or editing a
1939 \\{ses-mode-edit-map}"
1941 (unless (and (boundp 'ses--deferred-narrow)
1942 (eq ses--deferred-narrow 'ses-mode))
1943 (kill-all-local-variables)
1945 (setq major-mode 'ses-mode
1947 next-line-add-newlines nil
1949 ;; SES deliberately puts lots of trailing whitespace in its buffer.
1950 show-trailing-whitespace nil
1951 ;; Cell ranges do not work reasonably without this.
1952 transient-mark-mode t
1953 ;; Not to use tab characters for safe (tabs may do bad for column
1955 indent-tabs-mode nil)
1956 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1957 ;; This makes revert impossible if the buffer is read-only.
1958 ;; (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1959 (setq header-line-format '(:eval (progn
1960 (when (/= (window-hscroll)
1961 ses--header-hscroll)
1962 ;; Reset ses--header-hscroll first,
1963 ;; to avoid recursion problems when
1964 ;; debugging ses-create-header-string
1965 (setq ses--header-hscroll
1967 (ses-create-header-string))
1968 ses--header-string)))
1969 (let ((was-empty (zerop (buffer-size)))
1970 (was-modified (buffer-modified-p)))
1973 ;; Initialize buffer to contain one cell, for now.
1974 (insert ses-initial-file-contents))
1978 (unless (equal ses-initial-default-printer
1979 (1value ses--default-printer))
1980 (1value (ses-read-default-printer ses-initial-default-printer)))
1981 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1982 (1value (ses-set-column-width 0 ses-initial-column-width)))
1984 (if (> (car ses-initial-size) (1value ses--numrows))
1985 (1value (ses-insert-row (1- (car ses-initial-size)))))
1986 (if (> (cdr ses-initial-size) (1value ses--numcols))
1987 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1989 (restore-buffer-modified-p was-modified)
1990 (buffer-disable-undo)
1991 (buffer-enable-undo)
1992 (goto-char (point-min))))
1993 (use-local-map ses-mode-map)
1994 ;; Set the deferred narrowing flag (we can't narrow until after
1995 ;; after-find-file completes). If .ses is on the auto-load alist and the
1996 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
1997 ;; special flag to detect this (will be reset by ses-command-hook). For
1998 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
1999 ;; so use an idle timer to make sure.
2000 (setq ses--deferred-narrow 'ses-mode)
2001 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
2002 (run-with-idle-timer 0.01 nil 'ses-command-hook)
2003 (run-mode-hooks 'ses-mode-hook)))
2005 (put 'ses-mode 'mode-class 'special)
2007 (defun ses-command-hook ()
2008 "Invoked from `post-command-hook'. If point has moved to a different cell,
2009 moves the underlining overlay. Performs any recalculations or cell-data
2010 writes that have been deferred. If buffer-narrowing has been deferred,
2011 narrows the buffer now."
2013 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
2014 (when ses--deferred-recalc
2015 ;; We reset the deferred list before starting on the recalc --- in
2016 ;; case of error, we don't want to retry the recalc after every
2018 (ses-initialize-Dijkstra-attempt)
2019 (let ((old ses--deferred-recalc))
2020 (setq ses--deferred-recalc nil)
2021 (ses-update-cells old)))
2022 (when ses--deferred-write
2023 ;; We don't reset the deferred list before starting --- the most
2024 ;; likely error is keyboard-quit, and we do want to keep trying these
2025 ;; writes after a quit.
2027 (push '(apply ses-widen) buffer-undo-list))
2028 (when ses--deferred-narrow
2029 ;; We're not allowed to narrow the buffer until after-find-file has
2030 ;; read the local variables at the end of the file. Now it's safe to
2031 ;; do the narrowing.
2032 (narrow-to-region (point-min) ses--data-marker)
2033 (setq ses--deferred-narrow nil))
2034 ;; Update the mode line.
2035 (let ((oldcell ses--curcell))
2037 (unless (eq ses--curcell oldcell)
2040 (setq mode-line-process nil))
2041 ((atom ses--curcell)
2042 (setq mode-line-process (list " cell "
2043 (symbol-name ses--curcell))))
2045 (setq mode-line-process (list " range "
2046 (symbol-name (car ses--curcell))
2048 (symbol-name (cdr ses--curcell))))))
2049 (force-mode-line-update)))
2050 ;; Use underline overlay for single-cells only, turn off otherwise.
2051 (if (listp ses--curcell)
2052 (move-overlay ses--curcell-overlay 2 2)
2053 (let ((next (next-single-property-change (point) 'intangible)))
2054 (move-overlay ses--curcell-overlay (point) (1- next))))
2055 (when (not (pos-visible-in-window-p))
2056 ;; Scrolling will happen later.
2057 (run-with-idle-timer 0.01 nil 'ses-command-hook)
2058 (setq ses--curcell t)))
2059 ;; Prevent errors in this post-command-hook from silently erasing the hook!
2061 (unless executing-kbd-macro
2063 (message "%s" (error-message-string err))))
2064 nil) ; Make coverage-tester happy.
2066 (defun ses-create-header-string ()
2067 "Set up `ses--header-string' as the buffer's header line.
2068 Based on the current set of columns and `window-hscroll' position."
2069 (let ((totwidth (- (window-hscroll)))
2071 ;; Leave room for the left-side fringe and scrollbar.
2072 (push (propertize " " 'display '((space :align-to 0))) result)
2073 (dotimes (col ses--numcols)
2074 (setq width (ses-col-width col)
2075 totwidth (+ totwidth width 1))
2077 ;; Scrolled so intercolumn space is leftmost.
2079 (when (> totwidth 1)
2080 (if (> ses--header-row 0)
2082 (ses-goto-print (1- ses--header-row) col)
2083 (setq x (buffer-substring-no-properties (point)
2085 ;; Strip trailing space.
2086 (if (string-match "[ \t]+\\'" x)
2087 (setq x (substring x 0 (match-beginning 0))))
2088 ;; Cut off excess text.
2089 (if (>= (length x) totwidth)
2090 (setq x (substring x 0 (- totwidth -1)))))
2091 (setq x (ses-column-letter col)))
2092 (push (propertize x 'face ses-box-prop) result)
2093 (push (propertize "."
2094 'display `((space :align-to ,(1- totwidth)))
2097 ;; Allow the following space to be squished to make room for the 3-D box
2098 ;; Coverage test ignores properties, thinks this is always a space!
2099 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2101 (if (> ses--header-row 0)
2102 (push (propertize (format " [row %d]" ses--header-row)
2103 'display '((height (- 1))))
2105 (setq ses--header-string (apply #'concat (nreverse result)))))
2108 ;;----------------------------------------------------------------------------
2109 ;; Redisplay and recalculation
2110 ;;----------------------------------------------------------------------------
2112 (defun ses-jump (sym)
2113 "Move point to cell SYM."
2114 (interactive "SJump to cell: ")
2115 (let ((rowcol (ses-sym-rowcol sym)))
2116 (or rowcol (error "Invalid cell name"))
2117 (if (eq (symbol-value sym) '*skip*)
2118 (error "Cell is covered by preceding cell"))
2119 (ses-goto-print (car rowcol) (cdr rowcol))))
2121 (defun ses-jump-safe (cell)
2122 "Like `ses-jump', but no error if invalid cell."
2126 (defun ses-reprint-all (&optional nonarrow)
2127 "Recreate the display area. Calls all printer functions. Narrows to
2128 print area if NONARROW is nil."
2132 (setq ses--deferred-narrow t))
2133 (let ((startcell (get-text-property (point) 'intangible))
2134 (inhibit-read-only t))
2136 (goto-char (point-min))
2137 (search-forward ses-print-data-boundary)
2138 (backward-char (length ses-print-data-boundary))
2139 (delete-region (point-min) (point))
2140 ;; Insert all blank lines before printing anything, so ses-print-cell can
2141 ;; find the data area when inserting or deleting *skip* values for cells.
2142 (dotimes (_ ses--numrows)
2143 (insert-and-inherit ses--blank-line))
2144 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2145 (if (eq (ses-cell-value row 0) '*skip*)
2146 ;; Column deletion left a dangling skip.
2147 (ses-set-cell row 0 'value nil))
2148 (dotimes (col ses--numcols)
2149 (ses-print-cell row col))
2150 (beginning-of-line 2))
2151 (ses-jump-safe startcell)))
2153 (defun ses-initialize-Dijkstra-attempt ()
2154 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2155 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2157 ;; These functions use the variables 'row' and 'col' that are dynamically bound
2158 ;; by ses-print-cell. We define these variables at compile-time to make the
2165 (defun ses-recalculate-cell ()
2166 "Recalculate and reprint the current cell or range.
2168 For an individual cell, shows the error if the formula or printer
2169 signals one, or otherwise shows the cell's complete value. For a range, the
2170 cells are recalculated in \"natural\" order, so cells that other cells refer
2171 to are recalculated first."
2173 (ses-check-curcell 'range)
2175 (ses-initialize-Dijkstra-attempt)
2176 (let (sig cur-rowcol)
2177 (setq ses-start-time (float-time))
2178 (if (atom ses--curcell)
2180 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2182 (setf (ses-cell-property :ses-Dijkstra-attempt
2185 (cons ses--Dijkstra-attempt-nb 0))
2186 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2187 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2188 (cdr cur-rowcol)))))
2189 ;; First, recalculate all cells that don't refer to other cells and
2190 ;; produce a list of cells with references.
2191 (ses-dorange ses--curcell
2192 (ses--time-check "Recalculating... %s" (ses-cell-symbol row col))
2195 ;; The t causes an error if the cell has references. If no
2196 ;; references, the t will be the result value.
2197 (1value (ses-formula-references (ses-cell-formula row col) t))
2198 (setf (ses-cell-property :ses-Dijkstra-attempt row col)
2199 (cons ses--Dijkstra-attempt-nb 0))
2200 (when (setq sig (ses-calculate-cell row col t))
2201 (nconc sig (list (ses-cell-symbol row col)))))
2202 (wrong-type-argument
2203 ;; The formula contains a reference.
2204 (cl-pushnew (ses-cell-symbol row col) ses--deferred-recalc
2206 ;; Do the update now, so we can force recalculation.
2207 (let ((x ses--deferred-recalc))
2208 (setq ses--deferred-recalc nil)
2209 (condition-case hold
2210 (ses-update-cells x t)
2211 (error (setq sig hold))))
2214 (message "%s" (error-message-string sig)))
2215 ((consp ses--curcell)
2218 (princ (symbol-value ses--curcell))))))
2220 (defun ses-recalculate-all ()
2221 "Recalculate and reprint all cells."
2223 (let ((startcell (get-text-property (point) 'intangible))
2224 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2225 (1- ses--numcols)))))
2226 (ses-recalculate-cell)
2227 (ses-jump-safe startcell)))
2229 (defun ses-truncate-cell ()
2230 "Reprint current cell, but without spillover into any following blank cells."
2233 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2236 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
2237 (eq (ses-cell-value row (1+ col)) '*skip*))
2238 ;; This cell has spill-over. We'll momentarily pretend the following cell
2241 (list (ses-cell-symbol row (1+ col)))
2243 (ses-print-cell row col))
2244 ;; Now remove the *skip*. ses-print-cell is always nil here.
2245 (ses-set-cell row (1+ col) 'value nil)
2246 (1value (ses-print-cell row (1+ col))))))
2248 (defun ses-reconstruct-all ()
2249 "Reconstruct buffer based on cell data stored in Emacs variables."
2252 ;;Reconstruct reference lists.
2254 ;;Delete old reference lists
2255 (dotimes-with-progress-reporter
2256 (row ses--numrows) "Deleting references..."
2257 (dotimes (col ses--numcols)
2258 (ses-set-cell row col 'references nil)))
2259 ;;Create new reference lists
2260 (dotimes-with-progress-reporter
2261 (row ses--numrows) "Computing references..."
2262 (dotimes (col ses--numcols)
2263 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2264 (setq x (ses-sym-rowcol ref)
2267 (ses-set-cell yrow ycol 'references
2268 (cons (ses-cell-symbol row col)
2269 (ses-cell-references yrow ycol)))))))
2270 ;; Delete everything and reconstruct basic data area.
2272 (let ((inhibit-read-only t))
2273 (goto-char (point-max))
2274 (if (search-backward ";; Local Variables:\n" nil t)
2275 (delete-region (point-min) (point))
2276 ;; Buffer is quite screwed up --- can't even save the user-specified
2278 (delete-region (point-min) (point-max))
2279 (insert ses-initial-file-trailer)
2280 (goto-char (point-min)))
2281 ;; Create a blank display area.
2282 (dotimes (_ ses--numrows)
2283 (insert ses--blank-line))
2284 (insert ses-print-data-boundary)
2285 (backward-char (1- (length ses-print-data-boundary)))
2286 (setq ses--data-marker (point-marker))
2287 (forward-char (1- (length ses-print-data-boundary)))
2288 ;; Placeholders for cell data.
2289 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2290 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
2292 (insert ses-initial-global-parameters)
2293 (backward-char (1- (length ses-initial-global-parameters)))
2294 (setq ses--params-marker (point-marker))
2295 (forward-char (1- (length ses-initial-global-parameters))))
2296 (ses-set-parameter 'ses--col-widths ses--col-widths)
2297 (ses-set-parameter 'ses--col-printers ses--col-printers)
2298 (ses-set-parameter 'ses--default-printer ses--default-printer)
2299 (ses-set-parameter 'ses--header-row ses--header-row)
2300 (ses-set-parameter 'ses--numrows ses--numrows)
2301 (ses-set-parameter 'ses--numcols ses--numcols)
2302 ;;Keep our old narrowing
2304 (ses-recalculate-all)
2305 (goto-char (point-min)))
2308 ;;----------------------------------------------------------------------------
2309 ;; Input of cell formulas
2310 ;;----------------------------------------------------------------------------
2312 (defun ses-edit-cell (row col newval)
2313 "Display current cell contents in minibuffer, for editing. Returns nil if
2314 cell formula was unsafe and user declined confirmation."
2317 (barf-if-buffer-read-only)
2319 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2322 (formula (ses-cell-formula row col))
2324 (if (eq (car-safe formula) 'ses-safe-formula)
2325 (setq formula (cadr formula)))
2326 (if (eq (car-safe formula) 'quote)
2327 (setq initial (format "'%S" (cadr formula)))
2328 (setq initial (prin1-to-string formula)))
2329 (if (stringp formula)
2330 ;; Position cursor inside close-quote.
2331 (setq initial (cons initial (length initial))))
2333 (read-from-minibuffer (format "Cell %s: " ses--curcell)
2336 t ; Convert to Lisp object.
2337 'ses-read-cell-history)))))
2338 (when (ses-warn-unsafe newval 'unsafep)
2340 (ses-cell-set-formula row col newval)
2343 (defun ses-read-cell (row col newval)
2344 "Self-insert for initial character of cell function."
2346 (let* ((initial (this-command-keys))
2347 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2348 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
2349 (barf-if-buffer-read-only)
2352 (if (equal initial "\"")
2354 (if (not (stringp curval)) (setq curval nil))
2355 (read-string (if curval
2356 (format "String Cell %s (default %s): "
2357 ses--curcell curval)
2358 (format "String Cell %s: " ses--curcell))
2359 nil 'ses-read-string-history curval))
2360 (read-from-minibuffer
2361 (format "Cell %s: " ses--curcell)
2362 (cons (if (equal initial "(") "()" initial) 2)
2364 t ; Convert to Lisp object.
2365 'ses-read-cell-history
2366 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2369 (when (ses-edit-cell row col newval)
2370 (ses-command-hook) ; Update cell widths before movement.
2371 (dolist (x ses-after-entry-functions)
2374 (defun ses-read-symbol (row col symb)
2375 "Self-insert for a symbol as a cell formula. The set of all symbols that
2376 have been used as formulas in this spreadsheet is available for completions."
2378 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2380 (barf-if-buffer-read-only)
2381 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2382 ses--symbolic-formulas))
2385 (if (string= newval "")
2386 nil ; Don't create zero-length symbols!
2387 (list 'quote (intern newval))))))
2388 (when (ses-edit-cell row col symb)
2389 (ses-command-hook) ; Update cell widths before movement.
2390 (dolist (x ses-after-entry-functions)
2393 (defun ses-clear-cell-forward (count)
2394 "Delete formula and printer for current cell and then move to next cell.
2395 With prefix, deletes several cells."
2398 (1value (ses-clear-cell-backward (- count)))
2403 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2404 (or rowcol (signal 'end-of-buffer nil))
2405 (ses-clear-cell (car rowcol) (cdr rowcol)))
2408 (defun ses-clear-cell-backward (count)
2409 "Move to previous cell and then delete it. With prefix, deletes several
2413 (1value (ses-clear-cell-forward (- count)))
2414 (ses-check-curcell 'end)
2417 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
2419 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2420 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2423 ;;----------------------------------------------------------------------------
2424 ;; Input of cell-printer functions
2425 ;;----------------------------------------------------------------------------
2427 (defun ses-read-printer (prompt default)
2428 "Common code for functions `ses-read-cell-printer', `ses-read-column-printer',
2429 `ses-read-default-printer' and `ses-define-local-printer'.
2430 PROMPT should end with \": \". Result is t if operation was
2432 (barf-if-buffer-read-only)
2435 (setq prompt (format "%s (default %S): "
2436 (substring prompt 0 -2)
2438 (let ((new (read-from-minibuffer prompt
2439 nil ; Initial contents.
2441 t ; Evaluate the result.
2442 'ses-read-printer-history
2443 (prin1-to-string default))))
2444 (if (equal new default)
2445 ;; User changed mind, decided not to change printer.
2447 (ses-printer-validate new)
2450 (stringp (car-safe new))
2451 (and (symbolp new) (gethash new ses--local-printer-hashmap))
2452 (ses-warn-unsafe new 'unsafep-function)
2456 (defun ses-read-cell-printer (newval)
2457 "Set the printer function for the current cell or range.
2459 A printer function is either a string (a format control-string with one
2460 %-sequence -- result from format will be right-justified), or a list of one
2461 string (result from format will be left-justified), or a lambda-expression of
2462 one argument, or a symbol that names a function of one argument. In the
2463 latter two cases, the function's result should be either a string (will be
2464 right-justified) or a list of one string (will be left-justified)."
2467 (ses-check-curcell 'range)
2468 ;;Default is none if not all cells in range have same printer
2469 (catch 'ses-read-cell-printer
2470 (ses-dorange ses--curcell
2471 (let ((x (ses-cell-printer row col)))
2472 (if (eq (car-safe x) 'ses-safe-printer)
2476 (unless (equal default x)
2477 ;;Range contains differing printer functions
2479 (throw 'ses-read-cell-printer t))))))
2480 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2482 (unless (eq newval t)
2484 (ses-dorange ses--curcell
2485 (ses-set-cell row col 'printer newval)
2486 (ses-print-cell row col))))
2488 (defun ses-read-column-printer (col newval)
2489 "Set the printer function for the current column.
2490 See `ses-read-cell-printer' for input forms."
2492 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2494 (list col (ses-read-printer (format "Column %s printer: "
2495 (ses-column-letter col))
2496 (ses-col-printer col)))))
2498 (unless (eq newval t)
2500 (ses-set-parameter 'ses--col-printers newval col)
2502 (dotimes (row ses--numrows)
2503 (ses-print-cell row col)))))
2505 (defun ses-read-default-printer (newval)
2506 "Set the default printer function for cells that have no other.
2507 See `ses-read-cell-printer' for input forms."
2509 (list (ses-read-printer "Default printer: " ses--default-printer)))
2510 (unless (eq newval t)
2512 (ses-set-parameter 'ses--default-printer newval)
2513 (ses-reprint-all t)))
2516 ;;----------------------------------------------------------------------------
2517 ;; Spreadsheet size adjustments
2518 ;;----------------------------------------------------------------------------
2520 (defun ses-insert-row (count)
2521 "Insert a new row before the current one.
2522 With prefix, insert COUNT rows before current one."
2524 (ses-check-curcell 'end)
2525 (or (> count 0) (signal 'args-out-of-range nil))
2527 (let ((inhibit-quit t)
2528 (inhibit-read-only t)
2529 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2531 ;;Create a new set of cell-variables
2532 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2533 0 (1- ses--numcols))
2534 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2536 (ses-goto-print row 0)
2537 (dotimes-with-progress-reporter (x count) "Inserting row..."
2538 ;;Create a row of empty cells. The `symbol' fields will be set by
2539 ;;the call to ses-relocate-all.
2540 (setq newrow (make-vector ses--numcols nil))
2541 (dotimes (col ses--numcols)
2542 (aset newrow col (ses-make-cell)))
2543 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2544 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2545 (insert ses--blank-line))
2546 ;;Insert empty lines in cell data area (will be replaced by
2548 (ses-goto-data row 0)
2549 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2550 (ses-relocate-all row 0 count 0)
2551 ;;If any cell printers insert constant text, insert that text
2553 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2554 (global (ses-call-printer ses--default-printer)))
2555 (if (or (> (length cols) 0) (> (length global) 0))
2557 (dotimes (col ses--numcols)
2558 ;;These cells are always nil, only constant formatting printed
2559 (1value (ses-print-cell (+ x row) col))))))
2560 (when (> ses--header-row row)
2561 ;;Inserting before header
2562 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2563 (ses-reset-header-string)))
2564 ;;Reconstruct text attributes
2567 (push '(apply ses-widen) buffer-undo-list)
2568 ;;Return to current cell
2570 (ses-jump-safe ses--curcell)
2571 (ses-goto-print (1- ses--numrows) 0)))
2573 (defun ses-delete-row (count)
2574 "Delete the current row.
2575 With prefix, deletes COUNT rows starting from the current one."
2578 (or (> count 0) (signal 'args-out-of-range nil))
2579 (let ((inhibit-quit t)
2580 (inhibit-read-only t)
2581 (row (car (ses-sym-rowcol ses--curcell))))
2582 (setq count (min count (- ses--numrows row)))
2584 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2585 ;;Delete lines from print area
2586 (ses-goto-print row 0)
2587 (ses-delete-line count)
2588 ;;Delete lines from cell data area
2589 (ses-goto-data row 0)
2590 (ses-delete-line (* count (1+ ses--numcols)))
2591 ;;Relocate variables and formulas
2592 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2593 (ses-relocate-all row 0 (- count) 0)
2594 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2595 0 (1- ses--numcols))
2596 (when (> ses--header-row row)
2597 (if (<= ses--header-row (+ row count))
2598 ;;Deleting the header row
2599 (ses-set-parameter 'ses--header-row 0)
2600 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2601 (ses-reset-header-string)))
2602 ;;Reconstruct attributes
2605 (push '(apply ses-widen) buffer-undo-list)
2606 (ses-jump-safe ses--curcell))
2608 (defun ses-insert-column (count &optional col width printer)
2609 "Insert a new column before COL (default is the current one).
2610 With prefix, insert COUNT columns before current one.
2611 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2612 \(otherwise they're taken from the current column)."
2615 (or (> count 0) (signal 'args-out-of-range nil))
2617 (setq col (cdr (ses-sym-rowcol ses--curcell))
2618 width (ses-col-width col)
2619 printer (ses-col-printer col)))
2621 (let ((inhibit-quit t)
2622 (inhibit-read-only t)
2623 (widths ses--col-widths)
2624 (printers ses--col-printers)
2626 ;;Create a new set of cell-variables
2627 (ses-create-cell-variable-range 0 (1- ses--numrows)
2628 ses--numcols (+ ses--numcols count -1))
2629 ;;Insert each column.
2630 (dotimes-with-progress-reporter (x count) "Inserting column..."
2631 ;;Create a column of empty cells. The `symbol' fields will be set by
2632 ;;the call to ses-relocate-all.
2633 (ses-adjust-print-width col (1+ width))
2634 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2635 (dotimes (row ses--numrows)
2636 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2637 ;;Inserting in the middle of a spill-over
2639 (ses-aset-with-undo ses--cells row
2640 (ses-vector-insert (aref ses--cells row)
2641 col (ses-make-cell)))
2642 ;;Insert empty lines in cell data area (will be replaced by
2644 (ses-goto-data row col)
2646 ;; Insert column width and printer.
2647 (setq widths (ses-vector-insert widths col width)
2648 printers (ses-vector-insert printers col printer)))
2649 (ses-set-parameter 'ses--col-widths widths)
2650 (ses-set-parameter 'ses--col-printers printers)
2651 (ses-reset-header-string)
2652 (ses-relocate-all 0 col 0 count)
2655 (when (or (> (length (ses-call-printer printer)) 0)
2656 (> (length (ses-call-printer ses--default-printer)) 0))
2657 ;; Either column printer or global printer inserts some constant text.
2658 ;; Reprint the new columns to insert that text.
2659 (dotimes (x ses--numrows)
2661 ;; Always nil here --- this is a blank column.
2662 (1value (ses-print-cell-new-width x (+ y col))))))
2664 (ses-jump-safe ses--curcell))
2666 (defun ses-delete-column (count)
2667 "Delete the current column.
2668 With prefix, deletes COUNT columns starting from the current one."
2671 (or (> count 0) (signal 'args-out-of-range nil))
2672 (let ((inhibit-quit t)
2673 (inhibit-read-only t)
2674 (rowcol (ses-sym-rowcol ses--curcell))
2676 col origrow has-skip)
2677 (setq origrow (car rowcol)
2679 count (min count (- ses--numcols col)))
2680 (if (= count ses--numcols)
2681 (error "Can't delete all columns!"))
2682 ;;Determine width of column(s) being deleted
2684 (setq width (+ width (ses-col-width (+ col x)) 1)))
2686 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2687 (ses-adjust-print-width col (- width))
2688 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2689 ;;Delete lines from cell data area
2690 (ses-goto-data row col)
2691 (ses-delete-line count)
2692 ;;Delete cells. Check if deletion area begins or ends with a skip.
2693 (if (or (eq (ses-cell-value row col) '*skip*)
2694 (and (< col ses--numcols)
2695 (eq (ses-cell-value row (+ col count)) '*skip*)))
2697 (ses-aset-with-undo ses--cells row
2698 (ses-vector-delete (aref ses--cells row) col count)))
2700 (ses-set-parameter 'ses--col-widths
2701 (ses-vector-delete ses--col-widths col count))
2702 (ses-set-parameter 'ses--col-printers
2703 (ses-vector-delete ses--col-printers col count))
2704 (ses-reset-header-string)
2705 ;;Relocate variables and formulas
2706 (ses-relocate-all 0 col 0 (- count))
2707 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2708 ses--numcols (+ ses--numcols count -1))
2712 (if (>= col ses--numcols)
2713 (setq col (1- col)))
2714 (ses-goto-print origrow col)))
2716 (defun ses-forward-or-insert (&optional count)
2717 "Move to next cell in row, or inserts a new cell if already in last one, or
2718 inserts a new row if at bottom of print area. Repeat COUNT times."
2720 (ses-check-curcell 'end)
2721 (setq deactivate-mark t) ; Doesn't combine well with ranges.
2724 (if (not ses--curcell)
2725 (progn ; At bottom of print area.
2726 (barf-if-buffer-read-only)
2728 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2730 (char-before (next-single-property-change (point)
2732 ;; We're already in last nonskipped cell on line. Need to create a
2734 (barf-if-buffer-read-only)
2735 (ses-insert-column (- count x)
2738 (ses-col-printer col)))))
2741 (defun ses-append-row-jump-first-column ()
2742 "Insert a new row after current one and jump to its first column."
2746 (beginning-of-line 2)
2750 (defun ses-set-column-width (col newwidth)
2751 "Set the width of the current column."
2753 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2754 (barf-if-buffer-read-only)
2756 (if current-prefix-arg
2757 (prefix-numeric-value current-prefix-arg)
2758 (read-from-minibuffer (format "Column %s width (default %d): "
2759 (ses-column-letter col)
2760 (ses-col-width col))
2761 nil ; No initial contents.
2762 nil ; No override keymap.
2763 t ; Convert to Lisp object.
2766 (ses-col-width col))))))) ; Default value.
2768 (error "Invalid column width"))
2770 (ses-reset-header-string)
2772 (let ((inhibit-quit t))
2773 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2774 (ses-set-parameter 'ses--col-widths newwidth col))
2775 (dotimes (row ses--numrows)
2776 (ses-print-cell-new-width row col))))
2779 ;;----------------------------------------------------------------------------
2780 ;; Cut and paste, import and export
2781 ;;----------------------------------------------------------------------------
2783 (defun ses--advice-copy-region-as-kill (crak-fun beg end &rest args)
2784 ;; FIXME: Why doesn't it make sense to copy read-only or
2785 ;; intangible attributes? They're removed upon yank!
2786 "It doesn't make sense to copy read-only or intangible attributes into the
2787 kill ring. It probably doesn't make sense to copy keymap properties.
2788 We'll assume copying front-sticky properties doesn't make sense, either.
2790 This advice also includes some SES-specific code because otherwise it's too
2791 hard to override how mouse-1 works."
2796 (if (not (and (derived-mode-p 'ses-mode)
2797 (eq (get-text-property beg 'read-only) 'ses)
2798 (eq (get-text-property (1- end) 'read-only) 'ses)))
2799 (apply crak-fun beg end args) ; Normal copy-region-as-kill.
2800 (kill-new (ses-copy-region beg end))
2801 (if transient-mark-mode
2802 (setq deactivate-mark t))
2804 (advice-add 'copy-region-as-kill :around #'ses--advice-copy-region-as-kill)
2806 (defun ses-copy-region (beg end)
2807 "Treat the region as rectangular. Convert the intangible attributes to
2808 SES attributes recording the contents of the cell as of the time of copying."
2809 (when (= end ses--data-marker)
2810 ;;Avoid overflow situation
2811 (setq end (1- ses--data-marker)))
2812 (let* ((inhibit-point-motion-hooks t)
2813 (x (mapconcat #'ses-copy-region-helper
2814 (extract-rectangle beg (1- end)) "\n")))
2815 (remove-text-properties 0 (length x)
2823 (defun ses-copy-region-helper (line)
2824 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2825 external form by attaching to each print cell a 'ses attribute that records
2826 the corresponding data cell."
2827 (or (> (length line) 1)
2828 (error "Empty range"))
2829 (let ((inhibit-read-only t)
2831 mycell next sym rowcol)
2833 (setq sym (get-text-property pos 'intangible line)
2834 next (next-single-property-change pos 'intangible line)
2835 rowcol (ses-sym-rowcol sym)
2836 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2837 (put-text-property pos (or next (length line))
2839 (list (ses-cell-symbol mycell)
2840 (ses-cell-formula mycell)
2841 (ses-cell-printer mycell))
2846 (defun ses-kill-override (beg end)
2847 "Generic override for any commands that kill text.
2848 We clear the killed cells instead of deleting them."
2850 (ses-check-curcell 'needrange)
2851 ;; For some reason, the text-read-only error is not caught by `delete-region',
2852 ;; so we have to use subterfuge.
2853 (let ((buffer-read-only t))
2854 (1value (condition-case nil
2855 (noreturn (funcall (lookup-key (current-global-map)
2856 (this-command-keys))
2858 (buffer-read-only nil)))) ; The expected error.
2859 ;; Because the buffer was marked read-only, the kill command turned itself
2860 ;; into a copy. Now we clear the cells or signal the error. First we check
2861 ;; whether the buffer really is read-only.
2862 (barf-if-buffer-read-only)
2864 (ses-dorange ses--curcell
2865 (ses-clear-cell row col))
2866 (ses-jump (car ses--curcell)))
2868 (defun ses--advice-yank (yank-fun &optional arg &rest args)
2869 "In SES mode, the yanked text is inserted as cells.
2871 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2872 SES buffer), the formulas and print functions are restored for the cells. If
2873 the text contains tabs, this is an insertion of tab-separated formulas.
2874 Otherwise the text is inserted as the formula for the current cell.
2876 When inserting cells, the formulas are usually relocated to keep the same
2877 relative references to neighboring cells. This is best if the formulas
2878 generally refer to other cells within the yanked text. You can use the C-u
2879 prefix to specify insertion without relocation, which is best when the
2880 formulas refer to cells outside the yanked text.
2882 When inserting formulas, the text is treated as a string constant if it doesn't
2883 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2884 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2886 (if (not (and (derived-mode-p 'ses-mode)
2887 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2888 (apply yank-fun arg args) ; Normal non-SES yank.
2889 (ses-check-curcell 'end)
2891 (let ((text (current-kill (cond
2895 (or (ses-yank-cells text arg)
2896 (ses-yank-tsf text arg)
2897 (ses-yank-one (ses-yank-resize 1 1)
2900 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2901 ;; Just one cell --- delete final tab or newline.
2905 (exchange-point-and-mark))))
2906 (advice-add 'yank :around #'ses--advice-yank)
2908 (defun ses-yank-pop (arg)
2909 "Replace just-yanked stretch of killed text with a different stretch.
2910 This command is allowed only immediately after a `yank' or a `yank-pop',
2911 when the region contains a stretch of reinserted previously-killed text.
2912 We replace it with a different stretch of killed text.
2913 Unlike standard `yank-pop', this function uses `undo' to delete the
2914 previous insertion."
2916 (or (eq last-command 'yank)
2917 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2919 (noreturn (error "Previous command was not a yank")))
2922 (yank (1+ (or arg 1)))
2923 (setq this-command 'yank))
2925 (defun ses-yank-cells (text arg)
2926 "If the TEXT has a proper set of 'ses attributes, insert the text as
2927 cells, else return nil. The cells are reprinted--the supplied text is
2928 ignored because the column widths, default printer, etc. at yank time might
2929 be different from those at kill-time. ARG is a list to indicate that
2930 formulas are to be inserted without relocation."
2931 (let ((first (get-text-property 0 'ses text))
2932 (last (get-text-property (1- (length text)) 'ses text)))
2933 (when (and first last) ;;Otherwise not proper set of attributes
2934 (setq first (ses-sym-rowcol (car first))
2935 last (ses-sym-rowcol (car last)))
2936 (let* ((needrows (- (car last) (car first) -1))
2937 (needcols (- (cdr last) (cdr first) -1))
2938 (rowcol (ses-yank-resize needrows needcols))
2939 (rowincr (- (car rowcol) (car first)))
2940 (colincr (- (cdr rowcol) (cdr first)))
2943 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2944 (setq myrow (+ row (car rowcol)))
2945 (dotimes (col needcols)
2946 (setq mycol (+ col (cdr rowcol))
2947 last (get-text-property pos 'ses text)
2948 pos (next-single-property-change pos 'ses text)
2949 x (ses-sym-rowcol (car last)))
2951 ;; Newline --- all remaining cells on row are skipped.
2952 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2953 last (list nil nil nil)
2955 (if (/= (car x) (- myrow rowincr))
2956 (error "Cell row error"))
2957 (if (< (- mycol colincr) (cdr x))
2958 ;; Some columns were skipped.
2959 (let ((oldcol mycol))
2960 (while (< (- mycol colincr) (cdr x))
2961 (ses-clear-cell myrow mycol)
2964 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
2965 (when (car last) ; Skip this for *skip* cells.
2966 (setq x (nth 2 last))
2967 (unless (equal x (ses-cell-printer myrow mycol))
2970 (eq (car-safe x) 'ses-safe-printer)
2971 (setq x `(ses-safe-printer ,x)))
2972 (ses-set-cell myrow mycol 'printer x))
2973 (setq x (cadr last))
2975 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2977 (eq (car-safe x) 'ses-safe-formula)
2978 (setq x `(ses-safe-formula ,x)))
2979 (ses-cell-set-formula myrow mycol x)))
2981 (if (get-text-property pos 'ses text)
2982 (error "Missing newline between rows"))
2983 (setq pos (next-single-property-change pos 'ses text))))
2986 (defun ses-yank-one (rowcol text from to arg)
2987 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2988 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2989 (let ((val (condition-case nil
2990 (read-from-string text from to)
2991 (error (cons nil from)))))
2993 ((< (cdr val) (or to (length text)))
2994 ;; Invalid sexp --- leave it as a string.
2995 (setq val (substring text from to)))
2996 ((and (car val) (symbolp (car val)))
2997 (setq val (if (consp arg)
2998 (list 'quote (car val)) ; Keep symbol.
2999 (substring text from to)))) ; Treat symbol as text.
3001 (setq val (car val))))
3002 (let ((row (car rowcol))
3005 (setq val `(ses-safe-formula ,val)))
3006 (ses-cell-set-formula row col val))))
3008 (defun ses-yank-tsf (text arg)
3009 "If TEXT contains tabs and/or newlines, treat the tabs as
3010 column-separators and the newlines as row-separators and insert the text as
3011 cell formulas--else return nil. Treat plain symbols as strings unless ARG
3012 is a list. Ignore a final newline."
3013 (if (or (not (string-match "[\t\n]" text))
3014 (= (match-end 0) (length text)))
3017 (if (/= (aref text (1- (length text))) ?\n)
3018 (setq text (concat text "\n")))
3024 ;;Find all the tabs and newlines
3025 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
3027 (setq cols (1+ cols))
3028 (when (eq (aref text pos) ?\n)
3030 (setq needcols cols)
3031 (or (= needcols cols)
3032 (error "Inconsistent row lengths")))
3034 needrows (1+ needrows))))
3035 ;;Insert the formulas
3036 (setq rowcol (ses-yank-resize needrows needcols))
3037 (dotimes (row needrows)
3038 (dotimes (col needcols)
3039 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
3040 (+ (cdr rowcol) needcols (- col) -1))
3041 text (1+ (cadr spots)) (car spots) arg)
3042 (setq spots (cdr spots))))
3043 (ses-goto-print (+ (car rowcol) needrows -1)
3044 (+ (cdr rowcol) needcols -1))
3047 (defun ses-yank-resize (needrows needcols)
3048 "If this yank will require inserting rows and/or columns, ask for
3049 confirmation and then insert them. Result is (row,col) for top left of yank
3050 spot, or error signal if user requests cancel."
3052 (let ((rowcol (if ses--curcell
3053 (ses-sym-rowcol ses--curcell)
3054 (cons ses--numrows 0)))
3056 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
3057 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
3058 rowbool (> needrows 0)
3059 colbool (> needcols 0))
3060 (when (or rowbool colbool)
3061 ;;Need to insert. Get confirm
3062 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
3063 (if rowbool (format "%d rows" needrows) "")
3064 (if (and rowbool colbool) " and " "")
3065 (if colbool (format "%d columns" needcols) "")))
3070 (ses-goto-print ses--numrows 0)
3071 (ses-insert-row needrows))))
3073 (ses-insert-column needcols
3075 (ses-col-width (1- ses--numcols))
3076 (ses-col-printer (1- ses--numcols)))))
3079 (defun ses-export-tsv (_beg _end)
3080 "Export values from the current range, with tabs between columns and
3081 newlines between rows. Result is placed in kill ring."
3083 (ses-export-tab nil))
3085 (defun ses-export-tsf (_beg _end)
3086 "Export formulas from the current range, with tabs between columns and
3087 newlines between rows. Result is placed in kill ring."
3091 (defun ses-export-tab (want-formulas)
3092 "Export the current range with tabs between columns and newlines between rows.
3093 Result is placed in kill ring. The export is values unless WANT-FORMULAS
3094 is non-nil. Newlines and tabs in the export text are escaped."
3095 (ses-check-curcell 'needrange)
3096 (let ((print-escape-newlines t)
3098 (ses-dorange ses--curcell
3099 (setq item (if want-formulas
3100 (ses-cell-formula row col)
3101 (ses-cell-value row col)))
3102 (if (eq (car-safe item) 'ses-safe-formula)
3103 ;;Hide our deferred safety-check marker
3104 (setq item (cadr item)))
3105 (if (or (not item) (eq item '*skip*))
3107 (when (eq (car-safe item) 'quote)
3109 (setq item (cadr item)))
3110 (setq item (prin1-to-string item t))
3111 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
3117 (push "\n" result))))
3118 (setq result (apply #'concat (nreverse result)))
3122 ;;----------------------------------------------------------------------------
3123 ;; Other user commands
3124 ;;----------------------------------------------------------------------------
3126 (defun ses-unset-header-row ()
3127 "Select the default header row."
3129 (ses-set-header-row 0))
3131 (defun ses-set-header-row (row)
3132 "Set the ROW to display in the header-line.
3133 With a numerical prefix arg, use that row.
3134 With no prefix arg, use the current row.
3135 With a \\[universal-argument] prefix arg, prompt the user.
3136 The top row is row 1. Selecting row 0 displays the default header row."
3138 (list (if (numberp current-prefix-arg) current-prefix-arg
3139 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3140 (if current-prefix-arg
3141 (read-number "Header row: " currow)
3143 (if (or (< row 0) (> row ses--numrows))
3144 (error "Invalid header-row"))
3146 (let ((oldval ses--header-row))
3147 (let (buffer-undo-list)
3148 (ses-set-parameter 'ses--header-row row))
3149 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
3150 (ses-reset-header-string))
3152 (defun ses-mark-row ()
3153 "Mark the entirety of current row as a range."
3155 (ses-check-curcell 'range)
3156 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
3158 (ses-goto-print (1+ row) 0)
3159 (push-mark (point) nil t)
3160 (ses-goto-print row 0)))
3162 (defun ses-mark-column ()
3163 "Mark the entirety of current column as a range."
3165 (ses-check-curcell 'range)
3166 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
3169 (ses-goto-print (1- ses--numrows) col)
3171 (push-mark (point) nil t)
3172 (while (eq '*skip* (ses-cell-value row col))
3173 ;;Skip over initial cells in column that can't be selected
3174 (setq row (1+ row)))
3175 (ses-goto-print row col)))
3177 (defun ses-end-of-line ()
3178 "Move point to last cell on line."
3180 (ses-check-curcell 'end 'range)
3181 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3183 (let ((col (1- ses--numcols))
3185 (if (symbolp ses--curcell)
3187 (setq row (car (ses-sym-rowcol ses--curcell)))
3188 ;; Range --- use whichever end of the range the point is at.
3189 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
3191 (cdr ses--curcell))))
3192 ;; If range already includes the last cell in a row, point is actually
3193 ;; in the following row.
3194 (if (<= (cdr rowcol) (1- col))
3195 (setq row (car rowcol))
3196 (setq row (1+ (car rowcol)))
3197 (if (= row ses--numrows)
3198 ;;Already at end - can't go anywhere
3200 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
3201 (while (eq (ses-cell-value row col) '*skip*)
3202 ;; Back to beginning of multi-column cell.
3203 (setq col (1- col)))
3204 (ses-goto-print row col)))))
3206 (defun ses-renarrow-buffer ()
3207 "Narrow the buffer so only the print area is visible.
3208 Use after \\[widen]."
3210 (setq ses--deferred-narrow t))
3212 (defun ses-sort-column (sorter &optional reverse)
3213 "Sort the range by a specified column.
3214 With prefix, sorts in REVERSE order."
3215 (interactive "*sSort column: \nP")
3216 (ses-check-curcell 'needrange)
3217 (let ((min (ses-sym-rowcol (car ses--curcell)))
3218 (max (ses-sym-rowcol (cdr ses--curcell))))
3219 (let ((minrow (car min))
3224 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3225 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3226 (error "Invalid sort column"))
3227 ;;Get key columns and sort them
3228 (dotimes (x (- maxrow minrow -1))
3229 (ses-goto-print (+ minrow x) sorter)
3230 (setq end (next-single-property-change (point) 'intangible))
3231 (push (cons (buffer-substring-no-properties (point) end)
3234 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3235 ;;Extract the lines in reverse sorted order
3237 (setq keys (nreverse keys)))
3239 (ses-goto-print (cdr x) (1+ maxcol))
3241 (ses-goto-print (cdr x) mincol)
3242 (push (ses-copy-region (point) end) extracts))
3244 ;;Paste the lines sequentially
3245 (dotimes (x (- maxrow minrow -1))
3246 (ses-goto-print (+ minrow x) mincol)
3248 (ses-yank-cells (pop extracts) nil)))))
3250 (defun ses-sort-column-click (event reverse)
3251 "Mouse version of `ses-sort-column'."
3252 (interactive "*e\nP")
3253 (setq event (event-end event))
3254 (select-window (posn-window event))
3255 (setq event (car (posn-col-row event))) ; Click column.
3257 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3258 (setq event (- event (ses-col-width col) 1)
3260 (if (>= col ses--numcols)
3262 (ses-sort-column (ses-column-letter col) reverse))))
3264 (defun ses-insert-range ()
3265 "Insert into minibuffer the list of cells currently highlighted in the
3269 (with-current-buffer (window-buffer minibuffer-scroll-window)
3270 (ses-command-hook) ; For ses-coverage.
3271 (ses-check-curcell 'needrange)
3272 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3273 ,(cdr ses--curcell))))))
3274 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3276 (defun ses-insert-ses-range ()
3277 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
3278 highlighted range in the spreadsheet."
3281 (with-current-buffer (window-buffer minibuffer-scroll-window)
3282 (ses-command-hook) ; For ses-coverage.
3283 (ses-check-curcell 'needrange)
3284 (setq x (format "(ses-range %S %S)"
3286 (cdr ses--curcell))))
3289 (defun ses-insert-range-click (event)
3290 "Mouse version of `ses-insert-range'."
3292 (mouse-set-point event)
3295 (defun ses-insert-ses-range-click (event)
3296 "Mouse version of `ses-insert-ses-range'."
3298 (mouse-set-point event)
3299 (ses-insert-ses-range))
3301 (defun ses-replace-name-in-formula (formula old-name new-name)
3302 (let ((new-formula formula))
3303 (unless (and (consp formula)
3304 (eq (car-safe formula) 'quote))
3306 (let ((elt (car-safe formula)))
3309 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3311 (eq (car-safe formula) old-name))
3312 (setcar formula new-name))))
3313 (setq formula (cdr formula))))
3316 (defun ses-rename-cell (new-name &optional cell)
3317 "Rename current cell."
3318 (interactive "*SEnter new name: ")
3320 (and (local-variable-p new-name)
3321 (ses-is-cell-sym-p new-name)
3322 (error "Already a cell name"))
3323 (and (boundp new-name)
3324 (null (yes-or-no-p (format "`%S' is already bound outside this buffer, continue? "
3326 (error "Already a bound cell name")))
3328 (sym (if (ses-cell-p cell)
3329 (ses-cell-symbol cell)
3334 (rowcol (ses-sym-rowcol sym))
3337 new-rowcol old-name)
3338 (setq cell (or cell (ses-get-cell row col))
3339 old-name (ses-cell-symbol cell)
3340 new-rowcol (ses-decode-cell-symbol (symbol-name new-name)))
3342 (if (equal new-rowcol rowcol)
3343 (put new-name 'ses-cell rowcol)
3344 (error "Not a valid name for this cell location"))
3345 (setq ses--named-cell-hashmap
3346 (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
3347 (put new-name 'ses-cell :ses-named)
3348 (puthash new-name rowcol ses--named-cell-hashmap))
3349 (push `(ses-rename-cell ,old-name ,cell) buffer-undo-list)
3350 ;; Replace name by new name in formula of cells refering to renamed cell.
3351 (dolist (ref (ses-cell-references cell))
3352 (let* ((x (ses-sym-rowcol ref))
3353 (xcell (ses-get-cell (car x) (cdr x))))
3354 (setf (ses-cell-formula xcell)
3355 (ses-replace-name-in-formula
3356 (ses-cell-formula xcell)
3359 ;; Replace name by new name in reference list of cells to which renamed
3361 (dolist (ref (ses-formula-references (ses-cell-formula cell)))
3362 (let* ((x (ses-sym-rowcol ref))
3363 (xcell (ses-get-cell (car x) (cdr x))))
3364 (setf (ses-cell-references xcell)
3365 (cons new-name (delq sym
3366 (ses-cell-references xcell))))))
3367 (push new-name ses--renamed-cell-symb-list)
3368 (set new-name (symbol-value sym))
3369 (setf (ses-cell--symbol cell) new-name)
3371 (and curcell (setq ses--curcell new-name))
3372 (let* ((pos (point))
3373 (inhibit-read-only t)
3374 (col (current-column))
3375 (end (save-excursion
3376 (move-to-column (1+ col))
3378 (+ pos (ses-col-width col) 1)
3380 (put-text-property pos end 'intangible new-name))
3382 (setq mode-line-process (list " cell "
3383 (symbol-name new-name)))
3384 (force-mode-line-update)))
3386 (defun ses-refresh-local-printer (name _compiled-value) ;FIXME: unused arg?
3387 "Refresh printout for all cells which use printer NAME.
3388 NAME should be the name of a locally defined printer.
3389 Uses the value COMPILED-VALUE for this printer."
3390 (message "Refreshing cells using printer %S" name)
3392 (dotimes (row ses--numrows)
3393 (dotimes (col ses--numcols)
3394 (let ((cell-printer (ses-cell-printer row col)))
3395 (when (eq cell-printer name)
3399 (ses-print-cell row col)))))))
3401 (defun ses-define-local-printer (name)
3402 "Define a local printer with name NAME."
3403 (interactive "*SEnter printer name: ")
3404 (let* ((cur-printer (gethash name ses--local-printer-hashmap))
3405 (default (and (vectorp cur-printer) (ses--locprn-def cur-printer)))
3408 (ses-read-printer (format "Enter definition of printer %S: " name)
3411 ;; cancelled operation => do nothing
3413 ;; no change => do nothing
3414 ((and (vectorp cur-printer) (equal new-def default)))
3415 ;; re-defined printer
3416 ((vectorp cur-printer)
3417 (setq create-printer 0)
3418 (setf (ses--locprn-def cur-printer) new-def)
3419 (ses-refresh-local-printer
3421 (setf (ses--locprn-compiled cur-printer)
3422 (ses-local-printer-compile new-def))))
3425 (setq create-printer 1)
3428 (ses-make-local-printer-info new-def))
3429 ses--local-printer-hashmap)))
3430 (when create-printer
3431 (let ((printer-def-text
3433 "(ses-local-printer "
3436 (prin1-to-string (ses--locprn-def cur-printer))
3439 (ses-goto-data ses--numrows
3440 (ses--locprn-number cur-printer))
3441 (let ((inhibit-read-only t))
3442 ;; Special undo since it's outside the narrowed buffer.
3443 (let (buffer-undo-list)
3444 (if (= create-printer 0)
3445 (delete-region (point) (line-end-position))
3448 (insert printer-def-text)
3449 (when (= create-printer 1)
3450 (ses-file-format-extend-parameter-list 3)
3451 (ses-set-parameter 'ses--numlocprn
3452 (+ ses--numlocprn create-printer))))))))))
3455 ;;----------------------------------------------------------------------------
3456 ;; Checking formulas for safety
3457 ;;----------------------------------------------------------------------------
3459 (defun ses-safe-printer (printer)
3460 "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
3461 (if (or (stringp printer)
3462 (stringp (car-safe printer))
3464 (and (symbolp printer) (gethash printer ses--local-printer-hashmap))
3465 (ses-warn-unsafe printer 'unsafep-function))
3469 (defun ses-safe-formula (formula)
3470 "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
3471 (if (ses-warn-unsafe formula 'unsafep)
3473 `(ses-unsafe ',formula)))
3475 (defun ses-warn-unsafe (formula checker)
3476 "Apply CHECKER to FORMULA.
3477 If result is non-nil, asks user for confirmation about FORMULA,
3478 which might be unsafe. Returns t if formula is safe or user allows
3479 execution anyway. Always returns t if `safe-functions' is t."
3480 (if (eq safe-functions t)
3482 (setq checker (funcall checker formula))
3485 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3486 formula checker)))))
3489 ;;----------------------------------------------------------------------------
3490 ;; Standard formulas
3491 ;;----------------------------------------------------------------------------
3493 (defun ses--clean-! (&rest x)
3494 "Clean by `delq' list X from any occurrence of `nil' or `*skip*'."
3495 (delq nil (delq '*skip* x)))
3497 (defun ses--clean-_ (x y)
3498 "Clean list X by replacing by Y any occurrence of `nil' or `*skip*'.
3500 This will change X by making `setcar' on its cons cells."
3501 (let ((ret x) ret-elt)
3503 (setq ret-elt (car ret))
3504 (when (memq ret-elt '(nil *skip*))
3506 (setq ret (cdr ret))))
3509 (defmacro ses-range (from to &rest rest)
3510 "Expand to a list of cell-symbols for the range going from
3511 FROM up to TO. The range automatically expands to include any
3512 new row or column inserted into its middle. The SES library code
3513 specifically looks for the symbol `ses-range', so don't create an
3514 alias for this macro!
3516 By passing in REST some flags one can configure the way the range
3517 is read and how it is formatted.
3519 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3522 Readout direction is specified by a `>v', '`>^', `<v', `<^',
3523 `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3524 of such a flag, a default direction of `^<' is assumed. This
3525 way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3526 while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3528 If the range is one row, then `>' can be used as a shorthand to
3529 `>v' or `>^', and `<' to `<v' or `<^'.
3531 If the range is one column, then `v' can be used as a shorthand to
3532 `v>' or `v<', and `^' to `^>' or `v<'.
3534 A `!' flag will remove all cells whose value is nil or `*skip*'.
3536 A `_' flag will replace nil or `*skip*' by the value following
3537 the `_' flag. If the `_' flag is the last argument, then they are
3538 replaced by integer 0.
3540 A `*', `*1' or `*2' flag will vectorize the range in the sense of
3541 Calc. See info node `(Calc) Top'. Flag `*' will output either a
3542 vector or a matrix depending on the number of rows, `*1' will
3543 flatten the result to a one row vector, and `*2' will make a
3544 matrix whatever the number of rows.
3546 Warning: interaction with Calc is experimental and may produce
3547 confusing results if you are not aware of Calc data format.
3548 Use `math-format-value' as a printer for Calc objects."
3556 (ses-dorange (cons from to)
3557 (when (/= prev-row row)
3558 (push result-row result)
3559 (setq result-row nil))
3560 (push (ses-cell-symbol row col) result-row)
3561 (setq prev-row row))
3562 (push result-row result)
3564 (let ((x (pop rest)))
3566 (`>v (setq transpose nil reorient-x nil reorient-y nil))
3567 (`>^ (setq transpose nil reorient-x nil reorient-y t))
3568 (`<^ (setq transpose nil reorient-x t reorient-y t))
3569 (`<v (setq transpose nil reorient-x t reorient-y nil))
3570 (`v> (setq transpose t reorient-x nil reorient-y t))
3571 (`^> (setq transpose t reorient-x nil reorient-y nil))
3572 (`^< (setq transpose t reorient-x t reorient-y nil))
3573 (`v< (setq transpose t reorient-x t reorient-y t))
3574 ((or `* `*2 `*1) (setq vectorize x))
3575 (`! (setq clean 'ses--clean-!))
3576 (`_ (setq clean `(lambda (&rest x)
3577 (ses--clean-_ x ,(if rest (pop rest) 0)))))
3580 ; shorthands one row
3581 ((and (null (cddr result)) (memq x '(> <)))
3582 (push (intern (concat (symbol-name x) "v")) rest))
3583 ; shorthands one col
3584 ((and (null (cdar result)) (memq x '(v ^)))
3585 (push (intern (concat (symbol-name x) ">")) rest))
3586 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3588 (setcdr (last result 2) nil)
3589 (setq result (cdr (nreverse result))))
3591 (setq result (mapcar #'nreverse result)))
3593 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3596 (dolist (elt (pop result))
3597 (setcar iter (cons elt (car iter)))
3598 (setq iter (cdr iter))))
3601 (cl-flet ((vectorize-*1
3603 (cons clean (cons (quote 'vec) (apply #'append result))))
3606 (cons clean (cons (quote 'vec)
3608 (cons clean (cons (quote 'vec) x)))
3611 (`nil (cons clean (apply #'append result)))
3612 (`*1 (vectorize-*1 clean result))
3613 (`*2 (vectorize-*2 clean result))
3614 (`* (funcall (if (cdr result)
3619 (defun ses-delete-blanks (&rest args)
3620 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3623 (unless (memq cur '(nil *skip*))
3627 (defun ses+ (&rest args)
3628 "Compute the sum of the arguments, ignoring blanks."
3629 (apply #'+ (apply #'ses-delete-blanks args)))
3631 (defun ses-average (list)
3632 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3633 are ignored. Result is always floating-point, even if all args are integers."
3634 (setq list (apply #'ses-delete-blanks list))
3635 (/ (float (apply #'+ list)) (length list)))
3637 (defmacro ses-select (fromrange test torange)
3638 "Select cells in FROMRANGE that are `equal' to TEST.
3639 For each match, return the corresponding cell from TORANGE.
3640 The ranges are macroexpanded but not evaluated so they should be
3641 either (ses-range BEG END) or (list ...). The TEST is evaluated."
3642 (setq fromrange (cdr (macroexpand fromrange))
3643 torange (cdr (macroexpand torange))
3645 (or (= (length fromrange) (length torange))
3646 (error "ses-select: Ranges not same length"))
3648 (dolist (x fromrange)
3649 (if (equal test (symbol-value x))
3650 (push (car torange) result))
3651 (setq torange (cdr torange)))
3652 (cons 'list result)))
3654 ;;All standard formulas are safe
3655 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3657 (put x 'side-effect-free t))
3660 ;;----------------------------------------------------------------------------
3661 ;; Standard print functions
3662 ;;----------------------------------------------------------------------------
3664 (defun ses-center (value &optional span fill)
3665 "Print VALUE, centered within column.
3666 FILL is the fill character for centering (default = space).
3667 SPAN indicates how many additional rightward columns to include
3668 in width (default = 0)."
3669 (let ((printer (or (ses-col-printer ses--col) ses--default-printer))
3670 (width (ses-col-width ses--col))
3672 (or fill (setq fill ?\s))
3673 (or span (setq span 0))
3674 (setq value (ses-call-printer printer value))
3676 (setq width (+ width 1 (ses-col-width (+ ses--col span (- x))))))
3677 ;; Set column width.
3678 (setq width (- width (string-width value)))
3680 value ; Too large for field, anyway.
3681 (setq half (make-string (/ width 2) fill))
3682 (concat half value half
3683 (if (> (% width 2) 0) (char-to-string fill))))))
3685 (defun ses-center-span (value &optional fill)
3686 "Print VALUE, centered within the span that starts in the current column
3687 and continues until the next nonblank column.
3688 FILL specifies the fill character (default = space)."
3689 (let ((end (1+ ses--col)))
3690 (while (and (< end ses--numcols)
3691 (memq (ses-cell-value ses--row end) '(nil *skip*)))
3692 (setq end (1+ end)))
3693 (ses-center value (- end ses--col 1) fill)))
3695 (defun ses-dashfill (value &optional span)
3696 "Print VALUE centered using dashes.
3697 SPAN indicates how many rightward columns to include in width (default = 0)."
3698 (ses-center value span ?-))
3700 (defun ses-dashfill-span (value)
3701 "Print VALUE, centered using dashes within the span that starts in the
3702 current column and continues until the next nonblank column."
3703 (ses-center-span value ?-))
3705 (defun ses-tildefill-span (value)
3706 "Print VALUE, centered using tildes within the span that starts in the
3707 current column and continues until the next nonblank column."
3708 (ses-center-span value ?~))
3710 (defun ses-unsafe (_value)
3711 "Substitute for an unsafe formula or printer."
3712 (error "Unsafe formula or printer"))
3714 ;;All standard printers are safe, including ses-unsafe!
3715 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3716 (put x 'side-effect-free t))
3718 (defun ses-unload-function ()
3719 "Unload the Simple Emacs Spreadsheet."
3720 (advice-remove 'yank #'ses--advice-yank)
3721 (advice-remove 'copy-region-as-kill #'ses--advice-copy-region-as-kill)
3722 ;; Continue standard unloading.
3727 ;;; ses.el ends here