1 ;;; ses.el -- Simple Emacs Spreadsheet -*- coding: utf-8 -*-
3 ;; Copyright (C) 2002-2012 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."
73 (defcustom ses-initial-size
'(1 .
1)
74 "Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
76 :type
'(cons (integer :tag
"numrows") (integer :tag
"numcols")))
78 (defcustom ses-initial-column-width
7
79 "Initial width of columns in a new spreadsheet."
81 :type
'(integer :match
(lambda (widget value
) (> value
0))))
83 (defcustom ses-initial-default-printer
"%.7g"
84 "Initial default printer for a new spreadsheet."
87 (list :tag
"Parenthesized string" string
)
90 (defcustom ses-after-entry-functions
'(forward-char)
91 "Things to do after entering a value into a cell.
92 An abnormal hook that usually runs a cursor-movement function.
93 Each function is called with ARG=1."
96 :options
'(forward-char backward-char next-line previous-line
))
98 (defcustom ses-mode-hook nil
99 "Hook functions to be run upon entering SES mode."
104 ;;----------------------------------------------------------------------------
105 ;; Global variables and constants
106 ;;----------------------------------------------------------------------------
108 (defvar ses-read-cell-history nil
109 "List of formulas that have been typed in.")
111 (defvar ses-read-printer-history nil
112 "List of printer functions that have been typed in.")
114 (easy-menu-define ses-header-line-menu nil
115 "Context menu when mouse-3 is used on the header-line in an SES buffer."
117 ["Set current row" ses-set-header-row t
]
118 ["Unset row" ses-unset-header-row
(> ses--header-row
0)]))
120 (defconst ses-mode-map
121 (let ((keys `("\C-c\M-\C-l" ses-reconstruct-all
122 "\C-c\C-l" ses-recalculate-all
123 "\C-c\C-n" ses-renarrow-buffer
124 "\C-c\C-c" ses-recalculate-cell
125 "\C-c\M-\C-s" ses-sort-column
126 "\C-c\M-\C-h" ses-set-header-row
127 "\C-c\C-t" ses-truncate-cell
129 "\C-c\C-p" ses-read-default-printer
130 "\M-\C-l" ses-reprint-all
131 [?\S-\C-l
] ses-reprint-all
132 [header-line down-mouse-3
] ,ses-header-line-menu
133 [header-line mouse-2
] ses-sort-column-click
))
134 (newmap (make-sparse-keymap)))
136 (define-key (1value newmap
) (car keys
) (cadr keys
))
137 (setq keys
(cddr keys
)))
139 "Local keymap for Simple Emacs Spreadsheet.")
141 (easy-menu-define ses-menu ses-mode-map
142 "Menu bar menu for SES."
144 ["Insert row" ses-insert-row
(ses-in-print-area)]
145 ["Delete row" ses-delete-row
(ses-in-print-area)]
146 ["Insert column" ses-insert-column
(ses-in-print-area)]
147 ["Delete column" ses-delete-column
(ses-in-print-area)]
148 ["Set column printer" ses-read-column-printer t
]
149 ["Set column width" ses-set-column-width t
]
150 ["Set default printer" ses-read-default-printer t
]
151 ["Jump to cell" ses-jump t
]
152 ["Set cell printer" ses-read-cell-printer t
]
153 ["Recalculate cell" ses-recalculate-cell t
]
154 ["Truncate cell display" ses-truncate-cell t
]
155 ["Export values" ses-export-tsv t
]
156 ["Export formulas" ses-export-tsf t
]))
158 (defconst ses-mode-edit-map
159 (let ((keys '("\C-c\C-r" ses-insert-range
160 "\C-c\C-s" ses-insert-ses-range
161 [S-mouse-3
] ses-insert-range-click
162 [C-S-mouse-3
] ses-insert-ses-range-click
163 "\M-\C-i" lisp-complete-symbol
))
164 (newmap (make-sparse-keymap)))
165 (set-keymap-parent newmap minibuffer-local-map
)
167 (define-key newmap
(pop keys
) (pop keys
)))
169 "Local keymap for SES minibuffer cell-editing.")
171 ;Local keymap for SES print area
172 (defalias 'ses-mode-print-map
173 (let ((keys '([backtab] backward-char
174 [tab] ses-forward-or-insert
175 "\C-i" ses-forward-or-insert ; Needed for ses-coverage.el?
176 "\M-o" ses-insert-column
177 "\C-o" ses-insert-row
179 "\M-k" ses-delete-column
181 "\C-k" ses-delete-row
182 "\C-j" ses-append-row-jump-first-column
184 "\M-H" ses-mark-column
185 "\C-d" ses-clear-cell-forward
186 "\C-?" ses-clear-cell-backward
191 "c" ses-recalculate-cell
193 "p" ses-read-cell-printer
194 "t" ses-truncate-cell
195 "w" ses-set-column-width
196 "x" ses-export-keymap
197 "\M-p" ses-read-column-printer))
198 (repl '(;;We'll replace these wherever they appear in the keymap
199 clipboard-kill-region ses-kill-override
200 end-of-line ses-end-of-line
201 kill-line ses-delete-row
202 kill-region ses-kill-override
203 open-line ses-insert-row))
204 (numeric "0123456789.-")
205 (newmap (make-keymap)))
206 ;;Get rid of printables
207 (suppress-keymap newmap t)
208 ;;These keys insert themselves as the beginning of a numeric value
209 (dotimes (x (length numeric))
210 (define-key newmap (substring numeric x (1+ x)) 'ses-read-cell))
211 ;;Override these global functions wherever they're bound
213 (substitute-key-definition (car repl) (cadr repl) newmap
214 (current-global-map))
215 (setq repl (cddr repl)))
216 ;;Apparently substitute-key-definition doesn't catch this?
217 (define-key newmap [(menu-bar) edit cut] 'ses-kill-override)
218 ;;Define our other local keys
220 (define-key newmap (car keys) (cadr keys))
221 (setq keys (cddr keys)))
224 ;;Helptext for ses-mode wants keymap as variable, not function
225 (defconst ses-mode-print-map (symbol-function 'ses-mode-print-map))
227 ;;Key map used for 'x' key.
228 (defalias 'ses-export-keymap
229 (let ((map (make-sparse-keymap "SES export")))
230 (define-key map "T" (cons " tab-formulas" 'ses-export-tsf))
231 (define-key map "t" (cons " tab-values" 'ses-export-tsv))
234 (defconst ses-print-data-boundary "\n\014\n"
235 "Marker string denoting the boundary between print area and data area.")
237 (defconst ses-initial-global-parameters
238 "\n( ;Global parameters (these are read first)\n 2 ;SES file-format\n 1 ;numrows\n 1 ;numcols\n)\n\n"
239 "Initial contents for the three-element list at the bottom of the data area.")
241 (defconst ses-initial-file-trailer
242 ";; Local Variables:\n;; mode: ses\n;; End:\n"
243 "Initial contents for the file-trailer area at the bottom of the file.")
245 (defconst ses-initial-file-contents
246 (concat " \n" ; One blank cell in print area.
247 ses-print-data-boundary
248 "(ses-cell A1 nil nil nil nil)\n" ; One blank cell in data area.
249 "\n" ; End-of-row terminator for the one row in data area.
250 "(ses-column-widths [7])\n"
251 "(ses-column-printers [nil])\n"
252 "(ses-default-printer \"%.7g\")\n"
253 "(ses-header-row 0)\n"
254 ses-initial-global-parameters
255 ses-initial-file-trailer)
256 "The initial contents of an empty spreadsheet.")
258 (defconst ses-box-prop '(:box (:line-width 2 :style released-button))
259 "Display properties to create a raised box for cells in the header line.")
261 (defconst ses-standard-printer-functions
262 '(ses-center ses-center-span ses-dashfill ses-dashfill-span
264 "List of print functions to be included in initial history of printer
265 functions. None of these standard-printer functions is suitable for use as a
266 column printer or a global-default printer because they invoke the column or
267 default printer and then modify its output.")
270 ;;----------------------------------------------------------------------------
271 ;; Local variables and constants
272 ;;----------------------------------------------------------------------------
275 (defconst ses-localvars
276 '(ses--blank-line ses--cells ses--col-printers
277 ses--col-widths ses--curcell ses--curcell-overlay
279 ses--deferred-narrow ses--deferred-recalc
280 ses--deferred-write ses--file-format
281 (ses--header-hscroll . -1) ; Flag for "initial recalc needed"
282 ses--header-row ses--header-string ses--linewidth
283 ses--numcols ses--numrows ses--symbolic-formulas
284 ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
285 ses--Dijkstra-weight-bound
286 ;; This list is useful to speed-up clean-up of symbols when
287 ;; an area containing renamed cell is deleted.
288 ses--renamed-cell-symb-list
289 ;; Global variables that we override
290 mode-line-process next-line-add-newlines transient-mark-mode)
291 "Buffer-local variables used by SES.")
293 (defun ses-set-localvars ()
294 "Set buffer-local and initialize some SES variables."
295 (dolist (x ses-localvars)
298 (set (make-local-variable x) nil))
300 (set (make-local-variable (car x)) (cdr x)))
301 (t (error "Unexpected elements `%S' in list `ses-localvars'" x))))))
303 (eval-when-compile ; silence compiler
306 ;;; This variable is documented as being permitted in file-locals:
307 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
309 (defconst ses-paramlines-plist
310 '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
311 ses--header-row -2 ses--file-format 1 ses--numrows 2
313 "Offsets from 'Global parameters' line to various parameter lines in the
314 data area of a spreadsheet.")
318 ;; "Side-effect variables". They are set in one function, altered in
319 ;; another as a side effect, then read back by the first, as a way of
320 ;; passing back more than one value. These declarations are just to make
321 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
322 ;; think the make-local-variable trick above is cleaner).
325 (defvar ses-relocate-return nil
326 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
327 `ses-relocate-all'. Set to 'delete if a cell-reference was deleted from a
328 formula--so the formula needs recalculation. Set to 'range if the size of a
329 `ses-range' was changed--so both the formula's value and list of dependents
330 need to be recalculated.")
332 (defvar ses-call-printer-return nil
333 "Set to t if last cell printer invoked by `ses-call-printer' requested
334 left-justification of the result. Set to error-signal if `ses-call-printer'
335 encountered an error during printing. Otherwise nil.")
337 (defvar ses-start-time nil
338 "Time when current operation started. Used by `ses-time-check' to decide
339 when to emit a progress message.")
342 ;;----------------------------------------------------------------------------
344 ;;----------------------------------------------------------------------------
346 (defmacro ses-get-cell (row col)
347 "Return the cell structure that stores information about cell (ROW,COL)."
348 `(aref (aref ses--cells ,row) ,col))
350 ;; We might want to use defstruct here, but cells are explicitly used as
351 ;; arrays in ses-set-cell, so we'd need to fix this first. --Stef
352 (defsubst ses-make-cell (&optional symbol formula printer references
354 (vector symbol formula printer references property-list))
356 (defmacro ses-cell-symbol (row &optional col)
357 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
358 `(aref ,(if col `(ses-get-cell ,row ,col) row) 0))
359 (put 'ses-cell-symbol 'safe-function t)
361 (defmacro ses-cell-formula (row &optional col)
362 "From a CELL or a pair (ROW,COL), get the function that computes its value."
363 `(aref ,(if col `(ses-get-cell ,row ,col) row) 1))
365 (defmacro ses-cell-printer (row &optional col)
366 "From a CELL or a pair (ROW,COL), get the function that prints its value."
367 `(aref ,(if col `(ses-get-cell ,row ,col) row) 2))
369 (defmacro ses-cell-references (row &optional col)
370 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
371 functions refer to its value."
372 `(aref ,(if col `(ses-get-cell ,row ,col) row) 3))
374 (defun ses-cell-property-get-fun (property-name cell)
375 ;; To speed up property fetching, each time a property is found it is placed
376 ;; in the first position. This way, after the first get, the full property
377 ;; list needs to be scanned only when the property does not exist for that
379 (let* ((plist (aref cell 4))
380 (ret (plist-member plist property-name)))
382 ;; Property was found.
383 (let ((val (cadr ret)))
385 ;; Property found is already in the first position, so just return
388 ;; Property is not in the first position, the following will move it
389 ;; there before returning its value.
390 (let ((next (cddr ret)))
393 (setcdr ret (cdr next))
394 (setcar ret (car next)))
395 (setcdr (last plist 1) nil)))
397 `(,property-name ,val ,@plist))
400 (defmacro ses-cell-property-get (property-name row &optional col)
401 "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
403 When COL is omitted, CELL=ROW is a cell object. When COL is
404 present ROW and COL are the integer coordinates of the cell of
407 `(ses-cell-property-get-fun
409 ,(if col `(ses-get-cell ,row ,col) row)))
411 (defun ses-cell-property-delq-fun (property-name cell)
412 (let ((ret (plist-get (aref cell 4) property-name)))
414 (setcdr ret (cddr ret)))))
416 (defun ses-cell-property-set-fun (property-name property-val cell)
417 (let* ((plist (aref cell 4))
418 (ret (plist-member plist property-name)))
420 (setcar (cdr ret) property-val)
421 (aset cell 4 `(,property-name ,property-val ,@plist)))))
423 (defmacro ses-cell-property-set (property-name property-value row &optional col)
424 "From a CELL or a pair (ROW,COL), set the property value of
425 the corresponding cell with name PROPERTY-NAME to PROPERTY-VALUE."
427 `(ses-cell-property-set-fun ,property-name ,property-value
428 ,(if col `(ses-get-cell ,row ,col) row))
429 `(ses-cell-property-delq-fun ,property-name
430 ,(if col `(ses-get-cell ,row ,col) row))))
432 (defun ses-cell-property-pop-fun (property-name cell)
433 (let* ((plist (aref cell 4))
434 (ret (plist-member plist property-name)))
437 (let ((next (cddr ret)))
440 (setcdr ret (cdr next))
441 (setcar ret (car next)))
444 (setcdr (last plist 2) nil))))))))
447 (defmacro ses-cell-property-pop (property-name row &optional col)
448 "From a CELL or a pair (ROW,COL), get and remove the property value of
449 the corresponding cell with name PROPERTY-NAME."
450 `(ses-cell-property-pop-fun ,property-name
451 ,(if col `(ses-get-cell ,row ,col) row)))
453 (defun ses-cell-property-get-handle-fun (property-name cell)
454 (let* ((plist (aref cell 4))
455 (ret (plist-member plist property-name)))
459 (let ((val (cadr ret))
463 (setcdr ret (cdr next))
464 (setcar ret (car next)))
465 (setcdr (last plist 2) nil))
466 (setq ret (cons val plist))
467 (aset cell 4 (cons property-name ret))
469 (setq ret (cons nil plist))
470 (aset cell 4 (cons property-name ret))
473 (defmacro ses-cell-property-get-handle (property-name row &optional col)
474 "From a CELL or a pair (ROW,COL), get a cons cell whose car is
475 the property value of the corresponding cell property with name
477 `(ses-cell-property-get-handle-fun ,property-name
478 ,(if col `(ses-get-cell ,row ,col) row)))
481 (defalias 'ses-cell-property-handle-car 'car)
482 (defalias 'ses-cell-property-handle-setcar 'setcar)
484 (defmacro ses-cell-value (row &optional col)
485 "From a CELL or a pair (ROW,COL), get the current value for that cell."
486 `(symbol-value (ses-cell-symbol ,row ,col)))
488 (defmacro ses-col-width (col)
489 "Return the width for column COL."
490 `(aref ses--col-widths ,col))
492 (defmacro ses-col-printer (col)
493 "Return the default printer for column COL."
494 `(aref ses--col-printers ,col))
496 (defmacro ses-sym-rowcol (sym)
497 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0).
498 Result is nil if SYM is not a symbol that names a cell."
499 `(and (symbolp ,sym) (get ,sym 'ses-cell)))
501 (defmacro ses-cell (sym value formula printer references)
502 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
503 FORMULA, does not reprint using PRINTER, does not check REFERENCES. This is a
504 macro to prevent propagate-on-load viruses. Safety-checking for FORMULA and
505 PRINTER are deferred until first use."
506 (let ((rowcol (ses-sym-rowcol sym)))
507 (ses-formula-record formula)
508 (ses-printer-record printer)
510 (eq safe-functions t)
511 (setq formula `(ses-safe-formula ,formula)))
514 (eq safe-functions t)
515 (setq printer `(ses-safe-printer ,printer)))
516 (aset (aref ses--cells (car rowcol))
518 (ses-make-cell sym formula printer references)))
522 (defmacro ses-column-widths (widths)
523 "Load the vector of column widths from the spreadsheet file. This is a
524 macro to prevent propagate-on-load viruses."
525 (or (and (vectorp widths) (= (length widths) ses--numcols))
526 (error "Bad column-width vector"))
527 ;;To save time later, we also calculate the total width of each line in the
528 ;;print area (excluding the terminating newline)
529 (setq ses--col-widths widths
530 ses--linewidth (apply '+ -1 (mapcar '1+ widths))
531 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
534 (defmacro ses-column-printers (printers)
535 "Load the vector of column printers from the spreadsheet file and checks
536 them for safety. This is a macro to prevent propagate-on-load viruses."
537 (or (and (vectorp printers) (= (length printers) ses--numcols))
538 (error "Bad column-printers vector"))
539 (dotimes (x ses--numcols)
540 (aset printers x (ses-safe-printer (aref printers x))))
541 (setq ses--col-printers printers)
542 (mapc 'ses-printer-record printers)
545 (defmacro ses-default-printer (def)
546 "Load the global default printer from the spreadsheet file and checks it
547 for safety. This is a macro to prevent propagate-on-load viruses."
548 (setq ses--default-printer (ses-safe-printer def))
549 (ses-printer-record def)
552 (defmacro ses-header-row (row)
553 "Load the header row from the spreadsheet file and checks it
554 for safety. This is a macro to prevent propagate-on-load viruses."
555 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
556 (error "Bad header-row"))
557 (setq ses--header-row row)
560 (defmacro ses-dorange (curcell &rest body)
561 "Execute BODY repeatedly, with the variables `row' and `col' set to each
562 cell in the range specified by CURCELL. The range is available in the
563 variables `minrow', `maxrow', `mincol', and `maxcol'."
564 (declare (indent defun) (debug (form body)))
565 (let ((cur (make-symbol "cur"))
566 (min (make-symbol "min"))
567 (max (make-symbol "max"))
568 (r (make-symbol "r"))
569 (c (make-symbol "c")))
570 `(let* ((,cur ,curcell)
571 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
572 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
573 (let ((minrow (car ,min))
578 (if (or (> minrow maxrow) (> mincol maxcol))
579 (error "Empty range"))
580 (dotimes (,r (- maxrow minrow -1))
581 (setq row (+ ,r minrow))
582 (dotimes (,c (- maxcol mincol -1))
583 (setq col (+ ,c mincol))
586 ;;Support for coverage testing.
587 (defmacro 1value (form)
588 "For code-coverage testing, indicate that FORM is expected to always have
591 (defmacro noreturn (form)
592 "For code-coverage testing, indicate that FORM will always signal an error."
596 ;;----------------------------------------------------------------------------
598 ;;----------------------------------------------------------------------------
600 (defun ses-vector-insert (array idx new)
601 "Create a new vector which is one larger than ARRAY and has NEW inserted
603 (let* ((len (length array))
604 (result (make-vector (1+ len) new)))
607 (if (< x idx) x (1+ x))
611 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
612 (defun ses-vector-delete (array idx count)
613 "Create a new vector which is a copy of ARRAY with COUNT objects removed
614 starting at element IDX. ARRAY is either a vector or a symbol whose value
615 is a vector--if a symbol, the new vector is assigned as the symbol's value."
616 (let* ((a (if (arrayp array) array (symbol-value array)))
617 (len (- (length a) count))
618 (result (make-vector len nil)))
620 (aset result x (aref a (if (< x idx) x (+ x count)))))
625 (defun ses-delete-line (count)
626 "Like `kill-line', but no kill ring."
629 (delete-region pos (point))))
631 (defun ses-printer-validate (printer)
632 "Signal an error if PRINTER is not a valid SES cell printer."
636 (and (stringp (car-safe printer)) (not (cdr printer)))
637 (error "Invalid printer function"))
640 (defun ses-printer-record (printer)
641 "Add PRINTER to `ses-read-printer-history' if not already there, after first
642 checking that it is a valid printer function."
643 (ses-printer-validate printer)
644 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
646 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
648 (defun ses-formula-record (formula)
649 "If FORMULA is of the form 'symbol, add it to the list of symbolic formulas
650 for this spreadsheet."
651 (when (and (eq (car-safe formula) 'quote)
652 (symbolp (cadr formula)))
653 (add-to-list 'ses--symbolic-formulas
654 (list (symbol-name (cadr formula))))))
656 (defun ses-column-letter (col)
657 "Return the alphabetic name of column number COL.
658 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
659 (let ((units (char-to-string (+ ?A (% col 26)))))
662 (concat (ses-column-letter (1- (/ col 26))) units))))
664 (defun ses-create-cell-symbol (row col)
665 "Produce a symbol that names the cell (ROW,COL). (0,0) => 'A1."
666 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
668 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
669 "Create buffer-local variables for cells. This is undoable."
670 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
673 (dotimes (row (1+ (- maxrow minrow)))
674 (dotimes (col (1+ (- maxcol mincol)))
675 (setq xrow (+ row minrow)
677 sym (ses-create-cell-symbol xrow xcol))
678 (put sym 'ses-cell (cons xrow xcol))
679 (make-local-variable sym)))))
681 (defun ses-create-cell-variable (sym row col)
682 "Create a buffer-local variable `SYM' for cell at position (ROW, COL).
684 SYM is the symbol for that variable, ROW and COL are integers for
685 row and column of the cell, with numbering starting from 0.
687 Return nil in case of failure."
688 (unless (local-variable-p sym)
689 (make-local-variable sym)
690 (put sym 'ses-cell (cons row col))))
692 ;; We do not delete the ses-cell properties for the cell-variables, in
693 ;; case a formula that refers to this cell is in the kill-ring and is
694 ;; later pasted back in.
695 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
696 "Destroy buffer-local variables for cells. This is undoable."
698 (dotimes (row (1+ (- maxrow minrow)))
699 (dotimes (col (1+ (- maxcol mincol)))
700 (let ((xrow (+ row minrow)) (xcol (+ col mincol)))
701 (setq sym (if (and (< xrow ses--numrows) (< xcol ses--numcols))
702 (ses-cell-symbol xrow xcol)
703 (ses-create-cell-symbol xrow xcol))))
705 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
707 (kill-local-variable sym))))
708 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
711 (defun ses-reset-header-string ()
712 "Flag the header string for update. Upon undo, the header string will be
714 (push '(apply ses-reset-header-string) buffer-undo-list)
715 (setq ses--header-hscroll -1))
717 ;;Split this code off into a function to avoid coverage-testing difficulties
718 (defun ses-time-check (format arg)
719 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
720 and (eval ARG) and reset `ses-start-time' to the current time."
721 (when (> (- (float-time) ses-start-time) 1.0)
722 (message format (eval arg))
723 (setq ses-start-time (float-time)))
727 ;;----------------------------------------------------------------------------
729 ;;----------------------------------------------------------------------------
731 (defun ses-set-cell (row col field val)
732 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
733 cell (ROW,COL). This is undoable. The cell's data will be updated through
734 `post-command-hook'."
735 (let ((cell (ses-get-cell row col))
736 (elt (plist-get '(value t symbol 0 formula 1 printer 2 references 3)
739 (or elt (signal 'args-out-of-range nil))
740 (setq change (if (eq elt t)
741 (ses-set-with-undo (ses-cell-symbol cell) val)
742 (ses-aset-with-undo cell elt val)))
744 (add-to-list 'ses--deferred-write (cons row col))))
745 nil) ; Make coverage-tester happy.
747 (defun ses-cell-set-formula (row col formula)
748 "Store a new formula for (ROW . COL) and enqueue the cell for
749 recalculation via `post-command-hook'. Updates the reference lists for the
750 cells that this cell refers to. Does not update cell value or reprint the
751 cell. To avoid inconsistencies, this function is not interruptible, which
752 means Emacs will crash if FORMULA contains a circular list."
753 (let* ((cell (ses-get-cell row col))
754 (old (ses-cell-formula cell)))
755 (let ((sym (ses-cell-symbol cell))
756 (oldref (ses-formula-references old))
757 (newref (ses-formula-references formula))
760 (add-to-list 'ses--deferred-recalc sym)
761 ;;Delete old references from this cell. Skip the ones that are also
764 (unless (memq ref newref)
765 (setq x (ses-sym-rowcol ref)
768 (ses-set-cell xrow xcol 'references
769 (delq sym (ses-cell-references xrow xcol)))))
770 ;;Add new ones. Skip ones left over from old list
772 (setq x (ses-sym-rowcol ref)
775 x (ses-cell-references xrow xcol))
777 (ses-set-cell xrow xcol 'references (cons sym x))))
778 (ses-formula-record formula)
779 (ses-set-cell row col 'formula formula))))
782 (defun ses-repair-cell-reference-all ()
783 "Repair cell reference and warn if there was some reference corruption."
786 ;; Step 1, reset :ses-repair-reference cell property in the whole sheet.
787 (dotimes (row ses--numrows)
788 (dotimes (col ses--numcols)
789 (let ((references (ses-cell-property-pop :ses-repair-reference
793 (ses-cell-symbol row col)
795 references) errors)))))
797 ;; Step 2, build new.
798 (dotimes (row ses--numrows)
799 (dotimes (col ses--numcols)
800 (let* ((cell (ses-get-cell row col))
801 (sym (ses-cell-symbol cell))
802 (formula (ses-cell-formula cell))
803 (new-ref (ses-formula-references formula)))
804 (dolist (ref new-ref)
805 (let* ((rowcol (ses-sym-rowcol ref))
806 (h (ses-cell-property-get-handle :ses-repair-reference
807 (car rowcol) (cdr rowcol))))
808 (unless (memq ref (ses-cell-property-handle-car h))
809 (ses-cell-property-handle-setcar
812 (ses-cell-property-handle-car h)))))))))
814 ;; Step 3, overwrite with check.
815 (dotimes (row ses--numrows)
816 (dotimes (col ses--numcols)
817 (let* ((cell (ses-get-cell row col))
818 (irrelevant (ses-cell-references cell))
819 (new-ref (ses-cell-property-pop :ses-repair-reference cell))
821 (dolist (ref new-ref)
822 (if (memq ref irrelevant)
823 (setq irrelevant (delq ref irrelevant))
825 (ses-set-cell row col 'references new-ref)
826 (when (or missing irrelevant)
827 (push `( ,(ses-cell-symbol cell)
828 ,@(and missing (list :missing missing))
829 ,@(and irrelevant (list :irrelevant irrelevant)))
832 (warn "----------------------------------------------------------------
833 Some references were corrupted.
835 The following is a list where each element ELT is such
836 that (car ELT) is the reference of cell CELL with corruption,
837 and (cdr ELT) is a property list where
839 * property `:corrupt-property' means that
840 property `:ses-repair-reference' of cell CELL was initially non
843 * property `:missing' is a list of missing references
845 * property `:irrelevant' is a list of non needed references
848 (message "No reference corruption found"))))
850 (defun ses-calculate-cell (row col force)
851 "Calculate and print the value for cell (ROW,COL) using the cell's formula
852 function and print functions, if any. Result is nil for normal operation, or
853 the error signal if the formula or print function failed. The old value is
854 left unchanged if it was *skip* and the new value is nil.
855 Any cells that depend on this cell are queued for update after the end of
856 processing for the current keystroke, unless the new value is the same as
857 the old and FORCE is nil."
858 (let ((cell (ses-get-cell row col))
859 cycle-error formula-error printer-error)
860 (let ((oldval (ses-cell-value cell))
861 (formula (ses-cell-formula cell))
863 this-cell-Dijkstra-attempt-h
864 this-cell-Dijkstra-attempt
865 this-cell-Dijkstra-attempt+1
866 ref-cell-Dijkstra-attempt-h
867 ref-cell-Dijkstra-attempt
869 (when (eq (car-safe formula) 'ses-safe-formula)
870 (setq formula (ses-safe-formula (cadr formula)))
871 (ses-set-cell row col 'formula formula))
873 (setq newval (eval formula))
875 ;; Variable `sig' can't be nil.
876 (nconc sig (list (ses-cell-symbol cell)))
877 (setq formula-error sig
879 (if (and (not newval) (eq oldval '*skip*))
880 ;; Don't lose the *skip* --- previous field spans this one.
881 (setq newval '*skip*))
883 (when (or force (not (eq newval oldval)))
884 (add-to-list 'ses--deferred-write (cons row col)) ; In case force=t.
885 (setq this-cell-Dijkstra-attempt-h
886 (ses-cell-property-get-handle :ses-Dijkstra-attempt cell);
887 this-cell-Dijkstra-attempt
888 (ses-cell-property-handle-car this-cell-Dijkstra-attempt-h))
889 (if (null this-cell-Dijkstra-attempt)
890 (ses-cell-property-handle-setcar
891 this-cell-Dijkstra-attempt-h
892 (setq this-cell-Dijkstra-attempt
893 (cons ses--Dijkstra-attempt-nb 0)))
894 (unless (= ses--Dijkstra-attempt-nb
895 (car this-cell-Dijkstra-attempt))
896 (setcar this-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
897 (setcdr this-cell-Dijkstra-attempt 0)))
898 (setq this-cell-Dijkstra-attempt+1
899 (1+ (cdr this-cell-Dijkstra-attempt)))
900 (ses-set-cell row col 'value newval)
901 (dolist (ref (ses-cell-references cell))
902 (add-to-list 'ses--deferred-recalc ref)
903 (setq ref-rowcol (ses-sym-rowcol ref)
904 ref-cell-Dijkstra-attempt-h
905 (ses-cell-property-get-handle
906 :ses-Dijkstra-attempt
907 (car ref-rowcol) (cdr ref-rowcol))
908 ref-cell-Dijkstra-attempt
909 (ses-cell-property-handle-car ref-cell-Dijkstra-attempt-h))
911 (if (null ref-cell-Dijkstra-attempt)
912 (ses-cell-property-handle-setcar
913 ref-cell-Dijkstra-attempt-h
914 (setq ref-cell-Dijkstra-attempt
915 (cons ses--Dijkstra-attempt-nb
916 this-cell-Dijkstra-attempt+1)))
917 (if (= (car ref-cell-Dijkstra-attempt) ses--Dijkstra-attempt-nb)
918 (setcdr ref-cell-Dijkstra-attempt
919 (max (cdr ref-cell-Dijkstra-attempt)
920 this-cell-Dijkstra-attempt+1))
921 (setcar ref-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
922 (setcdr ref-cell-Dijkstra-attempt
923 this-cell-Dijkstra-attempt+1)))
925 (when (> this-cell-Dijkstra-attempt+1 ses--Dijkstra-weight-bound)
926 ;; Update print of this cell.
927 (throw 'cycle (setq formula-error
928 `(error ,(format "Found cycle on cells %S"
929 (ses-cell-symbol cell)))
930 cycle-error formula-error)))))))
931 (setq printer-error (ses-print-cell row col))
934 (error (error-message-string cycle-error)))
935 formula-error printer-error)))
937 (defun ses-clear-cell (row col)
938 "Delete formula and printer for cell (ROW,COL)."
939 (ses-set-cell row col 'printer nil)
940 (ses-cell-set-formula row col nil))
942 (defcustom ses-self-reference-early-detection nil
943 "True if cycle detection is early for cells that refer to themselves."
948 (defun ses-update-cells (list &optional force)
949 "Recalculate cells in LIST, checking for dependency loops. Prints
950 progress messages every second. Dependent cells are not recalculated
951 if the cell's value is unchanged and FORCE is nil."
952 (let ((ses--deferred-recalc list)
955 curlist prevlist this-sym this-rowcol formula)
956 (with-temp-message " "
957 (while ses--deferred-recalc
958 ;; In each loop, recalculate cells that refer only to other cells that
959 ;; have already been recalculated or aren't in the recalculation region.
960 ;; Repeat until all cells have been processed or until the set of cells
961 ;; being worked on stops changing.
963 (message "Recalculating... (%d cells left)"
964 (length ses--deferred-recalc)))
965 (setq curlist ses--deferred-recalc
966 ses--deferred-recalc nil
969 ;; this-sym has to be popped from curlist *BEFORE* the check, and not
970 ;; after because of the case of cells referring to themselves.
971 (setq this-sym (pop curlist)
972 this-rowcol (ses-sym-rowcol this-sym)
973 formula (ses-cell-formula (car this-rowcol)
976 (dolist (ref (ses-formula-references formula))
977 (if (and ses-self-reference-early-detection (eq ref this-sym))
978 (error "Cycle found: cell %S is self-referring" this-sym)
979 (when (or (memq ref curlist)
980 (memq ref ses--deferred-recalc))
981 ;; This cell refers to another that isn't done yet
982 (add-to-list 'ses--deferred-recalc this-sym)
984 ;; ses-update-cells is called from post-command-hook, so
985 ;; inhibit-quit is implicitly bound to t.
987 ;; Abort the recalculation. User will probably undo now.
989 (ses-calculate-cell (car this-rowcol) (cdr this-rowcol) force)))
990 (dolist (ref ses--deferred-recalc)
991 (add-to-list 'nextlist ref)))
992 (when ses--deferred-recalc
993 ;; Just couldn't finish these.
994 (dolist (x ses--deferred-recalc)
995 (let ((this-rowcol (ses-sym-rowcol x)))
996 (ses-set-cell (car this-rowcol) (cdr this-rowcol) 'value '*error*)
997 (1value (ses-print-cell (car this-rowcol) (cdr this-rowcol)))))
998 (error "Circular references: %s" ses--deferred-recalc))
1000 ;; Can't use save-excursion here: if the cell under point is updated,
1001 ;; save-excursion's marker will move past the cell.
1005 ;;----------------------------------------------------------------------------
1007 ;;----------------------------------------------------------------------------
1009 (defun ses-in-print-area ()
1010 "Return t if point is in print area of spreadsheet."
1011 (<= (point) ses--data-marker))
1013 ;; We turn off point-motion-hooks and explicitly position the cursor, in case
1014 ;; the intangible properties have gotten screwed up (e.g., when ses-goto-print
1015 ;; is called during a recursive ses-print-cell).
1016 (defun ses-goto-print (row col)
1017 "Move point to print area for cell (ROW,COL)."
1018 (let ((inhibit-point-motion-hooks t)
1020 (goto-char (point-min))
1022 ;; Calculate column position.
1024 (setq n (+ n (ses-col-width c) 1)))
1025 ;; Move to the position.
1026 (and (> n (move-to-column n))
1028 ;; Move point to the bol of next line (for TAB at the last cell).
1031 (defun ses-set-curcell ()
1032 "Set `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
1033 region, or nil if cursor is not at a cell."
1034 (if (or (not mark-active)
1036 (= (region-beginning) (region-end)))
1038 (setq ses--curcell (get-text-property (point) 'intangible))
1040 (let ((bcell (get-text-property (region-beginning) 'intangible))
1041 (ecell (get-text-property (1- (region-end)) 'intangible)))
1042 (when (= (region-end) ses--data-marker)
1043 ;; Correct for overflow.
1044 (setq ecell (get-text-property (- (region-end) 2) 'intangible)))
1045 (setq ses--curcell (if (and bcell ecell)
1050 (defun ses-check-curcell (&rest args)
1051 "Signal an error if `ses--curcell' is inappropriate.
1052 The end marker is appropriate if some argument is 'end.
1053 A range is appropriate if some argument is 'range.
1054 A single cell is appropriate unless some argument is 'needrange."
1055 (if (eq ses--curcell t)
1056 ;; curcell recalculation was postponed, but user typed ahead.
1060 (or (memq 'end args)
1061 (error "Not at cell")))
1062 ((consp ses--curcell)
1063 (or (memq 'range args)
1064 (memq 'needrange args)
1065 (error "Can't use a range")))
1066 ((memq 'needrange args)
1067 (error "Need a range"))))
1069 (defun ses-print-cell (row col)
1070 "Format and print the value of cell (ROW,COL) to the print area.
1071 Use the cell's printer function. If the cell's new print form is too wide,
1072 it will spill over into the following cell, but will not run off the end of the
1073 row or overwrite the next non-nil field. Result is nil for normal operation,
1074 or the error signal if the printer function failed and the cell was formatted
1075 with \"%s\". If the cell's value is *skip*, nothing is printed because the
1076 preceding cell has spilled over."
1077 (catch 'ses-print-cell
1078 (let* ((cell (ses-get-cell row col))
1079 (value (ses-cell-value cell))
1080 (printer (ses-cell-printer cell))
1082 text sig startpos x)
1083 ;; Create the string to print.
1086 ;; Don't print anything.
1087 (throw 'ses-print-cell nil))
1088 ((eq value '*error*)
1089 (setq text (make-string (ses-col-width col) ?#)))
1091 ;; Deferred safety-check on printer.
1092 (if (eq (car-safe printer) 'ses-safe-printer)
1093 (ses-set-cell row col 'printer
1094 (setq printer (ses-safe-printer (cadr printer)))))
1096 (setq text (ses-call-printer (or printer
1097 (ses-col-printer col)
1098 ses--default-printer)
1100 (if (consp ses-call-printer-return)
1101 ;; Printer returned an error.
1102 (setq sig ses-call-printer-return))))
1103 ;; Adjust print width to match column width.
1104 (let ((width (ses-col-width col))
1105 (len (string-width text)))
1108 ;; Fill field to length with spaces.
1109 (setq len (make-string (- width len) ?\s)
1110 text (if (eq ses-call-printer-return t)
1112 (concat len text))))
1114 ;; Spill over into following cells, if possible.
1115 (let ((maxwidth width))
1116 (while (and (> len maxwidth)
1117 (< maxcol ses--numcols)
1118 (or (not (setq x (ses-cell-value row maxcol)))
1121 ;; Set this cell to '*skip* so it won't overwrite our spillover.
1122 (ses-set-cell row maxcol 'value '*skip*))
1123 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
1124 maxcol (1+ maxcol)))
1125 (if (<= len maxwidth)
1126 ;; Fill to complete width of all the fields spanned.
1127 (setq text (concat text (make-string (- maxwidth len) ?\s)))
1128 ;; Not enough room to end of line or next non-nil field. Truncate
1129 ;; if string or decimal; otherwise fill with error indicator.
1130 (setq sig `(error "Too wide" ,text))
1133 (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
1134 ((and (numberp value)
1135 (string-match "\\.[0-9]+" text)
1138 (- (match-end 0) (match-beginning 0))))))
1139 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
1140 (setq text (concat (substring text
1142 (- (match-beginning 0) width))
1143 (substring text (match-end 0)))))
1145 (setq text (make-string maxwidth ?#)))))))))
1146 ;; Substitute question marks for tabs and newlines. Newlines are used as
1147 ;; row-separators; tabs could confuse the reimport logic.
1148 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
1149 (ses-goto-print row col)
1150 (setq startpos (point))
1151 ;; Install the printed result. This is not interruptible.
1152 (let ((inhibit-read-only t)
1154 (let ((inhibit-point-motion-hooks t))
1155 (delete-region (point) (progn
1156 (move-to-column (+ (current-column)
1157 (string-width text)))
1159 ;; We use concat instead of inserting separate strings in order to
1160 ;; reduce the number of cells in the undo list.
1161 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
1162 ;; We use set-text-properties to prevent a wacky print function from
1163 ;; inserting rogue properties, and to ensure that the keymap property is
1164 ;; inherited (is it a bug that only unpropertized strings actually
1165 ;; inherit from surrounding text?)
1166 (set-text-properties 0 (length x) nil x)
1167 (insert-and-inherit x)
1168 (put-text-property startpos (point) 'intangible
1169 (ses-cell-symbol cell))
1170 (when (and (zerop row) (zerop col))
1171 ;; Reconstruct special beginning-of-buffer attributes.
1172 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
1173 (put-text-property (point-min) (point) 'read-only 'ses)
1174 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)))
1175 (if (= row (1- ses--header-row))
1176 ;; This line is part of the header --- force recalc.
1177 (ses-reset-header-string))
1178 ;; If this cell (or a preceding one on the line) previously spilled over
1179 ;; and has gotten shorter, redraw following cells on line recursively.
1180 (when (and (< maxcol ses--numcols)
1181 (eq (ses-cell-value row maxcol) '*skip*))
1182 (ses-set-cell row maxcol 'value nil)
1183 (ses-print-cell row maxcol))
1184 ;; Return to start of cell.
1185 (goto-char startpos)
1188 (defun ses-call-printer (printer &optional value)
1189 "Invoke PRINTER (a string or parenthesized string or function-symbol or
1190 lambda of one argument) on VALUE. Result is the printed cell as a string.
1191 The variable `ses-call-printer-return' is set to t if the printer used
1192 parenthesis to request left-justification, or the error-signal if the
1193 printer signaled one (and \"%s\" is used as the default printer), else nil."
1194 (setq ses-call-printer-return nil)
1195 (condition-case signal
1199 (format printer value)
1201 ((stringp (car-safe printer))
1202 (setq ses-call-printer-return t)
1204 (format (car printer) value)
1207 (setq value (funcall printer (or value "")))
1210 (or (stringp (car-safe value))
1211 (error "Printer should return \"string\" or (\"string\")"))
1212 (setq ses-call-printer-return t)
1215 (setq ses-call-printer-return signal)
1216 (prin1-to-string value t))))
1218 (defun ses-adjust-print-width (col change)
1219 "Insert CHANGE spaces in front of column COL, or at end of line if
1220 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
1221 `inhibit-quit' to t."
1222 (let ((inhibit-read-only t)
1223 (blank (if (> change 0) (make-string change ?\s)))
1224 (at-end (= col ses--numcols)))
1225 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
1226 ;; ses-set-with-undo always returns t for strings.
1227 (1value (ses-set-with-undo 'ses--blank-line
1228 (concat (make-string ses--linewidth ?\s) "\n")))
1229 (dotimes (row ses--numrows)
1230 (ses-goto-print row col)
1232 ;; Insert new columns before newline.
1233 (let ((inhibit-point-motion-hooks t))
1237 (delete-char (- change))))))
1239 (defun ses-print-cell-new-width (row col)
1240 "Same as `ses-print-cell', except if the cell's value is *skip*,
1241 the preceding nonskipped cell is reprinted. This function is used
1242 when the width of cell (ROW,COL) has changed."
1243 (if (not (eq (ses-cell-value row col) '*skip*))
1244 (ses-print-cell row col)
1245 ;;Cell was skipped over - reprint previous
1246 (ses-goto-print row col)
1248 (let ((rowcol (ses-sym-rowcol (get-text-property (point) 'intangible))))
1249 (ses-print-cell (car rowcol) (cdr rowcol)))))
1252 ;;----------------------------------------------------------------------------
1254 ;;----------------------------------------------------------------------------
1256 (defun ses-narrowed-p () (/= (- (point-max) (point-min)) (buffer-size)))
1259 "Turn off narrowing, to be reenabled at end of command loop."
1260 (if (ses-narrowed-p)
1261 (setq ses--deferred-narrow t))
1264 (defun ses-goto-data (def &optional col)
1265 "Move point to data area for (DEF,COL). If DEF is a row
1266 number, COL is the column number for a data cell -- otherwise DEF
1267 is one of the symbols ses--col-widths, ses--col-printers,
1268 ses--default-printer, ses--numrows, or ses--numcols."
1270 (let ((inhibit-point-motion-hooks t)) ; In case intangible attrs are wrong.
1274 (goto-char ses--data-marker)
1275 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
1276 ;; Convert def-symbol to offset.
1277 (setq def (plist-get ses-paramlines-plist def))
1278 (or def (signal 'args-out-of-range nil))
1279 (goto-char ses--params-marker)
1280 (forward-line def))))
1282 (defun ses-set-parameter (def value &optional elem)
1283 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1284 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1285 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
1287 ;; We call ses-goto-data early, using the old values of numrows and numcols
1288 ;; in case one of them is being changed.
1290 (let ((inhibit-read-only t)
1291 (fmt (plist-get '(ses--col-widths "(ses-column-widths %S)"
1292 ses--col-printers "(ses-column-printers %S)"
1293 ses--default-printer "(ses-default-printer %S)"
1294 ses--header-row "(ses-header-row %S)"
1295 ses--file-format " %S ;SES file-format"
1296 ses--numrows " %S ;numrows"
1297 ses--numcols " %S ;numcols")
1302 (setq oldval (aref (symbol-value def) elem))
1303 (aset (symbol-value def) elem value))
1304 (setq oldval (symbol-value def))
1306 ;; Special undo since it's outside the narrowed buffer.
1307 (let (buffer-undo-list)
1308 (delete-region (point) (line-end-position))
1309 (insert (format fmt (symbol-value def))))
1310 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1313 (defun ses-write-cells ()
1314 "Write cells in `ses--deferred-write' from local variables to data area.
1315 Newlines in the data are escaped."
1316 (let* ((inhibit-read-only t)
1317 (print-escape-newlines t)
1318 rowcol row col cell sym formula printer text)
1319 (setq ses-start-time (float-time))
1320 (with-temp-message " "
1322 (while ses--deferred-write
1323 (ses-time-check "Writing... (%d cells left)"
1324 '(length ses--deferred-write))
1325 (setq rowcol (pop ses--deferred-write)
1328 cell (ses-get-cell row col)
1329 sym (ses-cell-symbol cell)
1330 formula (ses-cell-formula cell)
1331 printer (ses-cell-printer cell))
1332 (if (eq (car-safe formula) 'ses-safe-formula)
1333 (setq formula (cadr formula)))
1334 (if (eq (car-safe printer) 'ses-safe-printer)
1335 (setq printer (cadr printer)))
1336 ;; This is noticeably faster than (format "%S %S %S %S %S")
1337 (setq text (concat "(ses-cell "
1340 (prin1-to-string (symbol-value sym))
1342 (prin1-to-string formula)
1344 (prin1-to-string printer)
1346 (if (atom (ses-cell-references cell))
1349 (mapconcat 'symbol-name
1350 (ses-cell-references cell)
1354 (ses-goto-data row col)
1355 (delete-region (point) (line-end-position))
1360 ;;----------------------------------------------------------------------------
1361 ;; Formula relocation
1362 ;;----------------------------------------------------------------------------
1364 (defun ses-formula-references (formula &optional result-so-far)
1365 "Produce a list of symbols for cells that this FORMULA's value
1366 refers to. For recursive calls, RESULT-SO-FAR is the list being
1367 constructed, or t to get a wrong-type-argument error when the
1368 first reference is found."
1369 (if (ses-sym-rowcol formula)
1370 ;;Entire formula is one symbol
1371 (add-to-list 'result-so-far formula)
1374 ((eq (car formula) 'ses-range)
1376 (cdr (funcall 'macroexpand
1377 (list 'ses-range (nth 1 formula)
1379 (add-to-list 'result-so-far cur)))
1380 ((null (eq (car formula) 'quote))
1381 ;;Recursive call for subformulas
1382 (dolist (cur formula)
1383 (setq result-so-far (ses-formula-references cur result-so-far))))
1385 ;;Ignore other stuff
1387 ;; other type of atom are ignored
1391 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1392 "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
1393 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1394 by (ROWINCR,COLINCR)."
1395 (let ((row (car rowcol))
1397 (if (or (< row startrow) (< col startcol))
1399 (setq row (+ row rowincr)
1400 col (+ col colincr))
1401 (if (and (>= row startrow) (>= col startcol)
1402 (< row ses--numrows) (< col ses--numcols))
1403 ;;Relocate this variable
1404 (ses-create-cell-symbol row col)
1405 ;;Delete reference to a deleted cell
1408 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1409 "Produce a copy of FORMULA where all symbols that refer to cells in row
1410 STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
1411 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1412 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1414 If ROWINCR or COLINCR is negative, references to cells being deleted are
1416 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1418 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1419 (let (rowcol result)
1420 (if (or (atom formula) (eq (car formula) 'quote))
1421 (if (and (setq rowcol (ses-sym-rowcol formula))
1422 (string-match "\\`[A-Z]+[0-9]+\\'" (symbol-name formula)))
1423 (ses-relocate-symbol formula rowcol
1424 startrow startcol rowincr colincr)
1425 formula) ; Pass through as-is.
1426 (dolist (cur formula)
1427 (setq rowcol (ses-sym-rowcol cur))
1430 (setq cur (ses-relocate-symbol cur rowcol
1431 startrow startcol rowincr colincr))
1434 ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
1435 ;; don't change the flag if it's already 'range, since range implies
1437 (unless ses-relocate-return
1438 (setq ses-relocate-return 'delete))))
1439 ((eq (car-safe cur) 'ses-range)
1440 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1443 ((or (atom cur) (eq (car cur) 'quote))
1444 ;; Constants pass through unchanged.
1447 ;; Recursively copy and alter subformulas.
1448 (push (ses-relocate-formula cur startrow startcol
1451 (nreverse result))))
1453 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1454 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1455 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1456 new range, or nil if the entire range is deleted. If new rows are being added
1457 just beyond the end of a row range, or new columns just beyond a column range,
1458 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1459 if the range was altered."
1460 (let* ((minorig (cadr range))
1461 (minrowcol (ses-sym-rowcol minorig))
1462 (min (ses-relocate-symbol minorig minrowcol
1465 (maxorig (nth 2 range))
1466 (maxrowcol (ses-sym-rowcol maxorig))
1467 (max (ses-relocate-symbol maxorig maxrowcol
1472 ((and (not min) (not max))
1473 (setq range nil)) ; The entire range is deleted.
1475 ;; Inserting or deleting rows.
1478 ;; Chopped off beginning of range.
1479 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1480 ses-relocate-return 'range))
1483 ;; Trying to insert a nonexistent row.
1484 (setq max (ses-create-cell-symbol (1- ses--numrows)
1486 ;; End of range is being deleted.
1487 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1488 ses-relocate-return 'range))
1490 (= (car maxrowcol) (1- startrow))
1491 (= (cdr minrowcol) (cdr maxrowcol))
1492 ;; Insert after ending row of vertical range --- include it.
1493 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1494 (cdr maxrowcol))))))
1496 ;; Inserting or deleting columns.
1499 ;; Chopped off beginning of range.
1500 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1501 ses-relocate-return 'range))
1504 ;; Trying to insert a nonexistent column.
1505 (setq max (ses-create-cell-symbol (car maxrowcol)
1507 ;; End of range is being deleted.
1508 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1509 ses-relocate-return 'range))
1511 (= (cdr maxrowcol) (1- startcol))
1512 (= (car minrowcol) (car maxrowcol))
1513 ;; Insert after ending column of horizontal range --- include it.
1514 (setq max (ses-create-cell-symbol (car maxrowcol)
1515 (+ startcol colincr -1)))))))
1517 (if (/= (- (funcall field maxrowcol)
1518 (funcall field minrowcol))
1519 (- (funcall field (ses-sym-rowcol max))
1520 (funcall field (ses-sym-rowcol min))))
1521 ;; This range has changed size.
1522 (setq ses-relocate-return 'range))
1523 `(ses-range ,min ,max ,@(cl-cdddr range)))))
1525 (defun ses-relocate-all (minrow mincol rowincr colincr)
1526 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1527 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1530 (let (mycell newval xrow)
1531 (dotimes-with-progress-reporter
1532 (row ses--numrows) "Relocating formulas..."
1533 (dotimes (col ses--numcols)
1534 (setq ses-relocate-return nil
1535 mycell (ses-get-cell row col)
1536 newval (ses-relocate-formula (ses-cell-formula mycell)
1537 minrow mincol rowincr colincr)
1538 xrow (- row rowincr))
1539 (ses-set-cell row col 'formula newval)
1540 (if (eq ses-relocate-return 'range)
1541 ;; This cell contains a (ses-range X Y) where a cell has been
1542 ;; inserted or deleted in the middle of the range.
1543 (push (cons row col) reform))
1544 (if ses-relocate-return
1545 ;; This cell referred to a cell that's been deleted or is no
1546 ;; longer part of the range. We can't fix that now because
1547 ;; reference lists cells have been partially updated.
1548 (add-to-list 'ses--deferred-recalc
1549 (ses-create-cell-symbol row col)))
1550 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1551 minrow mincol rowincr colincr))
1552 (ses-set-cell row col 'references newval)
1553 (and (>= row minrow) (>= col mincol)
1554 (let ((sym (ses-cell-symbol row col))
1555 (xcol (- col colincr)))
1561 (ses-create-cell-symbol xrow xcol))))
1562 ;; This is a renamed cell, do not update the cell
1563 ;; name, but just update the coordinate property.
1564 (put sym 'ses-cell (cons row col))
1565 (ses-set-cell row col 'symbol
1566 (setq sym (ses-create-cell-symbol row col)))
1567 (unless (and (boundp sym) (local-variable-p sym))
1568 (set (make-local-variable sym) nil)
1569 (put sym 'ses-cell (cons row col)))))) )))
1570 ;; Relocate the cell values.
1571 (let (oldval myrow mycol xrow xcol)
1573 ((and (<= rowincr 0) (<= colincr 0))
1574 ;; Deletion of rows and/or columns.
1575 (dotimes-with-progress-reporter
1576 (row (- ses--numrows minrow)) "Relocating variables..."
1577 (setq myrow (+ row minrow))
1578 (dotimes (col (- ses--numcols mincol))
1579 (setq mycol (+ col mincol)
1580 xrow (- myrow rowincr)
1581 xcol (- mycol colincr))
1582 (let ((sym (ses-cell-symbol myrow mycol))
1583 (xsym (ses-create-cell-symbol xrow xcol)))
1584 ;; Make the value relocation only when if the cell is not
1585 ;; a renamed cell. Otherwise this is not needed.
1587 (ses-set-cell myrow mycol 'value
1588 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1589 (ses-cell-value xrow xcol)
1590 ;;Cell is off the end of the array
1591 (symbol-value xsym))))))))
1593 ((and (wholenump rowincr) (wholenump colincr))
1594 ;; Insertion of rows and/or columns. Run the loop backwards.
1595 (let ((disty (1- ses--numrows))
1596 (distx (1- ses--numcols))
1598 (dotimes-with-progress-reporter
1599 (row (- ses--numrows minrow)) "Relocating variables..."
1600 (setq myrow (- disty row))
1601 (dotimes (col (- ses--numcols mincol))
1602 (setq mycol (- distx col)
1603 xrow (- myrow rowincr)
1604 xcol (- mycol colincr))
1605 (if (or (< xrow minrow) (< xcol mincol))
1606 ;; Newly-inserted value.
1608 ;; Transfer old value.
1609 (setq oldval (ses-cell-value xrow xcol)))
1610 (ses-set-cell myrow mycol 'value oldval)))
1611 t)) ; Make testcover happy by returning non-nil here.
1613 (error "ROWINCR and COLINCR must have the same sign"))))
1614 ;; Reconstruct reference lists for cells that contain ses-ranges that have
1617 (message "Fixing ses-ranges...")
1619 (setq ses-start-time (float-time))
1621 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1622 (setq row (caar reform)
1624 reform (cdr reform))
1625 (ses-cell-set-formula row col (ses-cell-formula row col))))
1629 ;;----------------------------------------------------------------------------
1631 ;;----------------------------------------------------------------------------
1633 (defun ses-begin-change ()
1634 "For undo, remember point before we start changing hidden stuff."
1635 (let ((inhibit-read-only t))
1636 (insert-and-inherit "X")
1637 (delete-region (1- (point)) (point))))
1639 (defun ses-set-with-undo (sym newval)
1640 "Like set, but undoable. Result is t if value has changed."
1641 ;; We try to avoid adding redundant entries to the undo list, but this is
1642 ;; unavoidable for strings because equal ignores text properties and there's
1643 ;; no easy way to get the whole property list to see if it's different!
1644 (unless (and (boundp sym)
1645 (equal (symbol-value sym) newval)
1646 (not (stringp newval)))
1647 (push (if (boundp sym)
1648 `(apply ses-set-with-undo ,sym ,(symbol-value sym))
1649 `(apply ses-unset-with-undo ,sym))
1654 (defun ses-unset-with-undo (sym)
1655 "Set SYM to be unbound. This is undoable."
1656 (when (1value (boundp sym)) ; Always bound, except after a programming error.
1657 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
1660 (defun ses-aset-with-undo (array idx newval)
1661 "Like `aset', but undoable.
1662 Result is t if element has changed."
1663 (unless (equal (aref array idx) newval)
1664 (push `(apply ses-aset-with-undo ,array ,idx
1665 ,(aref array idx)) buffer-undo-list)
1666 (aset array idx newval)
1670 ;;----------------------------------------------------------------------------
1671 ;; Startup for major mode
1672 ;;----------------------------------------------------------------------------
1675 "Parse the current buffer and set up buffer-local variables.
1676 Does not execute cell formulas or print functions."
1678 ;; Read our global parameters, which should be a 3-element list.
1679 (goto-char (point-max))
1680 (search-backward ";; Local Variables:\n" nil t)
1682 (setq ses--params-marker (point-marker))
1683 (let ((params (condition-case nil (read (current-buffer)) (error nil))))
1684 (or (and (= (safe-length params) 3)
1685 (numberp (car params))
1686 (numberp (cadr params))
1687 (>= (cadr params) 0)
1688 (numberp (nth 2 params))
1689 (> (nth 2 params) 0))
1690 (error "Invalid SES file"))
1691 (setq ses--file-format (car params)
1692 ses--numrows (cadr params)
1693 ses--numcols (nth 2 params))
1694 (when (= ses--file-format 1)
1695 (let (buffer-undo-list) ; This is not undoable.
1696 (ses-goto-data 'ses--header-row)
1697 (insert "(ses-header-row 0)\n")
1698 (ses-set-parameter 'ses--file-format 2)
1699 (message "Upgrading from SES-1 file format")))
1700 (or (= ses--file-format 2)
1701 (error "This file needs a newer version of the SES library code"))
1702 ;; Initialize cell array.
1703 (setq ses--cells (make-vector ses--numrows nil))
1704 (dotimes (row ses--numrows)
1705 (aset ses--cells row (make-vector ses--numcols nil))))
1706 ;; Skip over print area, which we assume is correct.
1707 (goto-char (point-min))
1708 (forward-line ses--numrows)
1709 (or (looking-at ses-print-data-boundary)
1710 (error "Missing marker between print and data areas"))
1712 (setq ses--data-marker (point-marker))
1713 (forward-char (1- (length ses-print-data-boundary)))
1714 ;; Initialize printer and symbol lists.
1715 (mapc 'ses-printer-record ses-standard-printer-functions)
1716 (setq ses--symbolic-formulas nil)
1717 ;; Load cell definitions.
1718 (dotimes (row ses--numrows)
1719 (dotimes (col ses--numcols)
1720 (let* ((x (read (current-buffer)))
1721 (sym (car-safe (cdr-safe x))))
1722 (or (and (looking-at "\n")
1723 (eq (car-safe x) 'ses-cell)
1724 (ses-create-cell-variable sym row col))
1725 (error "Cell-def error"))
1727 (or (looking-at "\n\n")
1728 (error "Missing blank line between rows")))
1729 ;; Load global parameters.
1730 (let ((widths (read (current-buffer)))
1731 (n1 (char-after (point)))
1732 (printers (read (current-buffer)))
1733 (n2 (char-after (point)))
1734 (def-printer (read (current-buffer)))
1735 (n3 (char-after (point)))
1736 (head-row (read (current-buffer)))
1737 (n4 (char-after (point))))
1738 (or (and (eq (car-safe widths) 'ses-column-widths)
1740 (eq (car-safe printers) 'ses-column-printers)
1742 (eq (car-safe def-printer) 'ses-default-printer)
1744 (eq (car-safe head-row) 'ses-header-row)
1746 (error "Invalid SES global parameters"))
1747 (1value (eval widths))
1748 (1value (eval def-printer))
1749 (1value (eval printers))
1750 (1value (eval head-row)))
1751 ;; Should be back at global-params.
1753 (or (looking-at (replace-regexp-in-string "1" "[0-9]+"
1754 ses-initial-global-parameters))
1755 (error "Problem with column-defs or global-params"))
1756 ;; Check for overall newline count in definitions area.
1758 (let ((start (point)))
1759 (ses-goto-data 'ses--numrows)
1760 (or (= (point) start)
1761 (error "Extraneous newlines someplace?"))))
1764 "Set up for display of only the printed cell values.
1766 Narrows the buffer to show only the print area. Gives it `read-only' and
1767 `intangible' properties. Sets up highlighting for current cell."
1769 (let ((end (point-min))
1770 (inhibit-read-only t)
1771 (inhibit-point-motion-hooks t)
1772 (was-modified (buffer-modified-p))
1774 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1775 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1776 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1777 ;; The print area is read-only (except for our special commands) and uses a
1779 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1780 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1781 ;; For the beginning of the buffer, we want the read-only and keymap
1782 ;; attributes to be inherited from the first character.
1783 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1784 ;; Create intangible properties, which also indicate which cell the text
1786 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1787 (dotimes (col ses--numcols)
1789 sym (ses-cell-symbol row col))
1790 ;; Include skipped cells following this one.
1791 (while (and (< col (1- ses--numcols))
1792 (eq (ses-cell-value row (1+ col)) '*skip*))
1793 (setq end (+ end (ses-col-width col) 1)
1795 (setq end (save-excursion
1797 (move-to-column (+ (current-column) (- end pos)
1798 (ses-col-width col)))
1800 (+ end (ses-col-width col) 1)
1803 (put-text-property pos end 'intangible sym)))
1804 ;; Adding these properties did not actually alter the text.
1805 (unless was-modified
1806 (restore-buffer-modified-p nil)
1807 (buffer-disable-undo)
1808 (buffer-enable-undo)))
1809 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1810 ;; because column A must be at least 1 column wide.
1811 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1812 (overlay-put ses--curcell-overlay 'face 'underline))
1814 (defun ses-cleanup ()
1815 "Cleanup when changing a buffer from SES mode to something else.
1816 Delete overlays, remove special text properties."
1818 (let ((inhibit-read-only t)
1819 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1820 ;; user "the file is modified, do you really want to make modifications
1821 ;; to this buffer", where the "modifications" refer to the irrelevant
1822 ;; set-text-properties below.
1823 (buffer-file-name nil)
1824 (was-modified (buffer-modified-p)))
1825 ;; Delete read-only, keymap, and intangible properties.
1826 (set-text-properties (point-min) (point-max) nil)
1828 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1829 (unless was-modified
1830 (restore-buffer-modified-p nil))))
1834 "Major mode for Simple Emacs Spreadsheet.
1835 See \"ses-example.ses\" (in `data-directory') for more info.
1839 These key definitions are active only in the print area (the visible part):
1840 \\{ses-mode-print-map}
1841 These are active only in the minibuffer, when entering or editing a formula:
1842 \\{ses-mode-edit-map}"
1844 (unless (and (boundp 'ses--deferred-narrow)
1845 (eq ses--deferred-narrow 'ses-mode))
1846 (kill-all-local-variables)
1848 (setq major-mode 'ses-mode
1850 next-line-add-newlines nil
1852 ;; SES deliberately puts lots of trailing whitespace in its buffer.
1853 show-trailing-whitespace nil
1854 ;; Cell ranges do not work reasonably without this.
1855 transient-mark-mode t
1856 ;; Not to use tab characters for safe (tabs may do bad for column
1858 indent-tabs-mode nil)
1859 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1860 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1861 (setq header-line-format '(:eval (progn
1862 (when (/= (window-hscroll)
1863 ses--header-hscroll)
1864 ;; Reset ses--header-hscroll first,
1865 ;; to avoid recursion problems when
1866 ;; debugging ses-create-header-string
1867 (setq ses--header-hscroll
1869 (ses-create-header-string))
1870 ses--header-string)))
1871 (let ((was-empty (zerop (buffer-size)))
1872 (was-modified (buffer-modified-p)))
1875 ;; Initialize buffer to contain one cell, for now.
1876 (insert ses-initial-file-contents))
1880 (unless (equal ses-initial-default-printer
1881 (1value ses--default-printer))
1882 (1value (ses-read-default-printer ses-initial-default-printer)))
1883 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1884 (1value (ses-set-column-width 0 ses-initial-column-width)))
1886 (if (> (car ses-initial-size) (1value ses--numrows))
1887 (1value (ses-insert-row (1- (car ses-initial-size)))))
1888 (if (> (cdr ses-initial-size) (1value ses--numcols))
1889 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1891 (restore-buffer-modified-p was-modified)
1892 (buffer-disable-undo)
1893 (buffer-enable-undo)
1894 (goto-char (point-min))))
1895 (use-local-map ses-mode-map)
1896 ;; Set the deferred narrowing flag (we can't narrow until after
1897 ;; after-find-file completes). If .ses is on the auto-load alist and the
1898 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
1899 ;; special flag to detect this (will be reset by ses-command-hook). For
1900 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
1901 ;; so use an idle timer to make sure.
1902 (setq ses--deferred-narrow 'ses-mode)
1903 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1904 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1905 (run-mode-hooks 'ses-mode-hook)))
1907 (put 'ses-mode 'mode-class 'special)
1909 (defun ses-command-hook ()
1910 "Invoked from `post-command-hook'. If point has moved to a different cell,
1911 moves the underlining overlay. Performs any recalculations or cell-data
1912 writes that have been deferred. If buffer-narrowing has been deferred,
1913 narrows the buffer now."
1915 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
1916 (when ses--deferred-recalc
1917 ;; We reset the deferred list before starting on the recalc --- in
1918 ;; case of error, we don't want to retry the recalc after every
1920 (ses-initialize-Dijkstra-attempt)
1921 (let ((old ses--deferred-recalc))
1922 (setq ses--deferred-recalc nil)
1923 (ses-update-cells old)))
1924 (when ses--deferred-write
1925 ;; We don't reset the deferred list before starting --- the most
1926 ;; likely error is keyboard-quit, and we do want to keep trying these
1927 ;; writes after a quit.
1929 (push '(apply ses-widen) buffer-undo-list))
1930 (when ses--deferred-narrow
1931 ;; We're not allowed to narrow the buffer until after-find-file has
1932 ;; read the local variables at the end of the file. Now it's safe to
1933 ;; do the narrowing.
1934 (narrow-to-region (point-min) ses--data-marker)
1935 (setq ses--deferred-narrow nil))
1936 ;; Update the mode line.
1937 (let ((oldcell ses--curcell))
1939 (unless (eq ses--curcell oldcell)
1942 (setq mode-line-process nil))
1943 ((atom ses--curcell)
1944 (setq mode-line-process (list " cell "
1945 (symbol-name ses--curcell))))
1947 (setq mode-line-process (list " range "
1948 (symbol-name (car ses--curcell))
1950 (symbol-name (cdr ses--curcell))))))
1951 (force-mode-line-update)))
1952 ;; Use underline overlay for single-cells only, turn off otherwise.
1953 (if (listp ses--curcell)
1954 (move-overlay ses--curcell-overlay 2 2)
1955 (let ((next (next-single-property-change (point) 'intangible)))
1956 (move-overlay ses--curcell-overlay (point) (1- next))))
1957 (when (not (pos-visible-in-window-p))
1958 ;; Scrolling will happen later.
1959 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1960 (setq ses--curcell t)))
1961 ;; Prevent errors in this post-command-hook from silently erasing the hook!
1963 (unless executing-kbd-macro
1965 (message "%s" (error-message-string err))))
1966 nil) ; Make coverage-tester happy.
1968 (defun ses-create-header-string ()
1969 "Set up `ses--header-string' as the buffer's header line.
1970 Based on the current set of columns and `window-hscroll' position."
1971 (let ((totwidth (- (window-hscroll)))
1973 ;; Leave room for the left-side fringe and scrollbar.
1974 (push (propertize " " 'display '((space :align-to 0))) result)
1975 (dotimes (col ses--numcols)
1976 (setq width (ses-col-width col)
1977 totwidth (+ totwidth width 1))
1979 ;; Scrolled so intercolumn space is leftmost.
1981 (when (> totwidth 1)
1982 (if (> ses--header-row 0)
1984 (ses-goto-print (1- ses--header-row) col)
1985 (setq x (buffer-substring-no-properties (point)
1987 ;; Strip trailing space.
1988 (if (string-match "[ \t]+\\'" x)
1989 (setq x (substring x 0 (match-beginning 0))))
1990 ;; Cut off excess text.
1991 (if (>= (length x) totwidth)
1992 (setq x (substring x 0 (- totwidth -1)))))
1993 (setq x (ses-column-letter col)))
1994 (push (propertize x 'face ses-box-prop) result)
1995 (push (propertize "."
1996 'display `((space :align-to ,(1- totwidth)))
1999 ;; Allow the following space to be squished to make room for the 3-D box
2000 ;; Coverage test ignores properties, thinks this is always a space!
2001 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2003 (if (> ses--header-row 0)
2004 (push (propertize (format " [row %d]" ses--header-row)
2005 'display '((height (- 1))))
2007 (setq ses--header-string (apply 'concat (nreverse result)))))
2010 ;;----------------------------------------------------------------------------
2011 ;; Redisplay and recalculation
2012 ;;----------------------------------------------------------------------------
2014 (defun ses-jump (sym)
2015 "Move point to cell SYM."
2016 (interactive "SJump to cell: ")
2017 (let ((rowcol (ses-sym-rowcol sym)))
2018 (or rowcol (error "Invalid cell name"))
2019 (if (eq (symbol-value sym) '*skip*)
2020 (error "Cell is covered by preceding cell"))
2021 (ses-goto-print (car rowcol) (cdr rowcol))))
2023 (defun ses-jump-safe (cell)
2024 "Like `ses-jump', but no error if invalid cell."
2029 (defun ses-reprint-all (&optional nonarrow)
2030 "Recreate the display area. Calls all printer functions. Narrows to
2031 print area if NONARROW is nil."
2035 (setq ses--deferred-narrow t))
2036 (let ((startcell (get-text-property (point) 'intangible))
2037 (inhibit-read-only t))
2039 (goto-char (point-min))
2040 (search-forward ses-print-data-boundary)
2041 (backward-char (length ses-print-data-boundary))
2042 (delete-region (point-min) (point))
2043 ;; Insert all blank lines before printing anything, so ses-print-cell can
2044 ;; find the data area when inserting or deleting *skip* values for cells.
2045 (dotimes (row ses--numrows)
2046 (insert-and-inherit ses--blank-line))
2047 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2048 (if (eq (ses-cell-value row 0) '*skip*)
2049 ;; Column deletion left a dangling skip.
2050 (ses-set-cell row 0 'value nil))
2051 (dotimes (col ses--numcols)
2052 (ses-print-cell row col))
2053 (beginning-of-line 2))
2054 (ses-jump-safe startcell)))
2056 (defun ses-initialize-Dijkstra-attempt ()
2057 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2058 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2060 (defun ses-recalculate-cell ()
2061 "Recalculate and reprint the current cell or range.
2063 For an individual cell, shows the error if the formula or printer
2064 signals one, or otherwise shows the cell's complete value. For a range, the
2065 cells are recalculated in \"natural\" order, so cells that other cells refer
2066 to are recalculated first."
2068 (ses-check-curcell 'range)
2070 (ses-initialize-Dijkstra-attempt)
2071 (let (sig cur-rowcol)
2072 (setq ses-start-time (float-time))
2073 (if (atom ses--curcell)
2075 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2077 (ses-cell-property-set :ses-Dijkstra-attempt
2078 (cons ses--Dijkstra-attempt-nb 0)
2079 (car cur-rowcol) (cdr cur-rowcol) )
2080 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2081 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2082 (cdr cur-rowcol)))))
2083 ;; First, recalculate all cells that don't refer to other cells and
2084 ;; produce a list of cells with references.
2085 (ses-dorange ses--curcell
2086 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
2089 ;; The t causes an error if the cell has references. If no
2090 ;; references, the t will be the result value.
2091 (1value (ses-formula-references (ses-cell-formula row col) t))
2092 (ses-cell-property-set :ses-Dijkstra-attempt
2093 (cons ses--Dijkstra-attempt-nb 0)
2095 (when (setq sig (ses-calculate-cell row col t))
2096 (nconc sig (list (ses-cell-symbol row col)))))
2097 (wrong-type-argument
2098 ;; The formula contains a reference.
2099 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
2100 ;; Do the update now, so we can force recalculation.
2101 (let ((x ses--deferred-recalc))
2102 (setq ses--deferred-recalc nil)
2103 (condition-case hold
2104 (ses-update-cells x t)
2105 (error (setq sig hold))))
2108 (message "%s" (error-message-string sig)))
2109 ((consp ses--curcell)
2112 (princ (symbol-value ses--curcell))))))
2114 (defun ses-recalculate-all ()
2115 "Recalculate and reprint all cells."
2117 (let ((startcell (get-text-property (point) 'intangible))
2118 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2119 (1- ses--numcols)))))
2120 (ses-recalculate-cell)
2121 (ses-jump-safe startcell)))
2123 (defun ses-truncate-cell ()
2124 "Reprint current cell, but without spillover into any following blank cells."
2127 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2130 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
2131 (eq (ses-cell-value row (1+ col)) '*skip*))
2132 ;; This cell has spill-over. We'll momentarily pretend the following cell
2134 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
2135 (ses-print-cell row col)))
2136 ;; Now remove the *skip*. ses-print-cell is always nil here.
2137 (ses-set-cell row (1+ col) 'value nil)
2138 (1value (ses-print-cell row (1+ col))))))
2140 (defun ses-reconstruct-all ()
2141 "Reconstruct buffer based on cell data stored in Emacs variables."
2144 ;;Reconstruct reference lists.
2146 ;;Delete old reference lists
2147 (dotimes-with-progress-reporter
2148 (row ses--numrows) "Deleting references..."
2149 (dotimes (col ses--numcols)
2150 (ses-set-cell row col 'references nil)))
2151 ;;Create new reference lists
2152 (dotimes-with-progress-reporter
2153 (row ses--numrows) "Computing references..."
2154 (dotimes (col ses--numcols)
2155 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2156 (setq x (ses-sym-rowcol ref)
2159 (ses-set-cell yrow ycol 'references
2160 (cons (ses-cell-symbol row col)
2161 (ses-cell-references yrow ycol)))))))
2162 ;; Delete everything and reconstruct basic data area.
2164 (let ((inhibit-read-only t))
2165 (goto-char (point-max))
2166 (if (search-backward ";; Local Variables:\n" nil t)
2167 (delete-region (point-min) (point))
2168 ;; Buffer is quite screwed up --- can't even save the user-specified
2170 (delete-region (point-min) (point-max))
2171 (insert ses-initial-file-trailer)
2172 (goto-char (point-min)))
2173 ;; Create a blank display area.
2174 (dotimes (row ses--numrows)
2175 (insert ses--blank-line))
2176 (insert ses-print-data-boundary)
2177 (backward-char (1- (length ses-print-data-boundary)))
2178 (setq ses--data-marker (point-marker))
2179 (forward-char (1- (length ses-print-data-boundary)))
2180 ;; Placeholders for cell data.
2181 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2182 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
2184 (insert ses-initial-global-parameters)
2185 (backward-char (1- (length ses-initial-global-parameters)))
2186 (setq ses--params-marker (point-marker))
2187 (forward-char (1- (length ses-initial-global-parameters))))
2188 (ses-set-parameter 'ses--col-widths ses--col-widths)
2189 (ses-set-parameter 'ses--col-printers ses--col-printers)
2190 (ses-set-parameter 'ses--default-printer ses--default-printer)
2191 (ses-set-parameter 'ses--header-row ses--header-row)
2192 (ses-set-parameter 'ses--numrows ses--numrows)
2193 (ses-set-parameter 'ses--numcols ses--numcols)
2194 ;;Keep our old narrowing
2196 (ses-recalculate-all)
2197 (goto-char (point-min)))
2200 ;;----------------------------------------------------------------------------
2201 ;; Input of cell formulas
2202 ;;----------------------------------------------------------------------------
2204 (defun ses-edit-cell (row col newval)
2205 "Display current cell contents in minibuffer, for editing. Returns nil if
2206 cell formula was unsafe and user declined confirmation."
2209 (barf-if-buffer-read-only)
2211 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2214 (formula (ses-cell-formula row col))
2216 (if (eq (car-safe formula) 'ses-safe-formula)
2217 (setq formula (cadr formula)))
2218 (if (eq (car-safe formula) 'quote)
2219 (setq initial (format "'%S" (cadr formula)))
2220 (setq initial (prin1-to-string formula)))
2221 (if (stringp formula)
2222 ;; Position cursor inside close-quote.
2223 (setq initial (cons initial (length initial))))
2225 (read-from-minibuffer (format "Cell %s: " ses--curcell)
2228 t ; Convert to Lisp object.
2229 'ses-read-cell-history)))))
2230 (when (ses-warn-unsafe newval 'unsafep)
2232 (ses-cell-set-formula row col newval)
2235 (defun ses-read-cell (row col newval)
2236 "Self-insert for initial character of cell function."
2238 (let* ((initial (this-command-keys))
2239 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2240 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
2241 (barf-if-buffer-read-only)
2244 (read-from-minibuffer
2245 (format "Cell %s: " ses--curcell)
2246 (cons (if (equal initial "\"") "\"\""
2247 (if (equal initial "(") "()" initial)) 2)
2249 t ; Convert to Lisp object.
2250 'ses-read-cell-history
2251 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2254 (when (ses-edit-cell row col newval)
2255 (ses-command-hook) ; Update cell widths before movement.
2256 (dolist (x ses-after-entry-functions)
2259 (defun ses-read-symbol (row col symb)
2260 "Self-insert for a symbol as a cell formula. The set of all symbols that
2261 have been used as formulas in this spreadsheet is available for completions."
2263 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2265 (barf-if-buffer-read-only)
2266 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2267 ses--symbolic-formulas))
2270 (if (string= newval "")
2271 nil ; Don't create zero-length symbols!
2272 (list 'quote (intern newval))))))
2273 (when (ses-edit-cell row col symb)
2274 (ses-command-hook) ; Update cell widths before movement.
2275 (dolist (x ses-after-entry-functions)
2278 (defun ses-clear-cell-forward (count)
2279 "Delete formula and printer for current cell and then move to next cell.
2280 With prefix, deletes several cells."
2283 (1value (ses-clear-cell-backward (- count)))
2288 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2289 (or rowcol (signal 'end-of-buffer nil))
2290 (ses-clear-cell (car rowcol) (cdr rowcol)))
2293 (defun ses-clear-cell-backward (count)
2294 "Move to previous cell and then delete it. With prefix, deletes several
2298 (1value (ses-clear-cell-forward (- count)))
2299 (ses-check-curcell 'end)
2302 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
2304 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2305 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2308 ;;----------------------------------------------------------------------------
2309 ;; Input of cell-printer functions
2310 ;;----------------------------------------------------------------------------
2312 (defun ses-read-printer (prompt default)
2313 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
2314 PROMPT should end with \": \". Result is t if operation was canceled."
2315 (barf-if-buffer-read-only)
2318 (setq prompt (format "%s [currently %S]: "
2319 (substring prompt 0 -2)
2321 (let ((new (read-from-minibuffer prompt
2322 nil ; Initial contents.
2324 t ; Evaluate the result.
2325 'ses-read-printer-history
2326 (prin1-to-string default))))
2327 (if (equal new default)
2328 ;; User changed mind, decided not to change printer.
2330 (ses-printer-validate new)
2333 (stringp (car-safe new))
2334 (ses-warn-unsafe new 'unsafep-function)
2338 (defun ses-read-cell-printer (newval)
2339 "Set the printer function for the current cell or range.
2341 A printer function is either a string (a format control-string with one
2342 %-sequence -- result from format will be right-justified), or a list of one
2343 string (result from format will be left-justified), or a lambda-expression of
2344 one argument, or a symbol that names a function of one argument. In the
2345 latter two cases, the function's result should be either a string (will be
2346 right-justified) or a list of one string (will be left-justified)."
2350 (ses-check-curcell 'range)
2351 ;;Default is none if not all cells in range have same printer
2352 (catch 'ses-read-cell-printer
2353 (ses-dorange ses--curcell
2354 (setq x (ses-cell-printer row col))
2355 (if (eq (car-safe x) 'ses-safe-printer)
2359 (unless (equal default x)
2360 ;;Range contains differing printer functions
2362 (throw 'ses-read-cell-printer t)))))
2363 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2365 (unless (eq newval t)
2367 (ses-dorange ses--curcell
2368 (ses-set-cell row col 'printer newval)
2369 (ses-print-cell row col))))
2371 (defun ses-read-column-printer (col newval)
2372 "Set the printer function for the current column.
2373 See `ses-read-cell-printer' for input forms."
2375 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2377 (list col (ses-read-printer (format "Column %s printer: "
2378 (ses-column-letter col))
2379 (ses-col-printer col)))))
2381 (unless (eq newval t)
2383 (ses-set-parameter 'ses--col-printers newval col)
2385 (dotimes (row ses--numrows)
2386 (ses-print-cell row col)))))
2388 (defun ses-read-default-printer (newval)
2389 "Set the default printer function for cells that have no other.
2390 See `ses-read-cell-printer' for input forms."
2392 (list (ses-read-printer "Default printer: " ses--default-printer)))
2393 (unless (eq newval t)
2395 (ses-set-parameter 'ses--default-printer newval)
2396 (ses-reprint-all t)))
2399 ;;----------------------------------------------------------------------------
2400 ;; Spreadsheet size adjustments
2401 ;;----------------------------------------------------------------------------
2403 (defun ses-insert-row (count)
2404 "Insert a new row before the current one.
2405 With prefix, insert COUNT rows before current one."
2407 (ses-check-curcell 'end)
2408 (or (> count 0) (signal 'args-out-of-range nil))
2410 (let ((inhibit-quit t)
2411 (inhibit-read-only t)
2412 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2414 ;;Create a new set of cell-variables
2415 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2416 0 (1- ses--numcols))
2417 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2419 (ses-goto-print row 0)
2420 (dotimes-with-progress-reporter (x count) "Inserting row..."
2421 ;;Create a row of empty cells. The `symbol' fields will be set by
2422 ;;the call to ses-relocate-all.
2423 (setq newrow (make-vector ses--numcols nil))
2424 (dotimes (col ses--numcols)
2425 (aset newrow col (ses-make-cell)))
2426 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2427 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2428 (insert ses--blank-line))
2429 ;;Insert empty lines in cell data area (will be replaced by
2431 (ses-goto-data row 0)
2432 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2433 (ses-relocate-all row 0 count 0)
2434 ;;If any cell printers insert constant text, insert that text
2436 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2437 (global (ses-call-printer ses--default-printer)))
2438 (if (or (> (length cols) 0) (> (length global) 0))
2440 (dotimes (col ses--numcols)
2441 ;;These cells are always nil, only constant formatting printed
2442 (1value (ses-print-cell (+ x row) col))))))
2443 (when (> ses--header-row row)
2444 ;;Inserting before header
2445 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2446 (ses-reset-header-string)))
2447 ;;Reconstruct text attributes
2450 (push '(apply ses-widen) buffer-undo-list)
2451 ;;Return to current cell
2453 (ses-jump-safe ses--curcell)
2454 (ses-goto-print (1- ses--numrows) 0)))
2456 (defun ses-delete-row (count)
2457 "Delete the current row.
2458 With prefix, deletes COUNT rows starting from the current one."
2461 (or (> count 0) (signal 'args-out-of-range nil))
2462 (let ((inhibit-quit t)
2463 (inhibit-read-only t)
2464 (row (car (ses-sym-rowcol ses--curcell))))
2465 (setq count (min count (- ses--numrows row)))
2467 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2468 ;;Delete lines from print area
2469 (ses-goto-print row 0)
2470 (ses-delete-line count)
2471 ;;Delete lines from cell data area
2472 (ses-goto-data row 0)
2473 (ses-delete-line (* count (1+ ses--numcols)))
2474 ;;Relocate variables and formulas
2475 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2476 (ses-relocate-all row 0 (- count) 0)
2477 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2478 0 (1- ses--numcols))
2479 (when (> ses--header-row row)
2480 (if (<= ses--header-row (+ row count))
2481 ;;Deleting the header row
2482 (ses-set-parameter 'ses--header-row 0)
2483 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2484 (ses-reset-header-string)))
2485 ;;Reconstruct attributes
2488 (push '(apply ses-widen) buffer-undo-list)
2489 (ses-jump-safe ses--curcell))
2491 (defun ses-insert-column (count &optional col width printer)
2492 "Insert a new column before COL (default is the current one).
2493 With prefix, insert COUNT columns before current one.
2494 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2495 \(otherwise they're taken from the current column)."
2498 (or (> count 0) (signal 'args-out-of-range nil))
2500 (setq col (cdr (ses-sym-rowcol ses--curcell))
2501 width (ses-col-width col)
2502 printer (ses-col-printer col)))
2504 (let ((inhibit-quit t)
2505 (inhibit-read-only t)
2506 (widths ses--col-widths)
2507 (printers ses--col-printers)
2509 ;;Create a new set of cell-variables
2510 (ses-create-cell-variable-range 0 (1- ses--numrows)
2511 ses--numcols (+ ses--numcols count -1))
2512 ;;Insert each column.
2513 (dotimes-with-progress-reporter (x count) "Inserting column..."
2514 ;;Create a column of empty cells. The `symbol' fields will be set by
2515 ;;the call to ses-relocate-all.
2516 (ses-adjust-print-width col (1+ width))
2517 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2518 (dotimes (row ses--numrows)
2519 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2520 ;;Inserting in the middle of a spill-over
2522 (ses-aset-with-undo ses--cells row
2523 (ses-vector-insert (aref ses--cells row)
2524 col (ses-make-cell)))
2525 ;;Insert empty lines in cell data area (will be replaced by
2527 (ses-goto-data row col)
2529 ;; Insert column width and printer.
2530 (setq widths (ses-vector-insert widths col width)
2531 printers (ses-vector-insert printers col printer)))
2532 (ses-set-parameter 'ses--col-widths widths)
2533 (ses-set-parameter 'ses--col-printers printers)
2534 (ses-reset-header-string)
2535 (ses-relocate-all 0 col 0 count)
2538 (when (or (> (length (ses-call-printer printer)) 0)
2539 (> (length (ses-call-printer ses--default-printer)) 0))
2540 ;; Either column printer or global printer inserts some constant text.
2541 ;; Reprint the new columns to insert that text.
2542 (dotimes (x ses--numrows)
2544 ;; Always nil here --- this is a blank column.
2545 (1value (ses-print-cell-new-width x (+ y col))))))
2547 (ses-jump-safe ses--curcell))
2549 (defun ses-delete-column (count)
2550 "Delete the current column.
2551 With prefix, deletes COUNT columns starting from the current one."
2554 (or (> count 0) (signal 'args-out-of-range nil))
2555 (let ((inhibit-quit t)
2556 (inhibit-read-only t)
2557 (rowcol (ses-sym-rowcol ses--curcell))
2559 col origrow has-skip)
2560 (setq origrow (car rowcol)
2562 count (min count (- ses--numcols col)))
2563 (if (= count ses--numcols)
2564 (error "Can't delete all columns!"))
2565 ;;Determine width of column(s) being deleted
2567 (setq width (+ width (ses-col-width (+ col x)) 1)))
2569 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2570 (ses-adjust-print-width col (- width))
2571 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2572 ;;Delete lines from cell data area
2573 (ses-goto-data row col)
2574 (ses-delete-line count)
2575 ;;Delete cells. Check if deletion area begins or ends with a skip.
2576 (if (or (eq (ses-cell-value row col) '*skip*)
2577 (and (< col ses--numcols)
2578 (eq (ses-cell-value row (+ col count)) '*skip*)))
2580 (ses-aset-with-undo ses--cells row
2581 (ses-vector-delete (aref ses--cells row) col count)))
2583 (ses-set-parameter 'ses--col-widths
2584 (ses-vector-delete ses--col-widths col count))
2585 (ses-set-parameter 'ses--col-printers
2586 (ses-vector-delete ses--col-printers col count))
2587 (ses-reset-header-string)
2588 ;;Relocate variables and formulas
2589 (ses-relocate-all 0 col 0 (- count))
2590 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2591 ses--numcols (+ ses--numcols count -1))
2595 (if (>= col ses--numcols)
2596 (setq col (1- col)))
2597 (ses-goto-print origrow col)))
2599 (defun ses-forward-or-insert (&optional count)
2600 "Move to next cell in row, or inserts a new cell if already in last one, or
2601 inserts a new row if at bottom of print area. Repeat COUNT times."
2603 (ses-check-curcell 'end)
2604 (setq deactivate-mark t) ; Doesn't combine well with ranges.
2607 (if (not ses--curcell)
2608 (progn ; At bottom of print area.
2609 (barf-if-buffer-read-only)
2611 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2613 (char-before (next-single-property-change (point)
2615 ;; We're already in last nonskipped cell on line. Need to create a
2617 (barf-if-buffer-read-only)
2618 (ses-insert-column (- count x)
2621 (ses-col-printer col)))))
2624 (defun ses-append-row-jump-first-column ()
2625 "Insert a new row after current one and jump to its first column."
2629 (beginning-of-line 2)
2633 (defun ses-set-column-width (col newwidth)
2634 "Set the width of the current column."
2636 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2637 (barf-if-buffer-read-only)
2639 (if current-prefix-arg
2640 (prefix-numeric-value current-prefix-arg)
2641 (read-from-minibuffer (format "Column %s width [currently %d]: "
2642 (ses-column-letter col)
2643 (ses-col-width col))
2644 nil ; No initial contents.
2645 nil ; No override keymap.
2646 t ; Convert to Lisp object.
2649 (ses-col-width col))))))) ; Default value.
2651 (error "Invalid column width"))
2653 (ses-reset-header-string)
2655 (let ((inhibit-quit t))
2656 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2657 (ses-set-parameter 'ses--col-widths newwidth col))
2658 (dotimes (row ses--numrows)
2659 (ses-print-cell-new-width row col))))
2662 ;;----------------------------------------------------------------------------
2663 ;; Cut and paste, import and export
2664 ;;----------------------------------------------------------------------------
2666 (defadvice copy-region-as-kill (around ses-copy-region-as-kill
2667 activate preactivate)
2668 "It doesn't make sense to copy read-only or intangible attributes into the
2669 kill ring. It probably doesn't make sense to copy keymap properties.
2670 We'll assume copying front-sticky properties doesn't make sense, either.
2672 This advice also includes some SES-specific code because otherwise it's too
2673 hard to override how mouse-1 works."
2678 (if (not (and (eq major-mode 'ses-mode)
2679 (eq (get-text-property beg 'read-only) 'ses)
2680 (eq (get-text-property (1- end) 'read-only) 'ses)))
2681 ad-do-it ; Normal copy-region-as-kill.
2682 (kill-new (ses-copy-region beg end))
2683 (if transient-mark-mode
2684 (setq deactivate-mark t))
2687 (defun ses-copy-region (beg end)
2688 "Treat the region as rectangular. Convert the intangible attributes to
2689 SES attributes recording the contents of the cell as of the time of copying."
2690 (when (= end ses--data-marker)
2691 ;;Avoid overflow situation
2692 (setq end (1- ses--data-marker)))
2693 (let* ((inhibit-point-motion-hooks t)
2694 (x (mapconcat 'ses-copy-region-helper
2695 (extract-rectangle beg (1- end)) "\n")))
2696 (remove-text-properties 0 (length x)
2704 (defun ses-copy-region-helper (line)
2705 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2706 external form by attaching to each print cell a 'ses attribute that records
2707 the corresponding data cell."
2708 (or (> (length line) 1)
2709 (error "Empty range"))
2710 (let ((inhibit-read-only t)
2712 mycell next sym rowcol)
2714 (setq sym (get-text-property pos 'intangible line)
2715 next (next-single-property-change pos 'intangible line)
2716 rowcol (ses-sym-rowcol sym)
2717 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2718 (put-text-property pos (or next (length line))
2720 (list (ses-cell-symbol mycell)
2721 (ses-cell-formula mycell)
2722 (ses-cell-printer mycell))
2727 (defun ses-kill-override (beg end)
2728 "Generic override for any commands that kill text.
2729 We clear the killed cells instead of deleting them."
2731 (ses-check-curcell 'needrange)
2732 ;; For some reason, the text-read-only error is not caught by `delete-region',
2733 ;; so we have to use subterfuge.
2734 (let ((buffer-read-only t))
2735 (1value (condition-case x
2736 (noreturn (funcall (lookup-key (current-global-map)
2737 (this-command-keys))
2739 (buffer-read-only nil)))) ; The expected error.
2740 ;; Because the buffer was marked read-only, the kill command turned itself
2741 ;; into a copy. Now we clear the cells or signal the error. First we check
2742 ;; whether the buffer really is read-only.
2743 (barf-if-buffer-read-only)
2745 (ses-dorange ses--curcell
2746 (ses-clear-cell row col))
2747 (ses-jump (car ses--curcell)))
2749 (defadvice yank (around ses-yank activate preactivate)
2750 "In SES mode, the yanked text is inserted as cells.
2752 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2753 SES buffer), the formulas and print functions are restored for the cells. If
2754 the text contains tabs, this is an insertion of tab-separated formulas.
2755 Otherwise the text is inserted as the formula for the current cell.
2757 When inserting cells, the formulas are usually relocated to keep the same
2758 relative references to neighboring cells. This is best if the formulas
2759 generally refer to other cells within the yanked text. You can use the C-u
2760 prefix to specify insertion without relocation, which is best when the
2761 formulas refer to cells outside the yanked text.
2763 When inserting formulas, the text is treated as a string constant if it doesn't
2764 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2765 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2767 (if (not (and (eq major-mode 'ses-mode)
2768 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2769 ad-do-it ; Normal non-SES yank.
2770 (ses-check-curcell 'end)
2772 (let ((text (current-kill (cond
2776 (or (ses-yank-cells text arg)
2777 (ses-yank-tsf text arg)
2778 (ses-yank-one (ses-yank-resize 1 1)
2781 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2782 ;; Just one cell --- delete final tab or newline.
2786 (exchange-point-and-mark))))
2788 (defun ses-yank-pop (arg)
2789 "Replace just-yanked stretch of killed text with a different stretch.
2790 This command is allowed only immediately after a `yank' or a `yank-pop',
2791 when the region contains a stretch of reinserted previously-killed text.
2792 We replace it with a different stretch of killed text.
2793 Unlike standard `yank-pop', this function uses `undo' to delete the
2794 previous insertion."
2796 (or (eq last-command 'yank)
2797 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2799 (noreturn (error "Previous command was not a yank")))
2802 (yank (1+ (or arg 1)))
2803 (setq this-command 'yank))
2805 (defun ses-yank-cells (text arg)
2806 "If the TEXT has a proper set of 'ses attributes, insert the text as
2807 cells, else return nil. The cells are reprinted--the supplied text is
2808 ignored because the column widths, default printer, etc. at yank time might
2809 be different from those at kill-time. ARG is a list to indicate that
2810 formulas are to be inserted without relocation."
2811 (let ((first (get-text-property 0 'ses text))
2812 (last (get-text-property (1- (length text)) 'ses text)))
2813 (when (and first last) ;;Otherwise not proper set of attributes
2814 (setq first (ses-sym-rowcol (car first))
2815 last (ses-sym-rowcol (car last)))
2816 (let* ((needrows (- (car last) (car first) -1))
2817 (needcols (- (cdr last) (cdr first) -1))
2818 (rowcol (ses-yank-resize needrows needcols))
2819 (rowincr (- (car rowcol) (car first)))
2820 (colincr (- (cdr rowcol) (cdr first)))
2823 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2824 (setq myrow (+ row (car rowcol)))
2825 (dotimes (col needcols)
2826 (setq mycol (+ col (cdr rowcol))
2827 last (get-text-property pos 'ses text)
2828 pos (next-single-property-change pos 'ses text)
2829 x (ses-sym-rowcol (car last)))
2831 ;; Newline --- all remaining cells on row are skipped.
2832 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2833 last (list nil nil nil)
2835 (if (/= (car x) (- myrow rowincr))
2836 (error "Cell row error"))
2837 (if (< (- mycol colincr) (cdr x))
2838 ;; Some columns were skipped.
2839 (let ((oldcol mycol))
2840 (while (< (- mycol colincr) (cdr x))
2841 (ses-clear-cell myrow mycol)
2844 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
2845 (when (car last) ; Skip this for *skip* cells.
2846 (setq x (nth 2 last))
2847 (unless (equal x (ses-cell-printer myrow mycol))
2850 (eq (car-safe x) 'ses-safe-printer)
2851 (setq x `(ses-safe-printer ,x)))
2852 (ses-set-cell myrow mycol 'printer x))
2853 (setq x (cadr last))
2855 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2857 (eq (car-safe x) 'ses-safe-formula)
2858 (setq x `(ses-safe-formula ,x)))
2859 (ses-cell-set-formula myrow mycol x)))
2861 (if (get-text-property pos 'ses text)
2862 (error "Missing newline between rows"))
2863 (setq pos (next-single-property-change pos 'ses text))))
2866 (defun ses-yank-one (rowcol text from to arg)
2867 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2868 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2869 (let ((val (condition-case nil
2870 (read-from-string text from to)
2871 (error (cons nil from)))))
2873 ((< (cdr val) (or to (length text)))
2874 ;; Invalid sexp --- leave it as a string.
2875 (setq val (substring text from to)))
2876 ((and (car val) (symbolp (car val)))
2878 (setq val (list 'quote (car val))) ; Keep symbol.
2879 (setq val (substring text from to)))) ; Treat symbol as text.
2881 (setq val (car val))))
2882 (let ((row (car rowcol))
2885 (setq val `(ses-safe-formula ,val)))
2886 (ses-cell-set-formula row col val))))
2888 (defun ses-yank-tsf (text arg)
2889 "If TEXT contains tabs and/or newlines, treat the tabs as
2890 column-separators and the newlines as row-separators and insert the text as
2891 cell formulas--else return nil. Treat plain symbols as strings unless ARG
2892 is a list. Ignore a final newline."
2893 (if (or (not (string-match "[\t\n]" text))
2894 (= (match-end 0) (length text)))
2897 (if (/= (aref text (1- (length text))) ?\n)
2898 (setq text (concat text "\n")))
2904 ;;Find all the tabs and newlines
2905 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
2907 (setq cols (1+ cols))
2908 (when (eq (aref text pos) ?\n)
2910 (setq needcols cols)
2911 (or (= needcols cols)
2912 (error "Inconsistent row lengths")))
2914 needrows (1+ needrows))))
2915 ;;Insert the formulas
2916 (setq rowcol (ses-yank-resize needrows needcols))
2917 (dotimes (row needrows)
2918 (dotimes (col needcols)
2919 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
2920 (+ (cdr rowcol) needcols (- col) -1))
2921 text (1+ (cadr spots)) (car spots) arg)
2922 (setq spots (cdr spots))))
2923 (ses-goto-print (+ (car rowcol) needrows -1)
2924 (+ (cdr rowcol) needcols -1))
2927 (defun ses-yank-resize (needrows needcols)
2928 "If this yank will require inserting rows and/or columns, ask for
2929 confirmation and then insert them. Result is (row,col) for top left of yank
2930 spot, or error signal if user requests cancel."
2932 (let ((rowcol (if ses--curcell
2933 (ses-sym-rowcol ses--curcell)
2934 (cons ses--numrows 0)))
2936 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
2937 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
2938 rowbool (> needrows 0)
2939 colbool (> needcols 0))
2940 (when (or rowbool colbool)
2941 ;;Need to insert. Get confirm
2942 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
2943 (if rowbool (format "%d rows" needrows) "")
2944 (if (and rowbool colbool) " and " "")
2945 (if colbool (format "%d columns" needcols) "")))
2946 (error "Cancelled"))
2950 (ses-goto-print ses--numrows 0)
2951 (ses-insert-row needrows))))
2953 (ses-insert-column needcols
2955 (ses-col-width (1- ses--numcols))
2956 (ses-col-printer (1- ses--numcols)))))
2959 (defun ses-export-tsv (beg end)
2960 "Export values from the current range, with tabs between columns and
2961 newlines between rows. Result is placed in kill ring."
2963 (ses-export-tab nil))
2965 (defun ses-export-tsf (beg end)
2966 "Export formulas from the current range, with tabs between columns and
2967 newlines between rows. Result is placed in kill ring."
2971 (defun ses-export-tab (want-formulas)
2972 "Export the current range with tabs between columns and newlines between rows.
2973 Result is placed in kill ring. The export is values unless WANT-FORMULAS
2974 is non-nil. Newlines and tabs in the export text are escaped."
2975 (ses-check-curcell 'needrange)
2976 (let ((print-escape-newlines t)
2978 (ses-dorange ses--curcell
2979 (setq item (if want-formulas
2980 (ses-cell-formula row col)
2981 (ses-cell-value row col)))
2982 (if (eq (car-safe item) 'ses-safe-formula)
2983 ;;Hide our deferred safety-check marker
2984 (setq item (cadr item)))
2985 (if (or (not item) (eq item '*skip*))
2987 (when (eq (car-safe item) 'quote)
2989 (setq item (cadr item)))
2990 (setq item (prin1-to-string item t))
2991 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
2997 (push "\n" result))))
2998 (setq result (apply 'concat (nreverse result)))
3002 ;;----------------------------------------------------------------------------
3003 ;; Other user commands
3004 ;;----------------------------------------------------------------------------
3006 (defun ses-unset-header-row ()
3007 "Select the default header row."
3009 (ses-set-header-row 0))
3011 (defun ses-set-header-row (row)
3012 "Set the ROW to display in the header-line.
3013 With a numerical prefix arg, use that row.
3014 With no prefix arg, use the current row.
3015 With a \\[universal-argument] prefix arg, prompt the user.
3016 The top row is row 1. Selecting row 0 displays the default header row."
3018 (list (if (numberp current-prefix-arg) current-prefix-arg
3019 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3020 (if current-prefix-arg
3021 (read-number "Header row: " currow)
3023 (if (or (< row 0) (> row ses--numrows))
3024 (error "Invalid header-row"))
3026 (let ((oldval ses--header-row))
3027 (let (buffer-undo-list)
3028 (ses-set-parameter 'ses--header-row row))
3029 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
3030 (ses-reset-header-string))
3032 (defun ses-mark-row ()
3033 "Mark the entirety of current row as a range."
3035 (ses-check-curcell 'range)
3036 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
3038 (ses-goto-print (1+ row) 0)
3039 (push-mark (point) nil t)
3040 (ses-goto-print row 0)))
3042 (defun ses-mark-column ()
3043 "Mark the entirety of current column as a range."
3045 (ses-check-curcell 'range)
3046 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
3049 (ses-goto-print (1- ses--numrows) col)
3051 (push-mark (point) nil t)
3052 (while (eq '*skip* (ses-cell-value row col))
3053 ;;Skip over initial cells in column that can't be selected
3054 (setq row (1+ row)))
3055 (ses-goto-print row col)))
3057 (defun ses-end-of-line ()
3058 "Move point to last cell on line."
3060 (ses-check-curcell 'end 'range)
3061 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3063 (let ((col (1- ses--numcols))
3065 (if (symbolp ses--curcell)
3067 (setq row (car (ses-sym-rowcol ses--curcell)))
3068 ;; Range --- use whichever end of the range the point is at.
3069 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
3071 (cdr ses--curcell))))
3072 ;; If range already includes the last cell in a row, point is actually
3073 ;; in the following row.
3074 (if (<= (cdr rowcol) (1- col))
3075 (setq row (car rowcol))
3076 (setq row (1+ (car rowcol)))
3077 (if (= row ses--numrows)
3078 ;;Already at end - can't go anywhere
3080 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
3081 (while (eq (ses-cell-value row col) '*skip*)
3082 ;; Back to beginning of multi-column cell.
3083 (setq col (1- col)))
3084 (ses-goto-print row col)))))
3086 (defun ses-renarrow-buffer ()
3087 "Narrow the buffer so only the print area is visible.
3088 Use after \\[widen]."
3090 (setq ses--deferred-narrow t))
3092 (defun ses-sort-column (sorter &optional reverse)
3093 "Sort the range by a specified column.
3094 With prefix, sorts in REVERSE order."
3095 (interactive "*sSort column: \nP")
3096 (ses-check-curcell 'needrange)
3097 (let ((min (ses-sym-rowcol (car ses--curcell)))
3098 (max (ses-sym-rowcol (cdr ses--curcell))))
3099 (let ((minrow (car min))
3104 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3105 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3106 (error "Invalid sort column"))
3107 ;;Get key columns and sort them
3108 (dotimes (x (- maxrow minrow -1))
3109 (ses-goto-print (+ minrow x) sorter)
3110 (setq end (next-single-property-change (point) 'intangible))
3111 (push (cons (buffer-substring-no-properties (point) end)
3114 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3115 ;;Extract the lines in reverse sorted order
3117 (setq keys (nreverse keys)))
3119 (ses-goto-print (cdr x) (1+ maxcol))
3121 (ses-goto-print (cdr x) mincol)
3122 (push (ses-copy-region (point) end) extracts))
3124 ;;Paste the lines sequentially
3125 (dotimes (x (- maxrow minrow -1))
3126 (ses-goto-print (+ minrow x) mincol)
3128 (ses-yank-cells (pop extracts) nil)))))
3130 (defun ses-sort-column-click (event reverse)
3131 "Mouse version of `ses-sort-column'."
3132 (interactive "*e\nP")
3133 (setq event (event-end event))
3134 (select-window (posn-window event))
3135 (setq event (car (posn-col-row event))) ; Click column.
3137 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3138 (setq event (- event (ses-col-width col) 1)
3140 (if (>= col ses--numcols)
3142 (ses-sort-column (ses-column-letter col) reverse))))
3144 (defun ses-insert-range ()
3145 "Insert into minibuffer the list of cells currently highlighted in the
3149 (with-current-buffer (window-buffer minibuffer-scroll-window)
3150 (ses-command-hook) ; For ses-coverage.
3151 (ses-check-curcell 'needrange)
3152 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3153 ,(cdr ses--curcell))))))
3154 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3156 (defun ses-insert-ses-range ()
3157 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
3158 highlighted range in the spreadsheet."
3161 (with-current-buffer (window-buffer minibuffer-scroll-window)
3162 (ses-command-hook) ; For ses-coverage.
3163 (ses-check-curcell 'needrange)
3164 (setq x (format "(ses-range %S %S)"
3166 (cdr ses--curcell))))
3169 (defun ses-insert-range-click (event)
3170 "Mouse version of `ses-insert-range'."
3172 (mouse-set-point event)
3175 (defun ses-insert-ses-range-click (event)
3176 "Mouse version of `ses-insert-ses-range'."
3178 (mouse-set-point event)
3179 (ses-insert-ses-range))
3181 (defun ses-replace-name-in-formula (formula old-name new-name)
3182 (let ((new-formula formula))
3183 (unless (and (consp formula)
3184 (eq (car-safe formula) 'quote))
3186 (let ((elt (car-safe formula)))
3189 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3191 (eq (car-safe formula) old-name))
3192 (setcar formula new-name))))
3193 (setq formula (cdr formula))))
3196 (defun ses-rename-cell (new-name)
3197 "Rename current cell."
3198 (interactive "*SEnter new name: ")
3201 (and (local-variable-p new-name)
3202 (ses-sym-rowcol new-name)
3203 ;; this test is needed because ses-cell property of deleted cells
3204 ;; is not deleted in case of subsequent undo
3205 (memq new-name ses--renamed-cell-symb-list)
3206 (error "Already a cell name"))
3207 (and (boundp new-name)
3208 (null (yes-or-no-p (format "`%S' is already bound outside this buffer, continue? "
3210 (error "Already a bound cell name")))
3211 (let* ((rowcol (ses-sym-rowcol ses--curcell))
3214 (cell (ses-get-cell row col)))
3215 (put new-name 'ses-cell rowcol)
3216 ;; Replace name by new name in formula of cells referring to renamed cell.
3217 (dolist (ref (ses-cell-references cell))
3218 (let* ((x (ses-sym-rowcol ref))
3219 (xcell (ses-get-cell (car x) (cdr x))))
3220 (ses-cell-set-formula (car rowcol)
3222 (ses-replace-name-in-formula
3223 (ses-cell-formula xcell)
3226 ;; replace name by new name in reference list of cells to which renamed cell refers to
3227 (dolist (ref (ses-formula-references (ses-cell-formula cell)))
3228 (let* ((x (ses-sym-rowcol ref))
3231 (ses-set-cell xrow xcol 'references
3232 (cons new-name (delq ses--curcell
3233 (ses-cell-references xrow xcol))))))
3234 (push new-name ses--renamed-cell-symb-list)
3235 (set new-name (symbol-value ses--curcell))
3236 (aset cell 0 new-name)
3237 (put ses--curcell 'ses-cell nil)
3238 (makunbound ses--curcell)
3239 (setq ses--curcell new-name)
3240 (let* ((pos (point))
3241 (inhibit-read-only t)
3242 (col (current-column))
3243 (end (save-excursion
3244 (move-to-column (1+ col))
3246 (+ pos (ses-col-width col) 1)
3248 (put-text-property pos end 'intangible new-name))) )
3250 ;;----------------------------------------------------------------------------
3251 ;; Checking formulas for safety
3252 ;;----------------------------------------------------------------------------
3254 (defun ses-safe-printer (printer)
3255 "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
3256 (if (or (stringp printer)
3257 (stringp (car-safe printer))
3259 (ses-warn-unsafe printer 'unsafep-function))
3263 (defun ses-safe-formula (formula)
3264 "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
3265 (if (ses-warn-unsafe formula 'unsafep)
3267 `(ses-unsafe ',formula)))
3269 (defun ses-warn-unsafe (formula checker)
3270 "Apply CHECKER to FORMULA.
3271 If result is non-nil, asks user for confirmation about FORMULA,
3272 which might be unsafe. Returns t if formula is safe or user allows
3273 execution anyway. Always returns t if `safe-functions' is t."
3274 (if (eq safe-functions t)
3276 (setq checker (funcall checker formula))
3279 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3280 formula checker)))))
3283 ;;----------------------------------------------------------------------------
3284 ;; Standard formulas
3285 ;;----------------------------------------------------------------------------
3287 (defun ses--clean-! (&rest x)
3288 "Clean by `delq' list X from any occurrence of `nil' or `*skip*'."
3289 (delq nil (delq '*skip* x)))
3291 (defun ses--clean-_ (x y)
3292 "Clean list X by replacing by Y any occurrence of `nil' or `*skip*'.
3294 This will change X by making `setcar' on its cons cells."
3295 (let ((ret x) ret-elt)
3297 (setq ret-elt (car ret))
3298 (when (memq ret-elt '(nil *skip*))
3300 (setq ret (cdr ret))))
3303 (defmacro ses-range (from to &rest rest)
3304 "Expand to a list of cell-symbols for the range going from
3305 FROM up to TO. The range automatically expands to include any
3306 new row or column inserted into its middle. The SES library code
3307 specifically looks for the symbol `ses-range', so don't create an
3308 alias for this macro!
3310 By passing in REST some flags one can configure the way the range
3311 is read and how it is formatted.
3313 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3316 Readout direction is specified by a `>v', '`>^', `<v', `<^',
3317 `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3318 of such a flag, a default direction of `^<' is assumed. This
3319 way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3320 while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3322 If the range is one row, then `>' can be used as a shorthand to
3323 `>v' or `>^', and `<' to `<v' or `<^'.
3325 If the range is one column, then `v' can be used as a shorthand to
3326 `v>' or `v<', and `^' to `^>' or `v<'.
3328 A `!' flag will remove all cells whose value is nil or `*skip*'.
3330 A `_' flag will replace nil or `*skip*' by the value following
3331 the `_' flag. If the `_' flag is the last argument, then they are
3332 replaced by integer 0.
3334 A `*', `*1' or `*2' flag will vectorize the range in the sense of
3335 Calc. See info node `(Calc) Top'. Flag `*' will output either a
3336 vector or a matrix depending on the number of rows, `*1' will
3337 flatten the result to a one row vector, and `*2' will make a
3338 matrix whatever the number of rows.
3340 Warning: interaction with Calc is experimental and may produce
3341 confusing results if you are not aware of Calc data format.
3342 Use `math-format-value' as a printer for Calc objects."
3350 (ses-dorange (cons from to)
3351 (when (/= prev-row row)
3352 (push result-row result)
3353 (setq result-row nil))
3354 (push (ses-cell-symbol row col) result-row)
3355 (setq prev-row row))
3356 (push result-row result)
3358 (let ((x (pop rest)))
3360 (`>v (setq transpose nil reorient-x nil reorient-y nil))
3361 (`>^ (setq transpose nil reorient-x nil reorient-y t))
3362 (`<^ (setq transpose nil reorient-x t reorient-y t))
3363 (`<v (setq transpose nil reorient-x t reorient-y nil))
3364 (`v> (setq transpose t reorient-x nil reorient-y t))
3365 (`^> (setq transpose t reorient-x nil reorient-y nil))
3366 (`^< (setq transpose t reorient-x t reorient-y nil))
3367 (`v< (setq transpose t reorient-x t reorient-y t))
3368 ((or `* `*2 `*1) (setq vectorize x))
3369 (`! (setq clean 'ses--clean-!))
3370 (`_ (setq clean `(lambda (&rest x)
3371 (ses--clean-_ x ,(if rest (pop rest) 0)))))
3374 ; shorthands one row
3375 ((and (null (cddr result)) (memq x '(> <)))
3376 (push (intern (concat (symbol-name x) "v")) rest))
3377 ; shorthands one col
3378 ((and (null (cdar result)) (memq x '(v ^)))
3379 (push (intern (concat (symbol-name x) ">")) rest))
3380 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3382 (setcdr (last result 2) nil)
3383 (setq result (cdr (nreverse result))))
3385 (setq result (mapcar 'nreverse result)))
3387 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3390 (dolist (elt (pop result))
3391 (setcar iter (cons elt (car iter)))
3392 (setq iter (cdr iter))))
3395 (cl-flet ((vectorize-*1
3397 (cons clean (cons (quote 'vec) (apply 'append result))))
3400 (cons clean (cons (quote 'vec)
3402 (cons clean (cons (quote 'vec) x)))
3405 (`nil (cons clean (apply 'append result)))
3406 (`*1 (vectorize-*1 clean result))
3407 (`*2 (vectorize-*2 clean result))
3408 (`* (funcall (if (cdr result)
3413 (defun ses-delete-blanks (&rest args)
3414 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3417 (unless (memq cur '(nil *skip*))
3421 (defun ses+ (&rest args)
3422 "Compute the sum of the arguments, ignoring blanks."
3423 (apply '+ (apply 'ses-delete-blanks args)))
3425 (defun ses-average (list)
3426 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3427 are ignored. Result is always floating-point, even if all args are integers."
3428 (setq list (apply 'ses-delete-blanks list))
3429 (/ (float (apply '+ list)) (length list)))
3431 (defmacro ses-select (fromrange test torange)
3432 "Select cells in FROMRANGE that are `equal' to TEST.
3433 For each match, return the corresponding cell from TORANGE.
3434 The ranges are macroexpanded but not evaluated so they should be
3435 either (ses-range BEG END) or (list ...). The TEST is evaluated."
3436 (setq fromrange (cdr (macroexpand fromrange))
3437 torange (cdr (macroexpand torange))
3439 (or (= (length fromrange) (length torange))
3440 (error "ses-select: Ranges not same length"))
3442 (dolist (x fromrange)
3443 (if (equal test (symbol-value x))
3444 (push (car torange) result))
3445 (setq torange (cdr torange)))
3446 (cons 'list result)))
3448 ;;All standard formulas are safe
3449 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3451 (put x 'side-effect-free t))
3454 ;;----------------------------------------------------------------------------
3455 ;; Standard print functions
3456 ;;----------------------------------------------------------------------------
3458 ;; These functions use the variables 'row' and 'col' that are dynamically bound
3459 ;; by ses-print-cell. We define these variables at compile-time to make the
3464 (defun ses-center (value &optional span fill)
3465 "Print VALUE, centered within column.
3466 FILL is the fill character for centering (default = space).
3467 SPAN indicates how many additional rightward columns to include
3468 in width (default = 0)."
3469 (let ((printer (or (ses-col-printer col) ses--default-printer))
3470 (width (ses-col-width col))
3472 (or fill (setq fill ?\s))
3473 (or span (setq span 0))
3474 (setq value (ses-call-printer printer value))
3476 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
3477 ;; Set column width.
3478 (setq width (- width (string-width value)))
3480 value ; Too large for field, anyway.
3481 (setq half (make-string (/ width 2) fill))
3482 (concat half value half
3483 (if (> (% width 2) 0) (char-to-string fill))))))
3485 (defun ses-center-span (value &optional fill)
3486 "Print VALUE, centered within the span that starts in the current column
3487 and continues until the next nonblank column.
3488 FILL specifies the fill character (default = space)."
3489 (let ((end (1+ col)))
3490 (while (and (< end ses--numcols)
3491 (memq (ses-cell-value row end) '(nil *skip*)))
3492 (setq end (1+ end)))
3493 (ses-center value (- end col 1) fill)))
3495 (defun ses-dashfill (value &optional span)
3496 "Print VALUE centered using dashes.
3497 SPAN indicates how many rightward columns to include in width (default = 0)."
3498 (ses-center value span ?-))
3500 (defun ses-dashfill-span (value)
3501 "Print VALUE, centered using dashes within the span that starts in the
3502 current column and continues until the next nonblank column."
3503 (ses-center-span value ?-))
3505 (defun ses-tildefill-span (value)
3506 "Print VALUE, centered using tildes within the span that starts in the
3507 current column and continues until the next nonblank column."
3508 (ses-center-span value ?~))
3510 (defun ses-unsafe (value)
3511 "Substitute for an unsafe formula or printer."
3512 (error "Unsafe formula or printer"))
3514 ;;All standard printers are safe, including ses-unsafe!
3515 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3516 (put x 'side-effect-free t))
3518 (defun ses-unload-function ()
3519 "Unload the Simple Emacs Spreadsheet."
3520 (dolist (fun '(copy-region-as-kill yank))
3521 (ad-remove-advice fun 'around (intern (concat "ses-" (symbol-name fun))))
3523 ;; continue standard unloading
3528 ;;; ses.el ends here