1 ;;; ses.el -- Simple Emacs Spreadsheet -*- coding: utf-8 -*-
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-file-trailer
243 ";; Local Variables:\n;; mode: ses\n;; End:\n"
244 "Initial contents for the file-trailer area at the bottom of the file.")
246 (defconst ses-initial-file-contents
247 (concat " \n" ; One blank cell in print area.
248 ses-print-data-boundary
249 "(ses-cell A1 nil nil nil nil)\n" ; One blank cell in data area.
250 "\n" ; End-of-row terminator for the one row in data area.
251 "(ses-column-widths [7])\n"
252 "(ses-column-printers [nil])\n"
253 "(ses-default-printer \"%.7g\")\n"
254 "(ses-header-row 0)\n"
255 ses-initial-global-parameters
256 ses-initial-file-trailer)
257 "The initial contents of an empty spreadsheet.")
259 (defconst ses-box-prop '(:box (:line-width 2 :style released-button))
260 "Display properties to create a raised box for cells in the header line.")
262 (defconst ses-standard-printer-functions
263 '(ses-center ses-center-span ses-dashfill ses-dashfill-span
265 "List of print functions to be included in initial history of printer
266 functions. None of these standard-printer functions is suitable for use as a
267 column printer or a global-default printer because they invoke the column or
268 default printer and then modify its output.")
271 ;;----------------------------------------------------------------------------
272 ;; Local variables and constants
273 ;;----------------------------------------------------------------------------
276 (defconst ses-localvars
277 '(ses--blank-line ses--cells ses--col-printers
278 ses--col-widths ses--curcell ses--curcell-overlay
280 ses--deferred-narrow ses--deferred-recalc
281 ses--deferred-write ses--file-format
282 ses--named-cell-hashmap
283 (ses--header-hscroll . -1) ; Flag for "initial recalc needed"
284 ses--header-row ses--header-string ses--linewidth
285 ses--numcols ses--numrows ses--symbolic-formulas
286 ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
287 ses--Dijkstra-weight-bound
288 ;; This list is useful to speed-up clean-up of symbols when
289 ;; an area containing renamed cell is deleted.
290 ses--renamed-cell-symb-list
291 ;; Global variables that we override
292 mode-line-process next-line-add-newlines transient-mark-mode)
293 "Buffer-local variables used by SES.")
295 (defun ses-set-localvars ()
296 "Set buffer-local and initialize some SES variables."
297 (dolist (x ses-localvars)
300 (set (make-local-variable x) nil))
302 (set (make-local-variable (car x)) (cdr x)))
303 (t (error "Unexpected elements `%S' in list `ses-localvars'" x))))))
305 (eval-when-compile ; silence compiler
308 ;;; This variable is documented as being permitted in file-locals:
309 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
311 (defconst ses-paramlines-plist
312 '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
313 ses--header-row -2 ses--file-format 1 ses--numrows 2
315 "Offsets from 'Global parameters' line to various parameter lines in the
316 data area of a spreadsheet.")
320 ;; "Side-effect variables". They are set in one function, altered in
321 ;; another as a side effect, then read back by the first, as a way of
322 ;; passing back more than one value. These declarations are just to make
323 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
324 ;; think the make-local-variable trick above is cleaner).
327 (defvar ses-relocate-return nil
328 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
329 `ses-relocate-all'. Set to 'delete if a cell-reference was deleted from a
330 formula--so the formula needs recalculation. Set to 'range if the size of a
331 `ses-range' was changed--so both the formula's value and list of dependents
332 need to be recalculated.")
334 (defvar ses-call-printer-return nil
335 "Set to t if last cell printer invoked by `ses-call-printer' requested
336 left-justification of the result. Set to error-signal if `ses-call-printer'
337 encountered an error during printing. Otherwise nil.")
339 (defvar ses-start-time nil
340 "Time when current operation started. Used by `ses-time-check' to decide
341 when to emit a progress message.")
344 ;;----------------------------------------------------------------------------
346 ;;----------------------------------------------------------------------------
348 (defmacro ses-get-cell (row col)
349 "Return the cell structure that stores information about cell (ROW,COL)."
350 `(aref (aref ses--cells ,row) ,col))
352 ;; We might want to use defstruct here, but cells are explicitly used as
353 ;; arrays in ses-set-cell, so we'd need to fix this first. --Stef
354 (defsubst ses-make-cell (&optional symbol formula printer references
356 (vector symbol formula printer references property-list))
358 (defmacro ses-cell-symbol (row &optional col)
359 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
360 `(aref ,(if col `(ses-get-cell ,row ,col) row) 0))
361 (put 'ses-cell-symbol 'safe-function t)
363 (defmacro ses-cell-formula (row &optional col)
364 "From a CELL or a pair (ROW,COL), get the function that computes its value."
365 `(aref ,(if col `(ses-get-cell ,row ,col) row) 1))
367 (defmacro ses-cell-formula-aset (cell formula)
368 "From a CELL set the function that computes its value."
369 `(aset ,cell 1 ,formula))
371 (defmacro ses-cell-printer (row &optional col)
372 "From a CELL or a pair (ROW,COL), get the function that prints its value."
373 `(aref ,(if col `(ses-get-cell ,row ,col) row) 2))
375 (defmacro ses-cell-references (row &optional col)
376 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
377 functions refer to its value."
378 `(aref ,(if col `(ses-get-cell ,row ,col) row) 3))
380 (defmacro ses-cell-references-aset (cell references)
381 "From a CELL set the list REFERENCES of symbols for cells the
382 function of which refer to its value."
383 `(aset ,cell 3 ,references))
385 (defun ses-cell-p (cell)
386 "Return non `nil' is CELL is a cell of current buffer."
389 (eq cell (let ((rowcol (ses-sym-rowcol (ses-cell-symbol cell))))
391 (ses-get-cell (car rowcol) (cdr rowcol)))))))
393 (defun ses-cell-property-get-fun (property-name cell)
394 ;; To speed up property fetching, each time a property is found it is placed
395 ;; in the first position. This way, after the first get, the full property
396 ;; list needs to be scanned only when the property does not exist for that
398 (let* ((plist (aref cell 4))
399 (ret (plist-member plist property-name)))
401 ;; Property was found.
402 (let ((val (cadr ret)))
404 ;; Property found is already in the first position, so just return
407 ;; Property is not in the first position, the following will move it
408 ;; there before returning its value.
409 (let ((next (cddr ret)))
412 (setcdr ret (cdr next))
413 (setcar ret (car next)))
414 (setcdr (last plist 1) nil)))
416 `(,property-name ,val ,@plist))
419 (defmacro ses-cell-property-get (property-name row &optional col)
420 "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
422 When COL is omitted, CELL=ROW is a cell object. When COL is
423 present ROW and COL are the integer coordinates of the cell of
426 `(ses-cell-property-get-fun
428 ,(if col `(ses-get-cell ,row ,col) row)))
430 (defun ses-cell-property-delq-fun (property-name cell)
431 (let ((ret (plist-get (aref cell 4) property-name)))
433 (setcdr ret (cddr ret)))))
435 (defun ses-cell-property-set-fun (property-name property-val cell)
436 (let* ((plist (aref cell 4))
437 (ret (plist-member plist property-name)))
439 (setcar (cdr ret) property-val)
440 (aset cell 4 `(,property-name ,property-val ,@plist)))))
442 (defmacro ses-cell-property-set (property-name property-value row &optional col)
443 "From a CELL or a pair (ROW,COL), set the property value of
444 the corresponding cell with name PROPERTY-NAME to PROPERTY-VALUE."
446 `(ses-cell-property-set-fun ,property-name ,property-value
447 ,(if col `(ses-get-cell ,row ,col) row))
448 `(ses-cell-property-delq-fun ,property-name
449 ,(if col `(ses-get-cell ,row ,col) row))))
451 (defun ses-cell-property-pop-fun (property-name cell)
452 (let* ((plist (aref cell 4))
453 (ret (plist-member plist property-name)))
456 (let ((next (cddr ret)))
459 (setcdr ret (cdr next))
460 (setcar ret (car next)))
463 (setcdr (last plist 2) nil))))))))
466 (defmacro ses-cell-property-pop (property-name row &optional col)
467 "From a CELL or a pair (ROW,COL), get and remove the property value of
468 the corresponding cell with name PROPERTY-NAME."
469 `(ses-cell-property-pop-fun ,property-name
470 ,(if col `(ses-get-cell ,row ,col) row)))
472 (defun ses-cell-property-get-handle-fun (property-name cell)
473 (let* ((plist (aref cell 4))
474 (ret (plist-member plist property-name)))
478 (let ((val (cadr ret))
482 (setcdr ret (cdr next))
483 (setcar ret (car next)))
484 (setcdr (last plist 2) nil))
485 (setq ret (cons val plist))
486 (aset cell 4 (cons property-name ret))
488 (setq ret (cons nil plist))
489 (aset cell 4 (cons property-name ret))
492 (defmacro ses-cell-property-get-handle (property-name row &optional col)
493 "From a CELL or a pair (ROW,COL), get a cons cell whose car is
494 the property value of the corresponding cell property with name
496 `(ses-cell-property-get-handle-fun ,property-name
497 ,(if col `(ses-get-cell ,row ,col) row)))
500 (defalias 'ses-cell-property-handle-car 'car)
501 (defalias 'ses-cell-property-handle-setcar 'setcar)
503 (defmacro ses-cell-value (row &optional col)
504 "From a CELL or a pair (ROW,COL), get the current value for that cell."
505 `(symbol-value (ses-cell-symbol ,row ,col)))
507 (defmacro ses-col-width (col)
508 "Return the width for column COL."
509 `(aref ses--col-widths ,col))
511 (defmacro ses-col-printer (col)
512 "Return the default printer for column COL."
513 `(aref ses--col-printers ,col))
515 (defmacro ses-sym-rowcol (sym)
516 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0). Result
517 is nil if SYM is not a symbol that names a cell."
518 `(let ((rc (and (symbolp ,sym) (get ,sym 'ses-cell))))
519 (if (eq rc :ses-named)
520 (gethash ,sym ses--named-cell-hashmap)
523 (defun ses-is-cell-sym-p (sym)
524 "Check whether SYM point at a cell of this spread sheet."
525 (let ((rowcol (get sym 'ses-cell)))
527 (if (eq rowcol :ses-named)
528 (and ses--named-cell-hashmap (gethash sym ses--named-cell-hashmap))
529 (and (< (car rowcol) ses--numrows)
530 (< (cdr rowcol) ses--numcols)
531 (eq (ses-cell-symbol (car rowcol) (cdr rowcol)) sym))))))
533 (defmacro ses-cell (sym value formula printer references)
534 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
535 FORMULA, does not reprint using PRINTER, does not check REFERENCES. This is a
536 macro to prevent propagate-on-load viruses. Safety-checking for FORMULA and
537 PRINTER are deferred until first use."
538 (let ((rowcol (ses-sym-rowcol sym)))
539 (ses-formula-record formula)
540 (ses-printer-record printer)
542 (eq safe-functions t)
543 (setq formula `(ses-safe-formula ,formula)))
546 (eq safe-functions t)
547 (setq printer `(ses-safe-printer ,printer)))
548 (aset (aref ses--cells (car rowcol))
550 (ses-make-cell sym formula printer references)))
554 (defmacro ses-column-widths (widths)
555 "Load the vector of column widths from the spreadsheet file. This is a
556 macro to prevent propagate-on-load viruses."
557 (or (and (vectorp widths) (= (length widths) ses--numcols))
558 (error "Bad column-width vector"))
559 ;;To save time later, we also calculate the total width of each line in the
560 ;;print area (excluding the terminating newline)
561 (setq ses--col-widths widths
562 ses--linewidth (apply '+ -1 (mapcar '1+ widths))
563 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
566 (defmacro ses-column-printers (printers)
567 "Load the vector of column printers from the spreadsheet file and checks
568 them for safety. This is a macro to prevent propagate-on-load viruses."
569 (or (and (vectorp printers) (= (length printers) ses--numcols))
570 (error "Bad column-printers vector"))
571 (dotimes (x ses--numcols)
572 (aset printers x (ses-safe-printer (aref printers x))))
573 (setq ses--col-printers printers)
574 (mapc 'ses-printer-record printers)
577 (defmacro ses-default-printer (def)
578 "Load the global default printer from the spreadsheet file and checks it
579 for safety. This is a macro to prevent propagate-on-load viruses."
580 (setq ses--default-printer (ses-safe-printer def))
581 (ses-printer-record def)
584 (defmacro ses-header-row (row)
585 "Load the header row from the spreadsheet file and checks it
586 for safety. This is a macro to prevent propagate-on-load viruses."
587 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
588 (error "Bad header-row"))
589 (setq ses--header-row row)
592 (defmacro ses-dorange (curcell &rest body)
593 "Execute BODY repeatedly, with the variables `row' and `col' set to each
594 cell in the range specified by CURCELL. The range is available in the
595 variables `minrow', `maxrow', `mincol', and `maxcol'."
596 (declare (indent defun) (debug (form body)))
597 (let ((cur (make-symbol "cur"))
598 (min (make-symbol "min"))
599 (max (make-symbol "max"))
600 (r (make-symbol "r"))
601 (c (make-symbol "c")))
602 `(let* ((,cur ,curcell)
603 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
604 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
605 (let ((minrow (car ,min))
610 (if (or (> minrow maxrow) (> mincol maxcol))
611 (error "Empty range"))
612 (dotimes (,r (- maxrow minrow -1))
613 (setq row (+ ,r minrow))
614 (dotimes (,c (- maxcol mincol -1))
615 (setq col (+ ,c mincol))
618 ;;Support for coverage testing.
619 (defmacro 1value (form)
620 "For code-coverage testing, indicate that FORM is expected to always have
623 (defmacro noreturn (form)
624 "For code-coverage testing, indicate that FORM will always signal an error."
628 ;;----------------------------------------------------------------------------
630 ;;----------------------------------------------------------------------------
632 (defun ses-vector-insert (array idx new)
633 "Create a new vector which is one larger than ARRAY and has NEW inserted
635 (let* ((len (length array))
636 (result (make-vector (1+ len) new)))
639 (if (< x idx) x (1+ x))
643 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
644 (defun ses-vector-delete (array idx count)
645 "Create a new vector which is a copy of ARRAY with COUNT objects removed
646 starting at element IDX. ARRAY is either a vector or a symbol whose value
647 is a vector--if a symbol, the new vector is assigned as the symbol's value."
648 (let* ((a (if (arrayp array) array (symbol-value array)))
649 (len (- (length a) count))
650 (result (make-vector len nil)))
652 (aset result x (aref a (if (< x idx) x (+ x count)))))
657 (defun ses-delete-line (count)
658 "Like `kill-line', but no kill ring."
661 (delete-region pos (point))))
663 (defun ses-printer-validate (printer)
664 "Signal an error if PRINTER is not a valid SES cell printer."
668 (and (stringp (car-safe printer)) (not (cdr printer)))
669 (error "Invalid printer function"))
672 (defun ses-printer-record (printer)
673 "Add PRINTER to `ses-read-printer-history' if not already there, after first
674 checking that it is a valid printer function."
675 (ses-printer-validate printer)
676 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
678 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
680 (defun ses-formula-record (formula)
681 "If FORMULA is of the form 'symbol, add it to the list of symbolic formulas
682 for this spreadsheet."
683 (when (and (eq (car-safe formula) 'quote)
684 (symbolp (cadr formula)))
685 (add-to-list 'ses--symbolic-formulas
686 (list (symbol-name (cadr formula))))))
688 (defun ses-column-letter (col)
689 "Return the alphabetic name of column number COL.
690 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
691 (let ((units (char-to-string (+ ?A (% col 26)))))
694 (concat (ses-column-letter (1- (/ col 26))) units))))
696 (defun ses-create-cell-symbol (row col)
697 "Produce a symbol that names the cell (ROW,COL). (0,0) => 'A1."
698 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
700 (defun ses-decode-cell-symbol (str)
701 "Decode a symbol \"A1\" => (0,0). Returns `nil' if STR is not a
702 canonical cell name. Does not save match data."
703 (let (case-fold-search)
704 (and (string-match "\\`\\([A-Z]+\\)\\([0-9]+\\)\\'" str)
705 (let* ((col-str (match-string-no-properties 1 str))
708 (col-idx (1- (length col-str)))
709 (row (1- (string-to-number (match-string-no-properties 2 str)))))
714 (setq col (+ col (* (- (aref col-str col-idx) ?A) col-base))
715 col-base (* col-base 26)
716 col-idx (1- col-idx))
718 (setq col (+ col col-base)))))
721 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
722 "Create buffer-local variables for cells. This is undoable."
723 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
726 (dotimes (row (1+ (- maxrow minrow)))
727 (dotimes (col (1+ (- maxcol mincol)))
728 (setq xrow (+ row minrow)
730 sym (ses-create-cell-symbol xrow xcol))
731 (put sym 'ses-cell (cons xrow xcol))
732 (make-local-variable sym)))))
734 (defun ses-create-cell-variable (sym row col)
735 "Create a buffer-local variable `SYM' for cell at position (ROW, COL).
737 SYM is the symbol for that variable, ROW and COL are integers for
738 row and column of the cell, with numbering starting from 0.
740 Return nil in case of failure."
741 (unless (local-variable-p sym)
742 (make-local-variable sym)
743 (if (let (case-fold-search) (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name sym)))
744 (put sym 'ses-cell (cons row col))
745 (put sym 'ses-cell :ses-named)
746 (setq ses--named-cell-hashmap (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
747 (puthash sym (cons row col) ses--named-cell-hashmap))))
749 ;; We do not delete the ses-cell properties for the cell-variables, in
750 ;; case a formula that refers to this cell is in the kill-ring and is
751 ;; later pasted back in.
752 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
753 "Destroy buffer-local variables for cells. This is undoable."
755 (dotimes (row (1+ (- maxrow minrow)))
756 (dotimes (col (1+ (- maxcol mincol)))
757 (let ((xrow (+ row minrow)) (xcol (+ col mincol)))
758 (setq sym (if (and (< xrow ses--numrows) (< xcol ses--numcols))
759 (ses-cell-symbol xrow xcol)
760 (ses-create-cell-symbol xrow xcol))))
762 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
764 (kill-local-variable sym))))
765 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
768 (defun ses-reset-header-string ()
769 "Flag the header string for update. Upon undo, the header string will be
771 (push '(apply ses-reset-header-string) buffer-undo-list)
772 (setq ses--header-hscroll -1))
774 ;;Split this code off into a function to avoid coverage-testing difficulties
775 (defun ses-time-check (format arg)
776 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
777 and (eval ARG) and reset `ses-start-time' to the current time."
778 (when (> (- (float-time) ses-start-time) 1.0)
779 (message format (eval arg))
780 (setq ses-start-time (float-time)))
784 ;;----------------------------------------------------------------------------
786 ;;----------------------------------------------------------------------------
788 (defun ses-set-cell (row col field val)
789 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
790 cell (ROW,COL). This is undoable. The cell's data will be updated through
791 `post-command-hook'."
792 (let ((cell (ses-get-cell row col))
793 (elt (plist-get '(value t symbol 0 formula 1 printer 2 references 3)
796 (or elt (signal 'args-out-of-range nil))
797 (setq change (if (eq elt t)
798 (ses-set-with-undo (ses-cell-symbol cell) val)
799 (ses-aset-with-undo cell elt val)))
801 (add-to-list 'ses--deferred-write (cons row col))))
802 nil) ; Make coverage-tester happy.
804 (defun ses-cell-set-formula (row col formula)
805 "Store a new formula for (ROW . COL) and enqueue the cell for
806 recalculation via `post-command-hook'. Updates the reference lists for the
807 cells that this cell refers to. Does not update cell value or reprint the
808 cell. To avoid inconsistencies, this function is not interruptible, which
809 means Emacs will crash if FORMULA contains a circular list."
810 (let* ((cell (ses-get-cell row col))
811 (old (ses-cell-formula cell)))
812 (let ((sym (ses-cell-symbol cell))
813 (oldref (ses-formula-references old))
814 (newref (ses-formula-references formula))
817 (add-to-list 'ses--deferred-recalc sym)
818 ;;Delete old references from this cell. Skip the ones that are also
821 (unless (memq ref newref)
822 (setq x (ses-sym-rowcol ref)
825 (ses-set-cell xrow xcol 'references
826 (delq sym (ses-cell-references xrow xcol)))))
827 ;;Add new ones. Skip ones left over from old list
829 (setq x (ses-sym-rowcol ref)
832 x (ses-cell-references xrow xcol))
834 (ses-set-cell xrow xcol 'references (cons sym x))))
835 (ses-formula-record formula)
836 (ses-set-cell row col 'formula formula))))
839 (defun ses-repair-cell-reference-all ()
840 "Repair cell reference and warn if there was some reference corruption."
843 ;; Step 1, reset :ses-repair-reference cell property in the whole sheet.
844 (dotimes (row ses--numrows)
845 (dotimes (col ses--numcols)
846 (let ((references (ses-cell-property-pop :ses-repair-reference
850 (ses-cell-symbol row col)
852 references) errors)))))
854 ;; Step 2, build new.
855 (dotimes (row ses--numrows)
856 (dotimes (col ses--numcols)
857 (let* ((cell (ses-get-cell row col))
858 (sym (ses-cell-symbol cell))
859 (formula (ses-cell-formula cell))
860 (new-ref (ses-formula-references formula)))
861 (dolist (ref new-ref)
862 (let* ((rowcol (ses-sym-rowcol ref))
863 (h (ses-cell-property-get-handle :ses-repair-reference
864 (car rowcol) (cdr rowcol))))
865 (unless (memq ref (ses-cell-property-handle-car h))
866 (ses-cell-property-handle-setcar
869 (ses-cell-property-handle-car h)))))))))
871 ;; Step 3, overwrite with check.
872 (dotimes (row ses--numrows)
873 (dotimes (col ses--numcols)
874 (let* ((cell (ses-get-cell row col))
875 (irrelevant (ses-cell-references cell))
876 (new-ref (ses-cell-property-pop :ses-repair-reference cell))
878 (dolist (ref new-ref)
879 (if (memq ref irrelevant)
880 (setq irrelevant (delq ref irrelevant))
882 (ses-set-cell row col 'references new-ref)
883 (when (or missing irrelevant)
884 (push `( ,(ses-cell-symbol cell)
885 ,@(and missing (list :missing missing))
886 ,@(and irrelevant (list :irrelevant irrelevant)))
889 (warn "----------------------------------------------------------------
890 Some references were corrupted.
892 The following is a list where each element ELT is such
893 that (car ELT) is the reference of cell CELL with corruption,
894 and (cdr ELT) is a property list where
896 * property `:corrupt-property' means that
897 property `:ses-repair-reference' of cell CELL was initially non
900 * property `:missing' is a list of missing references
902 * property `:irrelevant' is a list of non needed references
905 (message "No reference corruption found"))))
907 (defun ses-calculate-cell (row col force)
908 "Calculate and print the value for cell (ROW,COL) using the cell's formula
909 function and print functions, if any. Result is nil for normal operation, or
910 the error signal if the formula or print function failed. The old value is
911 left unchanged if it was *skip* and the new value is nil.
912 Any cells that depend on this cell are queued for update after the end of
913 processing for the current keystroke, unless the new value is the same as
914 the old and FORCE is nil."
915 (let ((cell (ses-get-cell row col))
916 cycle-error formula-error printer-error)
917 (let ((oldval (ses-cell-value cell))
918 (formula (ses-cell-formula cell))
920 this-cell-Dijkstra-attempt-h
921 this-cell-Dijkstra-attempt
922 this-cell-Dijkstra-attempt+1
923 ref-cell-Dijkstra-attempt-h
924 ref-cell-Dijkstra-attempt
926 (when (eq (car-safe formula) 'ses-safe-formula)
927 (setq formula (ses-safe-formula (cadr formula)))
928 (ses-set-cell row col 'formula formula))
930 (setq newval (eval formula))
932 ;; Variable `sig' can't be nil.
933 (nconc sig (list (ses-cell-symbol cell)))
934 (setq formula-error sig
936 (if (and (not newval) (eq oldval '*skip*))
937 ;; Don't lose the *skip* --- previous field spans this one.
938 (setq newval '*skip*))
940 (when (or force (not (eq newval oldval)))
941 (add-to-list 'ses--deferred-write (cons row col)) ; In case force=t.
942 (setq this-cell-Dijkstra-attempt-h
943 (ses-cell-property-get-handle :ses-Dijkstra-attempt cell);
944 this-cell-Dijkstra-attempt
945 (ses-cell-property-handle-car this-cell-Dijkstra-attempt-h))
946 (if (null this-cell-Dijkstra-attempt)
947 (ses-cell-property-handle-setcar
948 this-cell-Dijkstra-attempt-h
949 (setq this-cell-Dijkstra-attempt
950 (cons ses--Dijkstra-attempt-nb 0)))
951 (unless (= ses--Dijkstra-attempt-nb
952 (car this-cell-Dijkstra-attempt))
953 (setcar this-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
954 (setcdr this-cell-Dijkstra-attempt 0)))
955 (setq this-cell-Dijkstra-attempt+1
956 (1+ (cdr this-cell-Dijkstra-attempt)))
957 (ses-set-cell row col 'value newval)
958 (dolist (ref (ses-cell-references cell))
959 (add-to-list 'ses--deferred-recalc ref)
960 (setq ref-rowcol (ses-sym-rowcol ref)
961 ref-cell-Dijkstra-attempt-h
962 (ses-cell-property-get-handle
963 :ses-Dijkstra-attempt
964 (car ref-rowcol) (cdr ref-rowcol))
965 ref-cell-Dijkstra-attempt
966 (ses-cell-property-handle-car ref-cell-Dijkstra-attempt-h))
968 (if (null ref-cell-Dijkstra-attempt)
969 (ses-cell-property-handle-setcar
970 ref-cell-Dijkstra-attempt-h
971 (setq ref-cell-Dijkstra-attempt
972 (cons ses--Dijkstra-attempt-nb
973 this-cell-Dijkstra-attempt+1)))
974 (if (= (car ref-cell-Dijkstra-attempt) ses--Dijkstra-attempt-nb)
975 (setcdr ref-cell-Dijkstra-attempt
976 (max (cdr ref-cell-Dijkstra-attempt)
977 this-cell-Dijkstra-attempt+1))
978 (setcar ref-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
979 (setcdr ref-cell-Dijkstra-attempt
980 this-cell-Dijkstra-attempt+1)))
982 (when (> this-cell-Dijkstra-attempt+1 ses--Dijkstra-weight-bound)
983 ;; Update print of this cell.
984 (throw 'cycle (setq formula-error
985 `(error ,(format "Found cycle on cells %S"
986 (ses-cell-symbol cell)))
987 cycle-error formula-error)))))))
988 (setq printer-error (ses-print-cell row col))
991 (error (error-message-string cycle-error)))
992 formula-error printer-error)))
994 (defun ses-clear-cell (row col)
995 "Delete formula and printer for cell (ROW,COL)."
996 (ses-set-cell row col 'printer nil)
997 (ses-cell-set-formula row col nil))
999 (defcustom ses-self-reference-early-detection nil
1000 "True if cycle detection is early for cells that refer to themselves."
1005 (defun ses-update-cells (list &optional force)
1006 "Recalculate cells in LIST, checking for dependency loops. Prints
1007 progress messages every second. Dependent cells are not recalculated
1008 if the cell's value is unchanged and FORCE is nil."
1009 (let ((ses--deferred-recalc list)
1012 curlist prevlist this-sym this-rowcol formula)
1013 (with-temp-message " "
1014 (while ses--deferred-recalc
1015 ;; In each loop, recalculate cells that refer only to other cells that
1016 ;; have already been recalculated or aren't in the recalculation region.
1017 ;; Repeat until all cells have been processed or until the set of cells
1018 ;; being worked on stops changing.
1020 (message "Recalculating... (%d cells left)"
1021 (length ses--deferred-recalc)))
1022 (setq curlist ses--deferred-recalc
1023 ses--deferred-recalc nil
1026 ;; this-sym has to be popped from curlist *BEFORE* the check, and not
1027 ;; after because of the case of cells referring to themselves.
1028 (setq this-sym (pop curlist)
1029 this-rowcol (ses-sym-rowcol this-sym)
1030 formula (ses-cell-formula (car this-rowcol)
1033 (dolist (ref (ses-formula-references formula))
1034 (if (and ses-self-reference-early-detection (eq ref this-sym))
1035 (error "Cycle found: cell %S is self-referring" this-sym)
1036 (when (or (memq ref curlist)
1037 (memq ref ses--deferred-recalc))
1038 ;; This cell refers to another that isn't done yet
1039 (add-to-list 'ses--deferred-recalc this-sym)
1041 ;; ses-update-cells is called from post-command-hook, so
1042 ;; inhibit-quit is implicitly bound to t.
1044 ;; Abort the recalculation. User will probably undo now.
1046 (ses-calculate-cell (car this-rowcol) (cdr this-rowcol) force)))
1047 (dolist (ref ses--deferred-recalc)
1048 (add-to-list 'nextlist ref)))
1049 (when ses--deferred-recalc
1050 ;; Just couldn't finish these.
1051 (dolist (x ses--deferred-recalc)
1052 (let ((this-rowcol (ses-sym-rowcol x)))
1053 (ses-set-cell (car this-rowcol) (cdr this-rowcol) 'value '*error*)
1054 (1value (ses-print-cell (car this-rowcol) (cdr this-rowcol)))))
1055 (error "Circular references: %s" ses--deferred-recalc))
1057 ;; Can't use save-excursion here: if the cell under point is updated,
1058 ;; save-excursion's marker will move past the cell.
1062 ;;----------------------------------------------------------------------------
1064 ;;----------------------------------------------------------------------------
1066 (defun ses-in-print-area ()
1067 "Return t if point is in print area of spreadsheet."
1068 (<= (point) ses--data-marker))
1070 ;; We turn off point-motion-hooks and explicitly position the cursor, in case
1071 ;; the intangible properties have gotten screwed up (e.g., when ses-goto-print
1072 ;; is called during a recursive ses-print-cell).
1073 (defun ses-goto-print (row col)
1074 "Move point to print area for cell (ROW,COL)."
1075 (let ((inhibit-point-motion-hooks t)
1077 (goto-char (point-min))
1079 ;; Calculate column position.
1081 (setq n (+ n (ses-col-width c) 1)))
1082 ;; Move to the position.
1083 (and (> n (move-to-column n))
1085 ;; Move point to the bol of next line (for TAB at the last cell).
1088 (defun ses-set-curcell ()
1089 "Set `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
1090 region, or nil if cursor is not at a cell."
1091 (if (or (not mark-active)
1093 (= (region-beginning) (region-end)))
1095 (setq ses--curcell (get-text-property (point) 'intangible))
1097 (let ((bcell (get-text-property (region-beginning) 'intangible))
1098 (ecell (get-text-property (1- (region-end)) 'intangible)))
1099 (when (= (region-end) ses--data-marker)
1100 ;; Correct for overflow.
1101 (setq ecell (get-text-property (- (region-end) 2) 'intangible)))
1102 (setq ses--curcell (if (and bcell ecell)
1107 (defun ses-check-curcell (&rest args)
1108 "Signal an error if `ses--curcell' is inappropriate.
1109 The end marker is appropriate if some argument is 'end.
1110 A range is appropriate if some argument is 'range.
1111 A single cell is appropriate unless some argument is 'needrange."
1112 (if (eq ses--curcell t)
1113 ;; curcell recalculation was postponed, but user typed ahead.
1117 (or (memq 'end args)
1118 (error "Not at cell")))
1119 ((consp ses--curcell)
1120 (or (memq 'range args)
1121 (memq 'needrange args)
1122 (error "Can't use a range")))
1123 ((memq 'needrange args)
1124 (error "Need a range"))))
1126 (defun ses-print-cell (row col)
1127 "Format and print the value of cell (ROW,COL) to the print area.
1128 Use the cell's printer function. If the cell's new print form is too wide,
1129 it will spill over into the following cell, but will not run off the end of the
1130 row or overwrite the next non-nil field. Result is nil for normal operation,
1131 or the error signal if the printer function failed and the cell was formatted
1132 with \"%s\". If the cell's value is *skip*, nothing is printed because the
1133 preceding cell has spilled over."
1134 (catch 'ses-print-cell
1135 (let* ((cell (ses-get-cell row col))
1136 (value (ses-cell-value cell))
1137 (printer (ses-cell-printer cell))
1139 text sig startpos x)
1140 ;; Create the string to print.
1143 ;; Don't print anything.
1144 (throw 'ses-print-cell nil))
1145 ((eq value '*error*)
1146 (setq text (make-string (ses-col-width col) ?#)))
1148 ;; Deferred safety-check on printer.
1149 (if (eq (car-safe printer) 'ses-safe-printer)
1150 (ses-set-cell row col 'printer
1151 (setq printer (ses-safe-printer (cadr printer)))))
1153 (setq text (ses-call-printer (or printer
1154 (ses-col-printer col)
1155 ses--default-printer)
1157 (if (consp ses-call-printer-return)
1158 ;; Printer returned an error.
1159 (setq sig ses-call-printer-return))))
1160 ;; Adjust print width to match column width.
1161 (let ((width (ses-col-width col))
1162 (len (string-width text)))
1165 ;; Fill field to length with spaces.
1166 (setq len (make-string (- width len) ?\s)
1167 text (if (eq ses-call-printer-return t)
1169 (concat len text))))
1171 ;; Spill over into following cells, if possible.
1172 (let ((maxwidth width))
1173 (while (and (> len maxwidth)
1174 (< maxcol ses--numcols)
1175 (or (not (setq x (ses-cell-value row maxcol)))
1178 ;; Set this cell to '*skip* so it won't overwrite our spillover.
1179 (ses-set-cell row maxcol 'value '*skip*))
1180 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
1181 maxcol (1+ maxcol)))
1182 (if (<= len maxwidth)
1183 ;; Fill to complete width of all the fields spanned.
1184 (setq text (concat text (make-string (- maxwidth len) ?\s)))
1185 ;; Not enough room to end of line or next non-nil field. Truncate
1186 ;; if string or decimal; otherwise fill with error indicator.
1187 (setq sig `(error "Too wide" ,text))
1190 (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
1191 ((and (numberp value)
1192 (string-match "\\.[0-9]+" text)
1195 (- (match-end 0) (match-beginning 0))))))
1196 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
1197 (setq text (concat (substring text
1199 (- (match-beginning 0) width))
1200 (substring text (match-end 0)))))
1202 (setq text (make-string maxwidth ?#)))))))))
1203 ;; Substitute question marks for tabs and newlines. Newlines are used as
1204 ;; row-separators; tabs could confuse the reimport logic.
1205 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
1206 (ses-goto-print row col)
1207 (setq startpos (point))
1208 ;; Install the printed result. This is not interruptible.
1209 (let ((inhibit-read-only t)
1211 (let ((inhibit-point-motion-hooks t))
1212 (delete-region (point) (progn
1213 (move-to-column (+ (current-column)
1214 (string-width text)))
1216 ;; We use concat instead of inserting separate strings in order to
1217 ;; reduce the number of cells in the undo list.
1218 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
1219 ;; We use set-text-properties to prevent a wacky print function from
1220 ;; inserting rogue properties, and to ensure that the keymap property is
1221 ;; inherited (is it a bug that only unpropertized strings actually
1222 ;; inherit from surrounding text?)
1223 (set-text-properties 0 (length x) nil x)
1224 (insert-and-inherit x)
1225 (put-text-property startpos (point) 'intangible
1226 (ses-cell-symbol cell))
1227 (when (and (zerop row) (zerop col))
1228 ;; Reconstruct special beginning-of-buffer attributes.
1229 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
1230 (put-text-property (point-min) (point) 'read-only 'ses)
1231 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)))
1232 (if (= row (1- ses--header-row))
1233 ;; This line is part of the header --- force recalc.
1234 (ses-reset-header-string))
1235 ;; If this cell (or a preceding one on the line) previously spilled over
1236 ;; and has gotten shorter, redraw following cells on line recursively.
1237 (when (and (< maxcol ses--numcols)
1238 (eq (ses-cell-value row maxcol) '*skip*))
1239 (ses-set-cell row maxcol 'value nil)
1240 (ses-print-cell row maxcol))
1241 ;; Return to start of cell.
1242 (goto-char startpos)
1245 (defun ses-call-printer (printer &optional value)
1246 "Invoke PRINTER (a string or parenthesized string or function-symbol or
1247 lambda of one argument) on VALUE. Result is the printed cell as a string.
1248 The variable `ses-call-printer-return' is set to t if the printer used
1249 parenthesis to request left-justification, or the error-signal if the
1250 printer signaled one (and \"%s\" is used as the default printer), else nil."
1251 (setq ses-call-printer-return nil)
1252 (condition-case signal
1256 (format printer value)
1258 ((stringp (car-safe printer))
1259 (setq ses-call-printer-return t)
1261 (format (car printer) value)
1264 (setq value (funcall printer (or value "")))
1267 (or (stringp (car-safe value))
1268 (error "Printer should return \"string\" or (\"string\")"))
1269 (setq ses-call-printer-return t)
1272 (setq ses-call-printer-return signal)
1273 (prin1-to-string value t))))
1275 (defun ses-adjust-print-width (col change)
1276 "Insert CHANGE spaces in front of column COL, or at end of line if
1277 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
1278 `inhibit-quit' to t."
1279 (let ((inhibit-read-only t)
1280 (blank (if (> change 0) (make-string change ?\s)))
1281 (at-end (= col ses--numcols)))
1282 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
1283 ;; ses-set-with-undo always returns t for strings.
1284 (1value (ses-set-with-undo 'ses--blank-line
1285 (concat (make-string ses--linewidth ?\s) "\n")))
1286 (dotimes (row ses--numrows)
1287 (ses-goto-print row col)
1289 ;; Insert new columns before newline.
1290 (let ((inhibit-point-motion-hooks t))
1294 (delete-char (- change))))))
1296 (defun ses-print-cell-new-width (row col)
1297 "Same as `ses-print-cell', except if the cell's value is *skip*,
1298 the preceding nonskipped cell is reprinted. This function is used
1299 when the width of cell (ROW,COL) has changed."
1300 (if (not (eq (ses-cell-value row col) '*skip*))
1301 (ses-print-cell row col)
1302 ;;Cell was skipped over - reprint previous
1303 (ses-goto-print row col)
1305 (let ((rowcol (ses-sym-rowcol (get-text-property (point) 'intangible))))
1306 (ses-print-cell (car rowcol) (cdr rowcol)))))
1309 ;;----------------------------------------------------------------------------
1311 ;;----------------------------------------------------------------------------
1314 "Turn off narrowing, to be reenabled at end of command loop."
1315 (if (buffer-narrowed-p)
1316 (setq ses--deferred-narrow t))
1319 (defun ses-goto-data (def &optional col)
1320 "Move point to data area for (DEF,COL). If DEF is a row
1321 number, COL is the column number for a data cell -- otherwise DEF
1322 is one of the symbols ses--col-widths, ses--col-printers,
1323 ses--default-printer, ses--numrows, or ses--numcols."
1325 (let ((inhibit-point-motion-hooks t)) ; In case intangible attrs are wrong.
1329 (goto-char ses--data-marker)
1330 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
1331 ;; Convert def-symbol to offset.
1332 (setq def (plist-get ses-paramlines-plist def))
1333 (or def (signal 'args-out-of-range nil))
1334 (goto-char ses--params-marker)
1335 (forward-line def))))
1337 (defun ses-set-parameter (def value &optional elem)
1338 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1339 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1340 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
1342 ;; We call ses-goto-data early, using the old values of numrows and numcols
1343 ;; in case one of them is being changed.
1345 (let ((inhibit-read-only t)
1346 (fmt (plist-get '(ses--col-widths "(ses-column-widths %S)"
1347 ses--col-printers "(ses-column-printers %S)"
1348 ses--default-printer "(ses-default-printer %S)"
1349 ses--header-row "(ses-header-row %S)"
1350 ses--file-format " %S ;SES file-format"
1351 ses--numrows " %S ;numrows"
1352 ses--numcols " %S ;numcols")
1357 (setq oldval (aref (symbol-value def) elem))
1358 (aset (symbol-value def) elem value))
1359 (setq oldval (symbol-value def))
1361 ;; Special undo since it's outside the narrowed buffer.
1362 (let (buffer-undo-list)
1363 (delete-region (point) (line-end-position))
1364 (insert (format fmt (symbol-value def))))
1365 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1368 (defun ses-write-cells ()
1369 "Write cells in `ses--deferred-write' from local variables to data area.
1370 Newlines in the data are escaped."
1371 (let* ((inhibit-read-only t)
1372 (print-escape-newlines t)
1373 rowcol row col cell sym formula printer text)
1374 (setq ses-start-time (float-time))
1375 (with-temp-message " "
1377 (while ses--deferred-write
1378 (ses-time-check "Writing... (%d cells left)"
1379 '(length ses--deferred-write))
1380 (setq rowcol (pop ses--deferred-write)
1383 cell (ses-get-cell row col)
1384 sym (ses-cell-symbol cell)
1385 formula (ses-cell-formula cell)
1386 printer (ses-cell-printer cell))
1387 (if (eq (car-safe formula) 'ses-safe-formula)
1388 (setq formula (cadr formula)))
1389 (if (eq (car-safe printer) 'ses-safe-printer)
1390 (setq printer (cadr printer)))
1391 ;; This is noticeably faster than (format "%S %S %S %S %S")
1392 (setq text (concat "(ses-cell "
1395 (prin1-to-string (symbol-value sym))
1397 (prin1-to-string formula)
1399 (prin1-to-string printer)
1401 (if (atom (ses-cell-references cell))
1404 (mapconcat 'symbol-name
1405 (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 (add-to-list 'result-so-far formula)
1429 ((eq (car formula) 'ses-range)
1431 (cdr (funcall 'macroexpand
1432 (list 'ses-range (nth 1 formula)
1434 (add-to-list 'result-so-far cur)))
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 (add-to-list 'ses--deferred-recalc
1604 (ses-create-cell-symbol row col)))
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-set-with-undo (sym newval)
1695 "Like set, but undoable. Result is t if value has changed."
1696 ;; We try to avoid adding redundant entries to the undo list, but this is
1697 ;; unavoidable for strings because equal ignores text properties and there's
1698 ;; no easy way to get the whole property list to see if it's different!
1699 (unless (and (boundp sym)
1700 (equal (symbol-value sym) newval)
1701 (not (stringp newval)))
1702 (push (if (boundp sym)
1703 `(apply ses-set-with-undo ,sym ,(symbol-value sym))
1704 `(apply ses-unset-with-undo ,sym))
1709 (defun ses-unset-with-undo (sym)
1710 "Set SYM to be unbound. This is undoable."
1711 (when (1value (boundp sym)) ; Always bound, except after a programming error.
1712 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
1715 (defun ses-aset-with-undo (array idx newval)
1716 "Like `aset', but undoable.
1717 Result is t if element has changed."
1718 (unless (equal (aref array idx) newval)
1719 (push `(apply ses-aset-with-undo ,array ,idx
1720 ,(aref array idx)) buffer-undo-list)
1721 (aset array idx newval)
1725 ;;----------------------------------------------------------------------------
1726 ;; Startup for major mode
1727 ;;----------------------------------------------------------------------------
1730 "Parse the current buffer and set up buffer-local variables.
1731 Does not execute cell formulas or print functions."
1733 ;; Read our global parameters, which should be a 3-element list.
1734 (goto-char (point-max))
1735 (search-backward ";; Local Variables:\n" nil t)
1737 (setq ses--params-marker (point-marker))
1738 (let ((params (ignore-errors (read (current-buffer)))))
1739 (or (and (= (safe-length params) 3)
1740 (numberp (car params))
1741 (numberp (cadr params))
1742 (>= (cadr params) 0)
1743 (numberp (nth 2 params))
1744 (> (nth 2 params) 0))
1745 (error "Invalid SES file"))
1746 (setq ses--file-format (car params)
1747 ses--numrows (cadr params)
1748 ses--numcols (nth 2 params))
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 2)
1754 (message "Upgrading from SES-1 file format")))
1755 (or (= ses--file-format 2)
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 ;; Skip over print area, which we assume is correct.
1762 (goto-char (point-min))
1763 (forward-line ses--numrows)
1764 (or (looking-at-p ses-print-data-boundary)
1765 (error "Missing marker between print and data areas"))
1767 (setq ses--data-marker (point-marker))
1768 (forward-char (1- (length ses-print-data-boundary)))
1769 ;; Initialize printer and symbol lists.
1770 (mapc 'ses-printer-record ses-standard-printer-functions)
1771 (setq ses--symbolic-formulas nil)
1772 ;; Load cell definitions.
1773 (dotimes (row ses--numrows)
1774 (dotimes (col ses--numcols)
1775 (let* ((x (read (current-buffer)))
1776 (sym (car-safe (cdr-safe x))))
1777 (or (and (looking-at-p "\n")
1778 (eq (car-safe x) 'ses-cell)
1779 (ses-create-cell-variable sym row col))
1780 (error "Cell-def error"))
1782 (or (looking-at-p "\n\n")
1783 (error "Missing blank line between rows")))
1784 ;; Load global parameters.
1785 (let ((widths (read (current-buffer)))
1786 (n1 (char-after (point)))
1787 (printers (read (current-buffer)))
1788 (n2 (char-after (point)))
1789 (def-printer (read (current-buffer)))
1790 (n3 (char-after (point)))
1791 (head-row (read (current-buffer)))
1792 (n4 (char-after (point))))
1793 (or (and (eq (car-safe widths) 'ses-column-widths)
1795 (eq (car-safe printers) 'ses-column-printers)
1797 (eq (car-safe def-printer) 'ses-default-printer)
1799 (eq (car-safe head-row) 'ses-header-row)
1801 (error "Invalid SES global parameters"))
1802 (1value (eval widths))
1803 (1value (eval def-printer))
1804 (1value (eval printers))
1805 (1value (eval head-row)))
1806 ;; Should be back at global-params.
1808 (or (looking-at-p (replace-regexp-in-string "1" "[0-9]+"
1809 ses-initial-global-parameters))
1810 (error "Problem with column-defs or global-params"))
1811 ;; Check for overall newline count in definitions area.
1813 (let ((start (point)))
1814 (ses-goto-data 'ses--numrows)
1815 (or (= (point) start)
1816 (error "Extraneous newlines someplace?"))))
1819 "Set up for display of only the printed cell values.
1821 Narrows the buffer to show only the print area. Gives it `read-only' and
1822 `intangible' properties. Sets up highlighting for current cell."
1824 (let ((end (point-min))
1825 (inhibit-read-only t)
1826 (inhibit-point-motion-hooks t)
1827 (was-modified (buffer-modified-p))
1829 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1830 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1831 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1832 ;; The print area is read-only (except for our special commands) and uses a
1834 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1835 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1836 ;; For the beginning of the buffer, we want the read-only and keymap
1837 ;; attributes to be inherited from the first character.
1838 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1839 ;; Create intangible properties, which also indicate which cell the text
1841 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1842 (dotimes (col ses--numcols)
1844 sym (ses-cell-symbol row col))
1845 ;; Include skipped cells following this one.
1846 (while (and (< col (1- ses--numcols))
1847 (eq (ses-cell-value row (1+ col)) '*skip*))
1848 (setq end (+ end (ses-col-width col) 1)
1850 (setq end (save-excursion
1852 (move-to-column (+ (current-column) (- end pos)
1853 (ses-col-width col)))
1855 (+ end (ses-col-width col) 1)
1858 (put-text-property pos end 'intangible sym)))
1859 ;; Adding these properties did not actually alter the text.
1860 (unless was-modified
1861 (restore-buffer-modified-p nil)
1862 (buffer-disable-undo)
1863 (buffer-enable-undo)))
1864 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1865 ;; because column A must be at least 1 column wide.
1866 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1867 (overlay-put ses--curcell-overlay 'face 'underline))
1869 (defun ses-cleanup ()
1870 "Cleanup when changing a buffer from SES mode to something else.
1871 Delete overlays, remove special text properties."
1873 (let ((inhibit-read-only t)
1874 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1875 ;; user "the file is modified, do you really want to make modifications
1876 ;; to this buffer", where the "modifications" refer to the irrelevant
1877 ;; set-text-properties below.
1878 (buffer-file-name nil)
1879 (was-modified (buffer-modified-p)))
1880 ;; Delete read-only, keymap, and intangible properties.
1881 (set-text-properties (point-min) (point-max) nil)
1883 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1884 (unless was-modified
1885 (restore-buffer-modified-p nil))))
1889 "Major mode for Simple Emacs Spreadsheet.
1891 When you invoke SES in a new buffer, it is divided into cells
1892 that you can enter data into. You can navigate the cells with
1893 the arrow keys and add more cells with the tab key. The contents
1894 of these cells can be numbers, text, or Lisp expressions. (To
1895 enter text, enclose it in double quotes.)
1897 In an expression, you can use cell coordinates to refer to the
1898 contents of another cell. For example, you can sum a range of
1899 cells with `(+ A1 A2 A3)'. There are specialized functions like
1900 `ses+' (addition for ranges with empty cells), `ses-average' (for
1901 performing calculations on cells), and `ses-range' and `ses-select'
1902 \(for extracting ranges of cells).
1904 Each cell also has a print function that controls how it is
1907 Each SES buffer is divided into a print area and a data area.
1908 Normally, you can simply use SES to look at and manipulate the print
1909 area, and let SES manage the data area outside the visible region.
1911 See \"ses-example.ses\" (in `data-directory') for an example
1912 spreadsheet, and the Info node `(ses)Top.'
1914 In the following, note the separate keymaps for cell editing mode
1915 and print mode specifications. Key definitions:
1918 These key definitions are active only in the print area (the visible
1920 \\{ses-mode-print-map}
1921 These are active only in the minibuffer, when entering or editing a
1923 \\{ses-mode-edit-map}"
1925 (unless (and (boundp 'ses--deferred-narrow)
1926 (eq ses--deferred-narrow 'ses-mode))
1927 (kill-all-local-variables)
1929 (setq major-mode 'ses-mode
1931 next-line-add-newlines nil
1933 ;; SES deliberately puts lots of trailing whitespace in its buffer.
1934 show-trailing-whitespace nil
1935 ;; Cell ranges do not work reasonably without this.
1936 transient-mark-mode t
1937 ;; Not to use tab characters for safe (tabs may do bad for column
1939 indent-tabs-mode nil)
1940 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1941 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1942 (setq header-line-format '(:eval (progn
1943 (when (/= (window-hscroll)
1944 ses--header-hscroll)
1945 ;; Reset ses--header-hscroll first,
1946 ;; to avoid recursion problems when
1947 ;; debugging ses-create-header-string
1948 (setq ses--header-hscroll
1950 (ses-create-header-string))
1951 ses--header-string)))
1952 (let ((was-empty (zerop (buffer-size)))
1953 (was-modified (buffer-modified-p)))
1956 ;; Initialize buffer to contain one cell, for now.
1957 (insert ses-initial-file-contents))
1961 (unless (equal ses-initial-default-printer
1962 (1value ses--default-printer))
1963 (1value (ses-read-default-printer ses-initial-default-printer)))
1964 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1965 (1value (ses-set-column-width 0 ses-initial-column-width)))
1967 (if (> (car ses-initial-size) (1value ses--numrows))
1968 (1value (ses-insert-row (1- (car ses-initial-size)))))
1969 (if (> (cdr ses-initial-size) (1value ses--numcols))
1970 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1972 (restore-buffer-modified-p was-modified)
1973 (buffer-disable-undo)
1974 (buffer-enable-undo)
1975 (goto-char (point-min))))
1976 (use-local-map ses-mode-map)
1977 ;; Set the deferred narrowing flag (we can't narrow until after
1978 ;; after-find-file completes). If .ses is on the auto-load alist and the
1979 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
1980 ;; special flag to detect this (will be reset by ses-command-hook). For
1981 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
1982 ;; so use an idle timer to make sure.
1983 (setq ses--deferred-narrow 'ses-mode)
1984 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1985 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1986 (run-mode-hooks 'ses-mode-hook)))
1988 (put 'ses-mode 'mode-class 'special)
1990 (defun ses-command-hook ()
1991 "Invoked from `post-command-hook'. If point has moved to a different cell,
1992 moves the underlining overlay. Performs any recalculations or cell-data
1993 writes that have been deferred. If buffer-narrowing has been deferred,
1994 narrows the buffer now."
1996 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
1997 (when ses--deferred-recalc
1998 ;; We reset the deferred list before starting on the recalc --- in
1999 ;; case of error, we don't want to retry the recalc after every
2001 (ses-initialize-Dijkstra-attempt)
2002 (let ((old ses--deferred-recalc))
2003 (setq ses--deferred-recalc nil)
2004 (ses-update-cells old)))
2005 (when ses--deferred-write
2006 ;; We don't reset the deferred list before starting --- the most
2007 ;; likely error is keyboard-quit, and we do want to keep trying these
2008 ;; writes after a quit.
2010 (push '(apply ses-widen) buffer-undo-list))
2011 (when ses--deferred-narrow
2012 ;; We're not allowed to narrow the buffer until after-find-file has
2013 ;; read the local variables at the end of the file. Now it's safe to
2014 ;; do the narrowing.
2015 (narrow-to-region (point-min) ses--data-marker)
2016 (setq ses--deferred-narrow nil))
2017 ;; Update the mode line.
2018 (let ((oldcell ses--curcell))
2020 (unless (eq ses--curcell oldcell)
2023 (setq mode-line-process nil))
2024 ((atom ses--curcell)
2025 (setq mode-line-process (list " cell "
2026 (symbol-name ses--curcell))))
2028 (setq mode-line-process (list " range "
2029 (symbol-name (car ses--curcell))
2031 (symbol-name (cdr ses--curcell))))))
2032 (force-mode-line-update)))
2033 ;; Use underline overlay for single-cells only, turn off otherwise.
2034 (if (listp ses--curcell)
2035 (move-overlay ses--curcell-overlay 2 2)
2036 (let ((next (next-single-property-change (point) 'intangible)))
2037 (move-overlay ses--curcell-overlay (point) (1- next))))
2038 (when (not (pos-visible-in-window-p))
2039 ;; Scrolling will happen later.
2040 (run-with-idle-timer 0.01 nil 'ses-command-hook)
2041 (setq ses--curcell t)))
2042 ;; Prevent errors in this post-command-hook from silently erasing the hook!
2044 (unless executing-kbd-macro
2046 (message "%s" (error-message-string err))))
2047 nil) ; Make coverage-tester happy.
2049 (defun ses-create-header-string ()
2050 "Set up `ses--header-string' as the buffer's header line.
2051 Based on the current set of columns and `window-hscroll' position."
2052 (let ((totwidth (- (window-hscroll)))
2054 ;; Leave room for the left-side fringe and scrollbar.
2055 (push (propertize " " 'display '((space :align-to 0))) result)
2056 (dotimes (col ses--numcols)
2057 (setq width (ses-col-width col)
2058 totwidth (+ totwidth width 1))
2060 ;; Scrolled so intercolumn space is leftmost.
2062 (when (> totwidth 1)
2063 (if (> ses--header-row 0)
2065 (ses-goto-print (1- ses--header-row) col)
2066 (setq x (buffer-substring-no-properties (point)
2068 ;; Strip trailing space.
2069 (if (string-match "[ \t]+\\'" x)
2070 (setq x (substring x 0 (match-beginning 0))))
2071 ;; Cut off excess text.
2072 (if (>= (length x) totwidth)
2073 (setq x (substring x 0 (- totwidth -1)))))
2074 (setq x (ses-column-letter col)))
2075 (push (propertize x 'face ses-box-prop) result)
2076 (push (propertize "."
2077 'display `((space :align-to ,(1- totwidth)))
2080 ;; Allow the following space to be squished to make room for the 3-D box
2081 ;; Coverage test ignores properties, thinks this is always a space!
2082 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2084 (if (> ses--header-row 0)
2085 (push (propertize (format " [row %d]" ses--header-row)
2086 'display '((height (- 1))))
2088 (setq ses--header-string (apply 'concat (nreverse result)))))
2091 ;;----------------------------------------------------------------------------
2092 ;; Redisplay and recalculation
2093 ;;----------------------------------------------------------------------------
2095 (defun ses-jump (sym)
2096 "Move point to cell SYM."
2097 (interactive "SJump to cell: ")
2098 (let ((rowcol (ses-sym-rowcol sym)))
2099 (or rowcol (error "Invalid cell name"))
2100 (if (eq (symbol-value sym) '*skip*)
2101 (error "Cell is covered by preceding cell"))
2102 (ses-goto-print (car rowcol) (cdr rowcol))))
2104 (defun ses-jump-safe (cell)
2105 "Like `ses-jump', but no error if invalid cell."
2109 (defun ses-reprint-all (&optional nonarrow)
2110 "Recreate the display area. Calls all printer functions. Narrows to
2111 print area if NONARROW is nil."
2115 (setq ses--deferred-narrow t))
2116 (let ((startcell (get-text-property (point) 'intangible))
2117 (inhibit-read-only t))
2119 (goto-char (point-min))
2120 (search-forward ses-print-data-boundary)
2121 (backward-char (length ses-print-data-boundary))
2122 (delete-region (point-min) (point))
2123 ;; Insert all blank lines before printing anything, so ses-print-cell can
2124 ;; find the data area when inserting or deleting *skip* values for cells.
2125 (dotimes (row ses--numrows)
2126 (insert-and-inherit ses--blank-line))
2127 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2128 (if (eq (ses-cell-value row 0) '*skip*)
2129 ;; Column deletion left a dangling skip.
2130 (ses-set-cell row 0 'value nil))
2131 (dotimes (col ses--numcols)
2132 (ses-print-cell row col))
2133 (beginning-of-line 2))
2134 (ses-jump-safe startcell)))
2136 (defun ses-initialize-Dijkstra-attempt ()
2137 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2138 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2140 (defun ses-recalculate-cell ()
2141 "Recalculate and reprint the current cell or range.
2143 For an individual cell, shows the error if the formula or printer
2144 signals one, or otherwise shows the cell's complete value. For a range, the
2145 cells are recalculated in \"natural\" order, so cells that other cells refer
2146 to are recalculated first."
2148 (ses-check-curcell 'range)
2150 (ses-initialize-Dijkstra-attempt)
2151 (let (sig cur-rowcol)
2152 (setq ses-start-time (float-time))
2153 (if (atom ses--curcell)
2155 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2157 (ses-cell-property-set :ses-Dijkstra-attempt
2158 (cons ses--Dijkstra-attempt-nb 0)
2159 (car cur-rowcol) (cdr cur-rowcol) )
2160 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2161 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2162 (cdr cur-rowcol)))))
2163 ;; First, recalculate all cells that don't refer to other cells and
2164 ;; produce a list of cells with references.
2165 (ses-dorange ses--curcell
2166 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
2169 ;; The t causes an error if the cell has references. If no
2170 ;; references, the t will be the result value.
2171 (1value (ses-formula-references (ses-cell-formula row col) t))
2172 (ses-cell-property-set :ses-Dijkstra-attempt
2173 (cons ses--Dijkstra-attempt-nb 0)
2175 (when (setq sig (ses-calculate-cell row col t))
2176 (nconc sig (list (ses-cell-symbol row col)))))
2177 (wrong-type-argument
2178 ;; The formula contains a reference.
2179 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
2180 ;; Do the update now, so we can force recalculation.
2181 (let ((x ses--deferred-recalc))
2182 (setq ses--deferred-recalc nil)
2183 (condition-case hold
2184 (ses-update-cells x t)
2185 (error (setq sig hold))))
2188 (message "%s" (error-message-string sig)))
2189 ((consp ses--curcell)
2192 (princ (symbol-value ses--curcell))))))
2194 (defun ses-recalculate-all ()
2195 "Recalculate and reprint all cells."
2197 (let ((startcell (get-text-property (point) 'intangible))
2198 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2199 (1- ses--numcols)))))
2200 (ses-recalculate-cell)
2201 (ses-jump-safe startcell)))
2203 (defun ses-truncate-cell ()
2204 "Reprint current cell, but without spillover into any following blank cells."
2207 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2210 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
2211 (eq (ses-cell-value row (1+ col)) '*skip*))
2212 ;; This cell has spill-over. We'll momentarily pretend the following cell
2214 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
2215 (ses-print-cell row col)))
2216 ;; Now remove the *skip*. ses-print-cell is always nil here.
2217 (ses-set-cell row (1+ col) 'value nil)
2218 (1value (ses-print-cell row (1+ col))))))
2220 (defun ses-reconstruct-all ()
2221 "Reconstruct buffer based on cell data stored in Emacs variables."
2224 ;;Reconstruct reference lists.
2226 ;;Delete old reference lists
2227 (dotimes-with-progress-reporter
2228 (row ses--numrows) "Deleting references..."
2229 (dotimes (col ses--numcols)
2230 (ses-set-cell row col 'references nil)))
2231 ;;Create new reference lists
2232 (dotimes-with-progress-reporter
2233 (row ses--numrows) "Computing references..."
2234 (dotimes (col ses--numcols)
2235 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2236 (setq x (ses-sym-rowcol ref)
2239 (ses-set-cell yrow ycol 'references
2240 (cons (ses-cell-symbol row col)
2241 (ses-cell-references yrow ycol)))))))
2242 ;; Delete everything and reconstruct basic data area.
2244 (let ((inhibit-read-only t))
2245 (goto-char (point-max))
2246 (if (search-backward ";; Local Variables:\n" nil t)
2247 (delete-region (point-min) (point))
2248 ;; Buffer is quite screwed up --- can't even save the user-specified
2250 (delete-region (point-min) (point-max))
2251 (insert ses-initial-file-trailer)
2252 (goto-char (point-min)))
2253 ;; Create a blank display area.
2254 (dotimes (row ses--numrows)
2255 (insert ses--blank-line))
2256 (insert ses-print-data-boundary)
2257 (backward-char (1- (length ses-print-data-boundary)))
2258 (setq ses--data-marker (point-marker))
2259 (forward-char (1- (length ses-print-data-boundary)))
2260 ;; Placeholders for cell data.
2261 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2262 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
2264 (insert ses-initial-global-parameters)
2265 (backward-char (1- (length ses-initial-global-parameters)))
2266 (setq ses--params-marker (point-marker))
2267 (forward-char (1- (length ses-initial-global-parameters))))
2268 (ses-set-parameter 'ses--col-widths ses--col-widths)
2269 (ses-set-parameter 'ses--col-printers ses--col-printers)
2270 (ses-set-parameter 'ses--default-printer ses--default-printer)
2271 (ses-set-parameter 'ses--header-row ses--header-row)
2272 (ses-set-parameter 'ses--numrows ses--numrows)
2273 (ses-set-parameter 'ses--numcols ses--numcols)
2274 ;;Keep our old narrowing
2276 (ses-recalculate-all)
2277 (goto-char (point-min)))
2280 ;;----------------------------------------------------------------------------
2281 ;; Input of cell formulas
2282 ;;----------------------------------------------------------------------------
2284 (defun ses-edit-cell (row col newval)
2285 "Display current cell contents in minibuffer, for editing. Returns nil if
2286 cell formula was unsafe and user declined confirmation."
2289 (barf-if-buffer-read-only)
2291 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2294 (formula (ses-cell-formula row col))
2296 (if (eq (car-safe formula) 'ses-safe-formula)
2297 (setq formula (cadr formula)))
2298 (if (eq (car-safe formula) 'quote)
2299 (setq initial (format "'%S" (cadr formula)))
2300 (setq initial (prin1-to-string formula)))
2301 (if (stringp formula)
2302 ;; Position cursor inside close-quote.
2303 (setq initial (cons initial (length initial))))
2305 (read-from-minibuffer (format "Cell %s: " ses--curcell)
2308 t ; Convert to Lisp object.
2309 'ses-read-cell-history)))))
2310 (when (ses-warn-unsafe newval 'unsafep)
2312 (ses-cell-set-formula row col newval)
2315 (defun ses-read-cell (row col newval)
2316 "Self-insert for initial character of cell function."
2318 (let* ((initial (this-command-keys))
2319 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2320 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
2321 (barf-if-buffer-read-only)
2324 (read-from-minibuffer
2325 (format "Cell %s: " ses--curcell)
2326 (cons (if (equal initial "\"") "\"\""
2327 (if (equal initial "(") "()" initial)) 2)
2329 t ; Convert to Lisp object.
2330 'ses-read-cell-history
2331 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2334 (when (ses-edit-cell row col newval)
2335 (ses-command-hook) ; Update cell widths before movement.
2336 (dolist (x ses-after-entry-functions)
2339 (defun ses-read-symbol (row col symb)
2340 "Self-insert for a symbol as a cell formula. The set of all symbols that
2341 have been used as formulas in this spreadsheet is available for completions."
2343 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2345 (barf-if-buffer-read-only)
2346 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2347 ses--symbolic-formulas))
2350 (if (string= newval "")
2351 nil ; Don't create zero-length symbols!
2352 (list 'quote (intern newval))))))
2353 (when (ses-edit-cell row col symb)
2354 (ses-command-hook) ; Update cell widths before movement.
2355 (dolist (x ses-after-entry-functions)
2358 (defun ses-clear-cell-forward (count)
2359 "Delete formula and printer for current cell and then move to next cell.
2360 With prefix, deletes several cells."
2363 (1value (ses-clear-cell-backward (- count)))
2368 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2369 (or rowcol (signal 'end-of-buffer nil))
2370 (ses-clear-cell (car rowcol) (cdr rowcol)))
2373 (defun ses-clear-cell-backward (count)
2374 "Move to previous cell and then delete it. With prefix, deletes several
2378 (1value (ses-clear-cell-forward (- count)))
2379 (ses-check-curcell 'end)
2382 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
2384 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2385 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2388 ;;----------------------------------------------------------------------------
2389 ;; Input of cell-printer functions
2390 ;;----------------------------------------------------------------------------
2392 (defun ses-read-printer (prompt default)
2393 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
2394 PROMPT should end with \": \". Result is t if operation was canceled."
2395 (barf-if-buffer-read-only)
2398 (setq prompt (format "%s [currently %S]: "
2399 (substring prompt 0 -2)
2401 (let ((new (read-from-minibuffer prompt
2402 nil ; Initial contents.
2404 t ; Evaluate the result.
2405 'ses-read-printer-history
2406 (prin1-to-string default))))
2407 (if (equal new default)
2408 ;; User changed mind, decided not to change printer.
2410 (ses-printer-validate new)
2413 (stringp (car-safe new))
2414 (ses-warn-unsafe new 'unsafep-function)
2418 (defun ses-read-cell-printer (newval)
2419 "Set the printer function for the current cell or range.
2421 A printer function is either a string (a format control-string with one
2422 %-sequence -- result from format will be right-justified), or a list of one
2423 string (result from format will be left-justified), or a lambda-expression of
2424 one argument, or a symbol that names a function of one argument. In the
2425 latter two cases, the function's result should be either a string (will be
2426 right-justified) or a list of one string (will be left-justified)."
2430 (ses-check-curcell 'range)
2431 ;;Default is none if not all cells in range have same printer
2432 (catch 'ses-read-cell-printer
2433 (ses-dorange ses--curcell
2434 (setq x (ses-cell-printer row col))
2435 (if (eq (car-safe x) 'ses-safe-printer)
2439 (unless (equal default x)
2440 ;;Range contains differing printer functions
2442 (throw 'ses-read-cell-printer t)))))
2443 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2445 (unless (eq newval t)
2447 (ses-dorange ses--curcell
2448 (ses-set-cell row col 'printer newval)
2449 (ses-print-cell row col))))
2451 (defun ses-read-column-printer (col newval)
2452 "Set the printer function for the current column.
2453 See `ses-read-cell-printer' for input forms."
2455 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2457 (list col (ses-read-printer (format "Column %s printer: "
2458 (ses-column-letter col))
2459 (ses-col-printer col)))))
2461 (unless (eq newval t)
2463 (ses-set-parameter 'ses--col-printers newval col)
2465 (dotimes (row ses--numrows)
2466 (ses-print-cell row col)))))
2468 (defun ses-read-default-printer (newval)
2469 "Set the default printer function for cells that have no other.
2470 See `ses-read-cell-printer' for input forms."
2472 (list (ses-read-printer "Default printer: " ses--default-printer)))
2473 (unless (eq newval t)
2475 (ses-set-parameter 'ses--default-printer newval)
2476 (ses-reprint-all t)))
2479 ;;----------------------------------------------------------------------------
2480 ;; Spreadsheet size adjustments
2481 ;;----------------------------------------------------------------------------
2483 (defun ses-insert-row (count)
2484 "Insert a new row before the current one.
2485 With prefix, insert COUNT rows before current one."
2487 (ses-check-curcell 'end)
2488 (or (> count 0) (signal 'args-out-of-range nil))
2490 (let ((inhibit-quit t)
2491 (inhibit-read-only t)
2492 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2494 ;;Create a new set of cell-variables
2495 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2496 0 (1- ses--numcols))
2497 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2499 (ses-goto-print row 0)
2500 (dotimes-with-progress-reporter (x count) "Inserting row..."
2501 ;;Create a row of empty cells. The `symbol' fields will be set by
2502 ;;the call to ses-relocate-all.
2503 (setq newrow (make-vector ses--numcols nil))
2504 (dotimes (col ses--numcols)
2505 (aset newrow col (ses-make-cell)))
2506 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2507 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2508 (insert ses--blank-line))
2509 ;;Insert empty lines in cell data area (will be replaced by
2511 (ses-goto-data row 0)
2512 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2513 (ses-relocate-all row 0 count 0)
2514 ;;If any cell printers insert constant text, insert that text
2516 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2517 (global (ses-call-printer ses--default-printer)))
2518 (if (or (> (length cols) 0) (> (length global) 0))
2520 (dotimes (col ses--numcols)
2521 ;;These cells are always nil, only constant formatting printed
2522 (1value (ses-print-cell (+ x row) col))))))
2523 (when (> ses--header-row row)
2524 ;;Inserting before header
2525 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2526 (ses-reset-header-string)))
2527 ;;Reconstruct text attributes
2530 (push '(apply ses-widen) buffer-undo-list)
2531 ;;Return to current cell
2533 (ses-jump-safe ses--curcell)
2534 (ses-goto-print (1- ses--numrows) 0)))
2536 (defun ses-delete-row (count)
2537 "Delete the current row.
2538 With prefix, deletes COUNT rows starting from the current one."
2541 (or (> count 0) (signal 'args-out-of-range nil))
2542 (let ((inhibit-quit t)
2543 (inhibit-read-only t)
2544 (row (car (ses-sym-rowcol ses--curcell))))
2545 (setq count (min count (- ses--numrows row)))
2547 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2548 ;;Delete lines from print area
2549 (ses-goto-print row 0)
2550 (ses-delete-line count)
2551 ;;Delete lines from cell data area
2552 (ses-goto-data row 0)
2553 (ses-delete-line (* count (1+ ses--numcols)))
2554 ;;Relocate variables and formulas
2555 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2556 (ses-relocate-all row 0 (- count) 0)
2557 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2558 0 (1- ses--numcols))
2559 (when (> ses--header-row row)
2560 (if (<= ses--header-row (+ row count))
2561 ;;Deleting the header row
2562 (ses-set-parameter 'ses--header-row 0)
2563 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2564 (ses-reset-header-string)))
2565 ;;Reconstruct attributes
2568 (push '(apply ses-widen) buffer-undo-list)
2569 (ses-jump-safe ses--curcell))
2571 (defun ses-insert-column (count &optional col width printer)
2572 "Insert a new column before COL (default is the current one).
2573 With prefix, insert COUNT columns before current one.
2574 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2575 \(otherwise they're taken from the current column)."
2578 (or (> count 0) (signal 'args-out-of-range nil))
2580 (setq col (cdr (ses-sym-rowcol ses--curcell))
2581 width (ses-col-width col)
2582 printer (ses-col-printer col)))
2584 (let ((inhibit-quit t)
2585 (inhibit-read-only t)
2586 (widths ses--col-widths)
2587 (printers ses--col-printers)
2589 ;;Create a new set of cell-variables
2590 (ses-create-cell-variable-range 0 (1- ses--numrows)
2591 ses--numcols (+ ses--numcols count -1))
2592 ;;Insert each column.
2593 (dotimes-with-progress-reporter (x count) "Inserting column..."
2594 ;;Create a column of empty cells. The `symbol' fields will be set by
2595 ;;the call to ses-relocate-all.
2596 (ses-adjust-print-width col (1+ width))
2597 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2598 (dotimes (row ses--numrows)
2599 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2600 ;;Inserting in the middle of a spill-over
2602 (ses-aset-with-undo ses--cells row
2603 (ses-vector-insert (aref ses--cells row)
2604 col (ses-make-cell)))
2605 ;;Insert empty lines in cell data area (will be replaced by
2607 (ses-goto-data row col)
2609 ;; Insert column width and printer.
2610 (setq widths (ses-vector-insert widths col width)
2611 printers (ses-vector-insert printers col printer)))
2612 (ses-set-parameter 'ses--col-widths widths)
2613 (ses-set-parameter 'ses--col-printers printers)
2614 (ses-reset-header-string)
2615 (ses-relocate-all 0 col 0 count)
2618 (when (or (> (length (ses-call-printer printer)) 0)
2619 (> (length (ses-call-printer ses--default-printer)) 0))
2620 ;; Either column printer or global printer inserts some constant text.
2621 ;; Reprint the new columns to insert that text.
2622 (dotimes (x ses--numrows)
2624 ;; Always nil here --- this is a blank column.
2625 (1value (ses-print-cell-new-width x (+ y col))))))
2627 (ses-jump-safe ses--curcell))
2629 (defun ses-delete-column (count)
2630 "Delete the current column.
2631 With prefix, deletes COUNT columns starting from the current one."
2634 (or (> count 0) (signal 'args-out-of-range nil))
2635 (let ((inhibit-quit t)
2636 (inhibit-read-only t)
2637 (rowcol (ses-sym-rowcol ses--curcell))
2639 col origrow has-skip)
2640 (setq origrow (car rowcol)
2642 count (min count (- ses--numcols col)))
2643 (if (= count ses--numcols)
2644 (error "Can't delete all columns!"))
2645 ;;Determine width of column(s) being deleted
2647 (setq width (+ width (ses-col-width (+ col x)) 1)))
2649 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2650 (ses-adjust-print-width col (- width))
2651 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2652 ;;Delete lines from cell data area
2653 (ses-goto-data row col)
2654 (ses-delete-line count)
2655 ;;Delete cells. Check if deletion area begins or ends with a skip.
2656 (if (or (eq (ses-cell-value row col) '*skip*)
2657 (and (< col ses--numcols)
2658 (eq (ses-cell-value row (+ col count)) '*skip*)))
2660 (ses-aset-with-undo ses--cells row
2661 (ses-vector-delete (aref ses--cells row) col count)))
2663 (ses-set-parameter 'ses--col-widths
2664 (ses-vector-delete ses--col-widths col count))
2665 (ses-set-parameter 'ses--col-printers
2666 (ses-vector-delete ses--col-printers col count))
2667 (ses-reset-header-string)
2668 ;;Relocate variables and formulas
2669 (ses-relocate-all 0 col 0 (- count))
2670 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2671 ses--numcols (+ ses--numcols count -1))
2675 (if (>= col ses--numcols)
2676 (setq col (1- col)))
2677 (ses-goto-print origrow col)))
2679 (defun ses-forward-or-insert (&optional count)
2680 "Move to next cell in row, or inserts a new cell if already in last one, or
2681 inserts a new row if at bottom of print area. Repeat COUNT times."
2683 (ses-check-curcell 'end)
2684 (setq deactivate-mark t) ; Doesn't combine well with ranges.
2687 (if (not ses--curcell)
2688 (progn ; At bottom of print area.
2689 (barf-if-buffer-read-only)
2691 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2693 (char-before (next-single-property-change (point)
2695 ;; We're already in last nonskipped cell on line. Need to create a
2697 (barf-if-buffer-read-only)
2698 (ses-insert-column (- count x)
2701 (ses-col-printer col)))))
2704 (defun ses-append-row-jump-first-column ()
2705 "Insert a new row after current one and jump to its first column."
2709 (beginning-of-line 2)
2713 (defun ses-set-column-width (col newwidth)
2714 "Set the width of the current column."
2716 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2717 (barf-if-buffer-read-only)
2719 (if current-prefix-arg
2720 (prefix-numeric-value current-prefix-arg)
2721 (read-from-minibuffer (format "Column %s width [currently %d]: "
2722 (ses-column-letter col)
2723 (ses-col-width col))
2724 nil ; No initial contents.
2725 nil ; No override keymap.
2726 t ; Convert to Lisp object.
2729 (ses-col-width col))))))) ; Default value.
2731 (error "Invalid column width"))
2733 (ses-reset-header-string)
2735 (let ((inhibit-quit t))
2736 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2737 (ses-set-parameter 'ses--col-widths newwidth col))
2738 (dotimes (row ses--numrows)
2739 (ses-print-cell-new-width row col))))
2742 ;;----------------------------------------------------------------------------
2743 ;; Cut and paste, import and export
2744 ;;----------------------------------------------------------------------------
2746 (defun ses--advice-copy-region-as-kill (crak-fun beg end &rest args)
2747 ;; FIXME: Why doesn't it make sense to copy read-only or
2748 ;; intangible attributes? They're removed upon yank!
2749 "It doesn't make sense to copy read-only or intangible attributes into the
2750 kill ring. It probably doesn't make sense to copy keymap properties.
2751 We'll assume copying front-sticky properties doesn't make sense, either.
2753 This advice also includes some SES-specific code because otherwise it's too
2754 hard to override how mouse-1 works."
2759 (if (not (and (derived-mode-p 'ses-mode)
2760 (eq (get-text-property beg 'read-only) 'ses)
2761 (eq (get-text-property (1- end) 'read-only) 'ses)))
2762 (apply crak-fun beg end args) ; Normal copy-region-as-kill.
2763 (kill-new (ses-copy-region beg end))
2764 (if transient-mark-mode
2765 (setq deactivate-mark t))
2767 (advice-add 'copy-region-as-kill :around #'ses--advice-copy-region-as-kill)
2769 (defun ses-copy-region (beg end)
2770 "Treat the region as rectangular. Convert the intangible attributes to
2771 SES attributes recording the contents of the cell as of the time of copying."
2772 (when (= end ses--data-marker)
2773 ;;Avoid overflow situation
2774 (setq end (1- ses--data-marker)))
2775 (let* ((inhibit-point-motion-hooks t)
2776 (x (mapconcat 'ses-copy-region-helper
2777 (extract-rectangle beg (1- end)) "\n")))
2778 (remove-text-properties 0 (length x)
2786 (defun ses-copy-region-helper (line)
2787 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2788 external form by attaching to each print cell a 'ses attribute that records
2789 the corresponding data cell."
2790 (or (> (length line) 1)
2791 (error "Empty range"))
2792 (let ((inhibit-read-only t)
2794 mycell next sym rowcol)
2796 (setq sym (get-text-property pos 'intangible line)
2797 next (next-single-property-change pos 'intangible line)
2798 rowcol (ses-sym-rowcol sym)
2799 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2800 (put-text-property pos (or next (length line))
2802 (list (ses-cell-symbol mycell)
2803 (ses-cell-formula mycell)
2804 (ses-cell-printer mycell))
2809 (defun ses-kill-override (beg end)
2810 "Generic override for any commands that kill text.
2811 We clear the killed cells instead of deleting them."
2813 (ses-check-curcell 'needrange)
2814 ;; For some reason, the text-read-only error is not caught by `delete-region',
2815 ;; so we have to use subterfuge.
2816 (let ((buffer-read-only t))
2817 (1value (condition-case nil
2818 (noreturn (funcall (lookup-key (current-global-map)
2819 (this-command-keys))
2821 (buffer-read-only nil)))) ; The expected error.
2822 ;; Because the buffer was marked read-only, the kill command turned itself
2823 ;; into a copy. Now we clear the cells or signal the error. First we check
2824 ;; whether the buffer really is read-only.
2825 (barf-if-buffer-read-only)
2827 (ses-dorange ses--curcell
2828 (ses-clear-cell row col))
2829 (ses-jump (car ses--curcell)))
2831 (defun ses--advice-yank (yank-fun &optional arg &rest args)
2832 "In SES mode, the yanked text is inserted as cells.
2834 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2835 SES buffer), the formulas and print functions are restored for the cells. If
2836 the text contains tabs, this is an insertion of tab-separated formulas.
2837 Otherwise the text is inserted as the formula for the current cell.
2839 When inserting cells, the formulas are usually relocated to keep the same
2840 relative references to neighboring cells. This is best if the formulas
2841 generally refer to other cells within the yanked text. You can use the C-u
2842 prefix to specify insertion without relocation, which is best when the
2843 formulas refer to cells outside the yanked text.
2845 When inserting formulas, the text is treated as a string constant if it doesn't
2846 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2847 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2849 (if (not (and (derived-mode-p 'ses-mode)
2850 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2851 (apply yank-fun arg args) ; Normal non-SES yank.
2852 (ses-check-curcell 'end)
2854 (let ((text (current-kill (cond
2858 (or (ses-yank-cells text arg)
2859 (ses-yank-tsf text arg)
2860 (ses-yank-one (ses-yank-resize 1 1)
2863 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2864 ;; Just one cell --- delete final tab or newline.
2868 (exchange-point-and-mark))))
2869 (advice-add 'yank :around #'ses--advice-yank)
2871 (defun ses-yank-pop (arg)
2872 "Replace just-yanked stretch of killed text with a different stretch.
2873 This command is allowed only immediately after a `yank' or a `yank-pop',
2874 when the region contains a stretch of reinserted previously-killed text.
2875 We replace it with a different stretch of killed text.
2876 Unlike standard `yank-pop', this function uses `undo' to delete the
2877 previous insertion."
2879 (or (eq last-command 'yank)
2880 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2882 (noreturn (error "Previous command was not a yank")))
2885 (yank (1+ (or arg 1)))
2886 (setq this-command 'yank))
2888 (defun ses-yank-cells (text arg)
2889 "If the TEXT has a proper set of 'ses attributes, insert the text as
2890 cells, else return nil. The cells are reprinted--the supplied text is
2891 ignored because the column widths, default printer, etc. at yank time might
2892 be different from those at kill-time. ARG is a list to indicate that
2893 formulas are to be inserted without relocation."
2894 (let ((first (get-text-property 0 'ses text))
2895 (last (get-text-property (1- (length text)) 'ses text)))
2896 (when (and first last) ;;Otherwise not proper set of attributes
2897 (setq first (ses-sym-rowcol (car first))
2898 last (ses-sym-rowcol (car last)))
2899 (let* ((needrows (- (car last) (car first) -1))
2900 (needcols (- (cdr last) (cdr first) -1))
2901 (rowcol (ses-yank-resize needrows needcols))
2902 (rowincr (- (car rowcol) (car first)))
2903 (colincr (- (cdr rowcol) (cdr first)))
2906 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2907 (setq myrow (+ row (car rowcol)))
2908 (dotimes (col needcols)
2909 (setq mycol (+ col (cdr rowcol))
2910 last (get-text-property pos 'ses text)
2911 pos (next-single-property-change pos 'ses text)
2912 x (ses-sym-rowcol (car last)))
2914 ;; Newline --- all remaining cells on row are skipped.
2915 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2916 last (list nil nil nil)
2918 (if (/= (car x) (- myrow rowincr))
2919 (error "Cell row error"))
2920 (if (< (- mycol colincr) (cdr x))
2921 ;; Some columns were skipped.
2922 (let ((oldcol mycol))
2923 (while (< (- mycol colincr) (cdr x))
2924 (ses-clear-cell myrow mycol)
2927 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
2928 (when (car last) ; Skip this for *skip* cells.
2929 (setq x (nth 2 last))
2930 (unless (equal x (ses-cell-printer myrow mycol))
2933 (eq (car-safe x) 'ses-safe-printer)
2934 (setq x `(ses-safe-printer ,x)))
2935 (ses-set-cell myrow mycol 'printer x))
2936 (setq x (cadr last))
2938 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2940 (eq (car-safe x) 'ses-safe-formula)
2941 (setq x `(ses-safe-formula ,x)))
2942 (ses-cell-set-formula myrow mycol x)))
2944 (if (get-text-property pos 'ses text)
2945 (error "Missing newline between rows"))
2946 (setq pos (next-single-property-change pos 'ses text))))
2949 (defun ses-yank-one (rowcol text from to arg)
2950 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2951 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2952 (let ((val (condition-case nil
2953 (read-from-string text from to)
2954 (error (cons nil from)))))
2956 ((< (cdr val) (or to (length text)))
2957 ;; Invalid sexp --- leave it as a string.
2958 (setq val (substring text from to)))
2959 ((and (car val) (symbolp (car val)))
2961 (setq val (list 'quote (car val))) ; Keep symbol.
2962 (setq val (substring text from to)))) ; Treat symbol as text.
2964 (setq val (car val))))
2965 (let ((row (car rowcol))
2968 (setq val `(ses-safe-formula ,val)))
2969 (ses-cell-set-formula row col val))))
2971 (defun ses-yank-tsf (text arg)
2972 "If TEXT contains tabs and/or newlines, treat the tabs as
2973 column-separators and the newlines as row-separators and insert the text as
2974 cell formulas--else return nil. Treat plain symbols as strings unless ARG
2975 is a list. Ignore a final newline."
2976 (if (or (not (string-match "[\t\n]" text))
2977 (= (match-end 0) (length text)))
2980 (if (/= (aref text (1- (length text))) ?\n)
2981 (setq text (concat text "\n")))
2987 ;;Find all the tabs and newlines
2988 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
2990 (setq cols (1+ cols))
2991 (when (eq (aref text pos) ?\n)
2993 (setq needcols cols)
2994 (or (= needcols cols)
2995 (error "Inconsistent row lengths")))
2997 needrows (1+ needrows))))
2998 ;;Insert the formulas
2999 (setq rowcol (ses-yank-resize needrows needcols))
3000 (dotimes (row needrows)
3001 (dotimes (col needcols)
3002 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
3003 (+ (cdr rowcol) needcols (- col) -1))
3004 text (1+ (cadr spots)) (car spots) arg)
3005 (setq spots (cdr spots))))
3006 (ses-goto-print (+ (car rowcol) needrows -1)
3007 (+ (cdr rowcol) needcols -1))
3010 (defun ses-yank-resize (needrows needcols)
3011 "If this yank will require inserting rows and/or columns, ask for
3012 confirmation and then insert them. Result is (row,col) for top left of yank
3013 spot, or error signal if user requests cancel."
3015 (let ((rowcol (if ses--curcell
3016 (ses-sym-rowcol ses--curcell)
3017 (cons ses--numrows 0)))
3019 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
3020 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
3021 rowbool (> needrows 0)
3022 colbool (> needcols 0))
3023 (when (or rowbool colbool)
3024 ;;Need to insert. Get confirm
3025 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
3026 (if rowbool (format "%d rows" needrows) "")
3027 (if (and rowbool colbool) " and " "")
3028 (if colbool (format "%d columns" needcols) "")))
3033 (ses-goto-print ses--numrows 0)
3034 (ses-insert-row needrows))))
3036 (ses-insert-column needcols
3038 (ses-col-width (1- ses--numcols))
3039 (ses-col-printer (1- ses--numcols)))))
3042 (defun ses-export-tsv (_beg _end)
3043 "Export values from the current range, with tabs between columns and
3044 newlines between rows. Result is placed in kill ring."
3046 (ses-export-tab nil))
3048 (defun ses-export-tsf (_beg _end)
3049 "Export formulas from the current range, with tabs between columns and
3050 newlines between rows. Result is placed in kill ring."
3054 (defun ses-export-tab (want-formulas)
3055 "Export the current range with tabs between columns and newlines between rows.
3056 Result is placed in kill ring. The export is values unless WANT-FORMULAS
3057 is non-nil. Newlines and tabs in the export text are escaped."
3058 (ses-check-curcell 'needrange)
3059 (let ((print-escape-newlines t)
3061 (ses-dorange ses--curcell
3062 (setq item (if want-formulas
3063 (ses-cell-formula row col)
3064 (ses-cell-value row col)))
3065 (if (eq (car-safe item) 'ses-safe-formula)
3066 ;;Hide our deferred safety-check marker
3067 (setq item (cadr item)))
3068 (if (or (not item) (eq item '*skip*))
3070 (when (eq (car-safe item) 'quote)
3072 (setq item (cadr item)))
3073 (setq item (prin1-to-string item t))
3074 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
3080 (push "\n" result))))
3081 (setq result (apply 'concat (nreverse result)))
3085 ;;----------------------------------------------------------------------------
3086 ;; Other user commands
3087 ;;----------------------------------------------------------------------------
3089 (defun ses-unset-header-row ()
3090 "Select the default header row."
3092 (ses-set-header-row 0))
3094 (defun ses-set-header-row (row)
3095 "Set the ROW to display in the header-line.
3096 With a numerical prefix arg, use that row.
3097 With no prefix arg, use the current row.
3098 With a \\[universal-argument] prefix arg, prompt the user.
3099 The top row is row 1. Selecting row 0 displays the default header row."
3101 (list (if (numberp current-prefix-arg) current-prefix-arg
3102 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3103 (if current-prefix-arg
3104 (read-number "Header row: " currow)
3106 (if (or (< row 0) (> row ses--numrows))
3107 (error "Invalid header-row"))
3109 (let ((oldval ses--header-row))
3110 (let (buffer-undo-list)
3111 (ses-set-parameter 'ses--header-row row))
3112 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
3113 (ses-reset-header-string))
3115 (defun ses-mark-row ()
3116 "Mark the entirety of current row as a range."
3118 (ses-check-curcell 'range)
3119 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
3121 (ses-goto-print (1+ row) 0)
3122 (push-mark (point) nil t)
3123 (ses-goto-print row 0)))
3125 (defun ses-mark-column ()
3126 "Mark the entirety of current column as a range."
3128 (ses-check-curcell 'range)
3129 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
3132 (ses-goto-print (1- ses--numrows) col)
3134 (push-mark (point) nil t)
3135 (while (eq '*skip* (ses-cell-value row col))
3136 ;;Skip over initial cells in column that can't be selected
3137 (setq row (1+ row)))
3138 (ses-goto-print row col)))
3140 (defun ses-end-of-line ()
3141 "Move point to last cell on line."
3143 (ses-check-curcell 'end 'range)
3144 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3146 (let ((col (1- ses--numcols))
3148 (if (symbolp ses--curcell)
3150 (setq row (car (ses-sym-rowcol ses--curcell)))
3151 ;; Range --- use whichever end of the range the point is at.
3152 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
3154 (cdr ses--curcell))))
3155 ;; If range already includes the last cell in a row, point is actually
3156 ;; in the following row.
3157 (if (<= (cdr rowcol) (1- col))
3158 (setq row (car rowcol))
3159 (setq row (1+ (car rowcol)))
3160 (if (= row ses--numrows)
3161 ;;Already at end - can't go anywhere
3163 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
3164 (while (eq (ses-cell-value row col) '*skip*)
3165 ;; Back to beginning of multi-column cell.
3166 (setq col (1- col)))
3167 (ses-goto-print row col)))))
3169 (defun ses-renarrow-buffer ()
3170 "Narrow the buffer so only the print area is visible.
3171 Use after \\[widen]."
3173 (setq ses--deferred-narrow t))
3175 (defun ses-sort-column (sorter &optional reverse)
3176 "Sort the range by a specified column.
3177 With prefix, sorts in REVERSE order."
3178 (interactive "*sSort column: \nP")
3179 (ses-check-curcell 'needrange)
3180 (let ((min (ses-sym-rowcol (car ses--curcell)))
3181 (max (ses-sym-rowcol (cdr ses--curcell))))
3182 (let ((minrow (car min))
3187 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3188 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3189 (error "Invalid sort column"))
3190 ;;Get key columns and sort them
3191 (dotimes (x (- maxrow minrow -1))
3192 (ses-goto-print (+ minrow x) sorter)
3193 (setq end (next-single-property-change (point) 'intangible))
3194 (push (cons (buffer-substring-no-properties (point) end)
3197 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3198 ;;Extract the lines in reverse sorted order
3200 (setq keys (nreverse keys)))
3202 (ses-goto-print (cdr x) (1+ maxcol))
3204 (ses-goto-print (cdr x) mincol)
3205 (push (ses-copy-region (point) end) extracts))
3207 ;;Paste the lines sequentially
3208 (dotimes (x (- maxrow minrow -1))
3209 (ses-goto-print (+ minrow x) mincol)
3211 (ses-yank-cells (pop extracts) nil)))))
3213 (defun ses-sort-column-click (event reverse)
3214 "Mouse version of `ses-sort-column'."
3215 (interactive "*e\nP")
3216 (setq event (event-end event))
3217 (select-window (posn-window event))
3218 (setq event (car (posn-col-row event))) ; Click column.
3220 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3221 (setq event (- event (ses-col-width col) 1)
3223 (if (>= col ses--numcols)
3225 (ses-sort-column (ses-column-letter col) reverse))))
3227 (defun ses-insert-range ()
3228 "Insert into minibuffer the list of cells currently highlighted in the
3232 (with-current-buffer (window-buffer minibuffer-scroll-window)
3233 (ses-command-hook) ; For ses-coverage.
3234 (ses-check-curcell 'needrange)
3235 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3236 ,(cdr ses--curcell))))))
3237 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3239 (defun ses-insert-ses-range ()
3240 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
3241 highlighted range in the spreadsheet."
3244 (with-current-buffer (window-buffer minibuffer-scroll-window)
3245 (ses-command-hook) ; For ses-coverage.
3246 (ses-check-curcell 'needrange)
3247 (setq x (format "(ses-range %S %S)"
3249 (cdr ses--curcell))))
3252 (defun ses-insert-range-click (event)
3253 "Mouse version of `ses-insert-range'."
3255 (mouse-set-point event)
3258 (defun ses-insert-ses-range-click (event)
3259 "Mouse version of `ses-insert-ses-range'."
3261 (mouse-set-point event)
3262 (ses-insert-ses-range))
3264 (defun ses-replace-name-in-formula (formula old-name new-name)
3265 (let ((new-formula formula))
3266 (unless (and (consp formula)
3267 (eq (car-safe formula) 'quote))
3269 (let ((elt (car-safe formula)))
3272 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3274 (eq (car-safe formula) old-name))
3275 (setcar formula new-name))))
3276 (setq formula (cdr formula))))
3279 (defun ses-rename-cell (new-name &optional cell)
3280 "Rename current cell."
3281 (interactive "*SEnter new name: ")
3283 (and (local-variable-p new-name)
3284 (ses-is-cell-sym-p new-name)
3285 (error "Already a cell name"))
3286 (and (boundp new-name)
3287 (null (yes-or-no-p (format "`%S' is already bound outside this buffer, continue? "
3289 (error "Already a bound cell name")))
3291 (sym (if (ses-cell-p cell)
3292 (ses-cell-symbol cell)
3297 (rowcol (ses-sym-rowcol sym))
3300 new-rowcol old-name)
3301 (setq cell (or cell (ses-get-cell row col))
3302 old-name (ses-cell-symbol cell)
3303 new-rowcol (ses-decode-cell-symbol (symbol-name new-name)))
3305 (if (equal new-rowcol rowcol)
3306 (put new-name 'ses-cell rowcol)
3307 (error "Not a valid name for this cell location"))
3308 (setq ses--named-cell-hashmap (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
3309 (put new-name 'ses-cell :ses-named)
3310 (puthash new-name rowcol ses--named-cell-hashmap))
3311 (push `(ses-rename-cell ,old-name ,cell) buffer-undo-list)
3312 ;; replace name by new name in formula of cells refering to renamed cell
3313 (dolist (ref (ses-cell-references cell))
3314 (let* ((x (ses-sym-rowcol ref))
3315 (xcell (ses-get-cell (car x) (cdr x))))
3316 (ses-cell-formula-aset xcell
3317 (ses-replace-name-in-formula
3318 (ses-cell-formula xcell)
3321 ;; replace name by new name in reference list of cells to which renamed cell refers to
3322 (dolist (ref (ses-formula-references (ses-cell-formula cell)))
3323 (let* ((x (ses-sym-rowcol ref))
3324 (xcell (ses-get-cell (car x) (cdr x))))
3325 (ses-cell-references-aset xcell
3326 (cons new-name (delq sym
3327 (ses-cell-references xcell))))))
3328 (push new-name ses--renamed-cell-symb-list)
3329 (set new-name (symbol-value sym))
3330 (aset cell 0 new-name)
3332 (and curcell (setq ses--curcell new-name))
3333 (let* ((pos (point))
3334 (inhibit-read-only t)
3335 (col (current-column))
3336 (end (save-excursion
3337 (move-to-column (1+ col))
3339 (+ pos (ses-col-width col) 1)
3341 (put-text-property pos end 'intangible new-name))
3343 (setq mode-line-process (list " cell "
3344 (symbol-name new-name)))
3345 (force-mode-line-update)))
3347 ;;----------------------------------------------------------------------------
3348 ;; Checking formulas for safety
3349 ;;----------------------------------------------------------------------------
3351 (defun ses-safe-printer (printer)
3352 "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
3353 (if (or (stringp printer)
3354 (stringp (car-safe printer))
3356 (ses-warn-unsafe printer 'unsafep-function))
3360 (defun ses-safe-formula (formula)
3361 "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
3362 (if (ses-warn-unsafe formula 'unsafep)
3364 `(ses-unsafe ',formula)))
3366 (defun ses-warn-unsafe (formula checker)
3367 "Apply CHECKER to FORMULA.
3368 If result is non-nil, asks user for confirmation about FORMULA,
3369 which might be unsafe. Returns t if formula is safe or user allows
3370 execution anyway. Always returns t if `safe-functions' is t."
3371 (if (eq safe-functions t)
3373 (setq checker (funcall checker formula))
3376 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3377 formula checker)))))
3380 ;;----------------------------------------------------------------------------
3381 ;; Standard formulas
3382 ;;----------------------------------------------------------------------------
3384 (defun ses--clean-! (&rest x)
3385 "Clean by `delq' list X from any occurrence of `nil' or `*skip*'."
3386 (delq nil (delq '*skip* x)))
3388 (defun ses--clean-_ (x y)
3389 "Clean list X by replacing by Y any occurrence of `nil' or `*skip*'.
3391 This will change X by making `setcar' on its cons cells."
3392 (let ((ret x) ret-elt)
3394 (setq ret-elt (car ret))
3395 (when (memq ret-elt '(nil *skip*))
3397 (setq ret (cdr ret))))
3400 (defmacro ses-range (from to &rest rest)
3401 "Expand to a list of cell-symbols for the range going from
3402 FROM up to TO. The range automatically expands to include any
3403 new row or column inserted into its middle. The SES library code
3404 specifically looks for the symbol `ses-range', so don't create an
3405 alias for this macro!
3407 By passing in REST some flags one can configure the way the range
3408 is read and how it is formatted.
3410 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3413 Readout direction is specified by a `>v', '`>^', `<v', `<^',
3414 `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3415 of such a flag, a default direction of `^<' is assumed. This
3416 way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3417 while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3419 If the range is one row, then `>' can be used as a shorthand to
3420 `>v' or `>^', and `<' to `<v' or `<^'.
3422 If the range is one column, then `v' can be used as a shorthand to
3423 `v>' or `v<', and `^' to `^>' or `v<'.
3425 A `!' flag will remove all cells whose value is nil or `*skip*'.
3427 A `_' flag will replace nil or `*skip*' by the value following
3428 the `_' flag. If the `_' flag is the last argument, then they are
3429 replaced by integer 0.
3431 A `*', `*1' or `*2' flag will vectorize the range in the sense of
3432 Calc. See info node `(Calc) Top'. Flag `*' will output either a
3433 vector or a matrix depending on the number of rows, `*1' will
3434 flatten the result to a one row vector, and `*2' will make a
3435 matrix whatever the number of rows.
3437 Warning: interaction with Calc is experimental and may produce
3438 confusing results if you are not aware of Calc data format.
3439 Use `math-format-value' as a printer for Calc objects."
3447 (ses-dorange (cons from to)
3448 (when (/= prev-row row)
3449 (push result-row result)
3450 (setq result-row nil))
3451 (push (ses-cell-symbol row col) result-row)
3452 (setq prev-row row))
3453 (push result-row result)
3455 (let ((x (pop rest)))
3457 (`>v (setq transpose nil reorient-x nil reorient-y nil))
3458 (`>^ (setq transpose nil reorient-x nil reorient-y t))
3459 (`<^ (setq transpose nil reorient-x t reorient-y t))
3460 (`<v (setq transpose nil reorient-x t reorient-y nil))
3461 (`v> (setq transpose t reorient-x nil reorient-y t))
3462 (`^> (setq transpose t reorient-x nil reorient-y nil))
3463 (`^< (setq transpose t reorient-x t reorient-y nil))
3464 (`v< (setq transpose t reorient-x t reorient-y t))
3465 ((or `* `*2 `*1) (setq vectorize x))
3466 (`! (setq clean 'ses--clean-!))
3467 (`_ (setq clean `(lambda (&rest x)
3468 (ses--clean-_ x ,(if rest (pop rest) 0)))))
3471 ; shorthands one row
3472 ((and (null (cddr result)) (memq x '(> <)))
3473 (push (intern (concat (symbol-name x) "v")) rest))
3474 ; shorthands one col
3475 ((and (null (cdar result)) (memq x '(v ^)))
3476 (push (intern (concat (symbol-name x) ">")) rest))
3477 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3479 (setcdr (last result 2) nil)
3480 (setq result (cdr (nreverse result))))
3482 (setq result (mapcar 'nreverse result)))
3484 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3487 (dolist (elt (pop result))
3488 (setcar iter (cons elt (car iter)))
3489 (setq iter (cdr iter))))
3492 (cl-flet ((vectorize-*1
3494 (cons clean (cons (quote 'vec) (apply 'append result))))
3497 (cons clean (cons (quote 'vec)
3499 (cons clean (cons (quote 'vec) x)))
3502 (`nil (cons clean (apply 'append result)))
3503 (`*1 (vectorize-*1 clean result))
3504 (`*2 (vectorize-*2 clean result))
3505 (`* (funcall (if (cdr result)
3510 (defun ses-delete-blanks (&rest args)
3511 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3514 (unless (memq cur '(nil *skip*))
3518 (defun ses+ (&rest args)
3519 "Compute the sum of the arguments, ignoring blanks."
3520 (apply '+ (apply 'ses-delete-blanks args)))
3522 (defun ses-average (list)
3523 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3524 are ignored. Result is always floating-point, even if all args are integers."
3525 (setq list (apply 'ses-delete-blanks list))
3526 (/ (float (apply '+ list)) (length list)))
3528 (defmacro ses-select (fromrange test torange)
3529 "Select cells in FROMRANGE that are `equal' to TEST.
3530 For each match, return the corresponding cell from TORANGE.
3531 The ranges are macroexpanded but not evaluated so they should be
3532 either (ses-range BEG END) or (list ...). The TEST is evaluated."
3533 (setq fromrange (cdr (macroexpand fromrange))
3534 torange (cdr (macroexpand torange))
3536 (or (= (length fromrange) (length torange))
3537 (error "ses-select: Ranges not same length"))
3539 (dolist (x fromrange)
3540 (if (equal test (symbol-value x))
3541 (push (car torange) result))
3542 (setq torange (cdr torange)))
3543 (cons 'list result)))
3545 ;;All standard formulas are safe
3546 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3548 (put x 'side-effect-free t))
3551 ;;----------------------------------------------------------------------------
3552 ;; Standard print functions
3553 ;;----------------------------------------------------------------------------
3555 ;; These functions use the variables 'row' and 'col' that are dynamically bound
3556 ;; by ses-print-cell. We define these variables at compile-time to make the
3561 (defun ses-center (value &optional span fill)
3562 "Print VALUE, centered within column.
3563 FILL is the fill character for centering (default = space).
3564 SPAN indicates how many additional rightward columns to include
3565 in width (default = 0)."
3566 (let ((printer (or (ses-col-printer col) ses--default-printer))
3567 (width (ses-col-width col))
3569 (or fill (setq fill ?\s))
3570 (or span (setq span 0))
3571 (setq value (ses-call-printer printer value))
3573 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
3574 ;; Set column width.
3575 (setq width (- width (string-width value)))
3577 value ; Too large for field, anyway.
3578 (setq half (make-string (/ width 2) fill))
3579 (concat half value half
3580 (if (> (% width 2) 0) (char-to-string fill))))))
3582 (defun ses-center-span (value &optional fill)
3583 "Print VALUE, centered within the span that starts in the current column
3584 and continues until the next nonblank column.
3585 FILL specifies the fill character (default = space)."
3586 (let ((end (1+ col)))
3587 (while (and (< end ses--numcols)
3588 (memq (ses-cell-value row end) '(nil *skip*)))
3589 (setq end (1+ end)))
3590 (ses-center value (- end col 1) fill)))
3592 (defun ses-dashfill (value &optional span)
3593 "Print VALUE centered using dashes.
3594 SPAN indicates how many rightward columns to include in width (default = 0)."
3595 (ses-center value span ?-))
3597 (defun ses-dashfill-span (value)
3598 "Print VALUE, centered using dashes within the span that starts in the
3599 current column and continues until the next nonblank column."
3600 (ses-center-span value ?-))
3602 (defun ses-tildefill-span (value)
3603 "Print VALUE, centered using tildes within the span that starts in the
3604 current column and continues until the next nonblank column."
3605 (ses-center-span value ?~))
3607 (defun ses-unsafe (_value)
3608 "Substitute for an unsafe formula or printer."
3609 (error "Unsafe formula or printer"))
3611 ;;All standard printers are safe, including ses-unsafe!
3612 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3613 (put x 'side-effect-free t))
3615 (defun ses-unload-function ()
3616 "Unload the Simple Emacs Spreadsheet."
3617 (advice-remove 'yank #'ses--advice-yank)
3618 (advice-remove 'copy-region-as-kill #'ses--advice-copy-region-as-kill)
3619 ;; Continue standard unloading.
3624 ;;; ses.el ends here