1 ;;; ses.el -- Simple Emacs Spreadsheet -*- coding: utf-8 -*-
3 ;; Copyright (C) 2002-2014 Free Software Foundation, Inc.
5 ;; Author: Jonathan Yavner <jyavner@member.fsf.org>
6 ;; Maintainer: Vincent Belaïche <vincentb1@users.sourceforge.net>
7 ;; Keywords: spreadsheet Dijkstra
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; * split (catch 'cycle ...) call back into one or more functions
29 ;; * Use $ or … for truncated fields
30 ;; * Add command to make a range of columns be temporarily invisible.
31 ;; * Allow paste of one cell to a range of cells -- copy formula to each.
32 ;; * Do something about control characters & octal codes in cell print
33 ;; areas. Use string-width?
34 ;; * Input validation functions. How specified?
35 ;; * Faces (colors & styles) in print cells.
36 ;; * Move a column by dragging its letter in the header line.
37 ;; * Left-margin column for row number.
38 ;; * Move a row by dragging its number in the left-margin.
42 ;; Cycles used to be detected by stationarity of ses--deferred-recalc. This was
43 ;; working fine in most cases, however failed in some cases of several path
46 ;; The current algorithm is based on Dijkstra's algorithm. The cycle length is
47 ;; stored in some cell property. In order not to reset in all cells such
48 ;; property at each update, the cycle length is stored in this property along
49 ;; with some update attempt id that is incremented at each update. The current
50 ;; update id is ses--Dijkstra-attempt-nb. In case there is a cycle the cycle
51 ;; length diverge to infinite so it will exceed ses--Dijkstra-weight-bound at
52 ;; some point of time that allows detection. Otherwise it converges to the
53 ;; longest path length in the update tree.
59 (eval-when-compile (require 'cl-lib
))
62 ;;----------------------------------------------------------------------------
63 ;; User-customizable variables
64 ;;----------------------------------------------------------------------------
67 "Simple Emacs Spreadsheet."
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--named-cell-hashmap
282 (ses--header-hscroll . -1) ; Flag for "initial recalc needed"
283 ses--header-row ses--header-string ses--linewidth
284 ses--numcols ses--numrows ses--symbolic-formulas
285 ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
286 ses--Dijkstra-weight-bound
287 ;; This list is useful to speed-up clean-up of symbols when
288 ;; an area containing renamed cell is deleted.
289 ses--renamed-cell-symb-list
290 ;; Global variables that we override
291 mode-line-process next-line-add-newlines transient-mark-mode)
292 "Buffer-local variables used by SES.")
294 (defun ses-set-localvars ()
295 "Set buffer-local and initialize some SES variables."
296 (dolist (x ses-localvars)
299 (set (make-local-variable x) nil))
301 (set (make-local-variable (car x)) (cdr x)))
302 (t (error "Unexpected elements `%S' in list `ses-localvars'" x))))))
304 (eval-when-compile ; silence compiler
307 ;;; This variable is documented as being permitted in file-locals:
308 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
310 (defconst ses-paramlines-plist
311 '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
312 ses--header-row -2 ses--file-format 1 ses--numrows 2
314 "Offsets from 'Global parameters' line to various parameter lines in the
315 data area of a spreadsheet.")
319 ;; "Side-effect variables". They are set in one function, altered in
320 ;; another as a side effect, then read back by the first, as a way of
321 ;; passing back more than one value. These declarations are just to make
322 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
323 ;; think the make-local-variable trick above is cleaner).
326 (defvar ses-relocate-return nil
327 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
328 `ses-relocate-all'. Set to 'delete if a cell-reference was deleted from a
329 formula--so the formula needs recalculation. Set to 'range if the size of a
330 `ses-range' was changed--so both the formula's value and list of dependents
331 need to be recalculated.")
333 (defvar ses-call-printer-return nil
334 "Set to t if last cell printer invoked by `ses-call-printer' requested
335 left-justification of the result. Set to error-signal if `ses-call-printer'
336 encountered an error during printing. Otherwise nil.")
338 (defvar ses-start-time nil
339 "Time when current operation started. Used by `ses-time-check' to decide
340 when to emit a progress message.")
343 ;;----------------------------------------------------------------------------
345 ;;----------------------------------------------------------------------------
347 (defmacro ses-get-cell (row col)
348 "Return the cell structure that stores information about cell (ROW,COL)."
349 `(aref (aref ses--cells ,row) ,col))
351 ;; We might want to use defstruct here, but cells are explicitly used as
352 ;; arrays in ses-set-cell, so we'd need to fix this first. --Stef
353 (defsubst ses-make-cell (&optional symbol formula printer references
355 (vector symbol formula printer references property-list))
357 (defmacro ses-cell-symbol (row &optional col)
358 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
359 `(aref ,(if col `(ses-get-cell ,row ,col) row) 0))
360 (put 'ses-cell-symbol 'safe-function t)
362 (defmacro ses-cell-formula (row &optional col)
363 "From a CELL or a pair (ROW,COL), get the function that computes its value."
364 `(aref ,(if col `(ses-get-cell ,row ,col) row) 1))
366 (defmacro ses-cell-formula-aset (cell formula)
367 "From a CELL set the function that computes its value."
368 `(aset ,cell 1 ,formula))
370 (defmacro ses-cell-printer (row &optional col)
371 "From a CELL or a pair (ROW,COL), get the function that prints its value."
372 `(aref ,(if col `(ses-get-cell ,row ,col) row) 2))
374 (defmacro ses-cell-references (row &optional col)
375 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
376 functions refer to its value."
377 `(aref ,(if col `(ses-get-cell ,row ,col) row) 3))
379 (defmacro ses-cell-references-aset (cell references)
380 "From a CELL set the list REFERENCES of symbols for cells the
381 function of which refer to its value."
382 `(aset ,cell 3 ,references))
384 (defun ses-cell-p (cell)
385 "Return non `nil' is CELL is a cell of current buffer."
388 (eq cell (let ((rowcol (ses-sym-rowcol (ses-cell-symbol cell))))
390 (ses-get-cell (car rowcol) (cdr rowcol)))))))
392 (defun ses-cell-property-get-fun (property-name cell)
393 ;; To speed up property fetching, each time a property is found it is placed
394 ;; in the first position. This way, after the first get, the full property
395 ;; list needs to be scanned only when the property does not exist for that
397 (let* ((plist (aref cell 4))
398 (ret (plist-member plist property-name)))
400 ;; Property was found.
401 (let ((val (cadr ret)))
403 ;; Property found is already in the first position, so just return
406 ;; Property is not in the first position, the following will move it
407 ;; there before returning its value.
408 (let ((next (cddr ret)))
411 (setcdr ret (cdr next))
412 (setcar ret (car next)))
413 (setcdr (last plist 1) nil)))
415 `(,property-name ,val ,@plist))
418 (defmacro ses-cell-property-get (property-name row &optional col)
419 "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
421 When COL is omitted, CELL=ROW is a cell object. When COL is
422 present ROW and COL are the integer coordinates of the cell of
425 `(ses-cell-property-get-fun
427 ,(if col `(ses-get-cell ,row ,col) row)))
429 (defun ses-cell-property-delq-fun (property-name cell)
430 (let ((ret (plist-get (aref cell 4) property-name)))
432 (setcdr ret (cddr ret)))))
434 (defun ses-cell-property-set-fun (property-name property-val cell)
435 (let* ((plist (aref cell 4))
436 (ret (plist-member plist property-name)))
438 (setcar (cdr ret) property-val)
439 (aset cell 4 `(,property-name ,property-val ,@plist)))))
441 (defmacro ses-cell-property-set (property-name property-value row &optional col)
442 "From a CELL or a pair (ROW,COL), set the property value of
443 the corresponding cell with name PROPERTY-NAME to PROPERTY-VALUE."
445 `(ses-cell-property-set-fun ,property-name ,property-value
446 ,(if col `(ses-get-cell ,row ,col) row))
447 `(ses-cell-property-delq-fun ,property-name
448 ,(if col `(ses-get-cell ,row ,col) row))))
450 (defun ses-cell-property-pop-fun (property-name cell)
451 (let* ((plist (aref cell 4))
452 (ret (plist-member plist property-name)))
455 (let ((next (cddr ret)))
458 (setcdr ret (cdr next))
459 (setcar ret (car next)))
462 (setcdr (last plist 2) nil))))))))
465 (defmacro ses-cell-property-pop (property-name row &optional col)
466 "From a CELL or a pair (ROW,COL), get and remove the property value of
467 the corresponding cell with name PROPERTY-NAME."
468 `(ses-cell-property-pop-fun ,property-name
469 ,(if col `(ses-get-cell ,row ,col) row)))
471 (defun ses-cell-property-get-handle-fun (property-name cell)
472 (let* ((plist (aref cell 4))
473 (ret (plist-member plist property-name)))
477 (let ((val (cadr ret))
481 (setcdr ret (cdr next))
482 (setcar ret (car next)))
483 (setcdr (last plist 2) nil))
484 (setq ret (cons val plist))
485 (aset cell 4 (cons property-name ret))
487 (setq ret (cons nil plist))
488 (aset cell 4 (cons property-name ret))
491 (defmacro ses-cell-property-get-handle (property-name row &optional col)
492 "From a CELL or a pair (ROW,COL), get a cons cell whose car is
493 the property value of the corresponding cell property with name
495 `(ses-cell-property-get-handle-fun ,property-name
496 ,(if col `(ses-get-cell ,row ,col) row)))
499 (defalias 'ses-cell-property-handle-car 'car)
500 (defalias 'ses-cell-property-handle-setcar 'setcar)
502 (defmacro ses-cell-value (row &optional col)
503 "From a CELL or a pair (ROW,COL), get the current value for that cell."
504 `(symbol-value (ses-cell-symbol ,row ,col)))
506 (defmacro ses-col-width (col)
507 "Return the width for column COL."
508 `(aref ses--col-widths ,col))
510 (defmacro ses-col-printer (col)
511 "Return the default printer for column COL."
512 `(aref ses--col-printers ,col))
514 (defmacro ses-sym-rowcol (sym)
515 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0). Result
516 is nil if SYM is not a symbol that names a cell."
517 `(let ((rc (and (symbolp ,sym) (get ,sym 'ses-cell))))
518 (if (eq rc :ses-named)
519 (gethash ,sym ses--named-cell-hashmap)
522 (defun ses-is-cell-sym-p (sym)
523 "Check whether SYM point at a cell of this spread sheet."
524 (let ((rowcol (get sym 'ses-cell)))
526 (if (eq rowcol :ses-named)
527 (and ses--named-cell-hashmap (gethash sym ses--named-cell-hashmap))
528 (and (< (car rowcol) ses--numrows)
529 (< (cdr rowcol) ses--numcols)
530 (eq (ses-cell-symbol (car rowcol) (cdr rowcol)) sym))))))
532 (defmacro ses-cell (sym value formula printer references)
533 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
534 FORMULA, does not reprint using PRINTER, does not check REFERENCES. This is a
535 macro to prevent propagate-on-load viruses. Safety-checking for FORMULA and
536 PRINTER are deferred until first use."
537 (let ((rowcol (ses-sym-rowcol sym)))
538 (ses-formula-record formula)
539 (ses-printer-record printer)
541 (eq safe-functions t)
542 (setq formula `(ses-safe-formula ,formula)))
545 (eq safe-functions t)
546 (setq printer `(ses-safe-printer ,printer)))
547 (aset (aref ses--cells (car rowcol))
549 (ses-make-cell sym formula printer references)))
553 (defmacro ses-column-widths (widths)
554 "Load the vector of column widths from the spreadsheet file. This is a
555 macro to prevent propagate-on-load viruses."
556 (or (and (vectorp widths) (= (length widths) ses--numcols))
557 (error "Bad column-width vector"))
558 ;;To save time later, we also calculate the total width of each line in the
559 ;;print area (excluding the terminating newline)
560 (setq ses--col-widths widths
561 ses--linewidth (apply '+ -1 (mapcar '1+ widths))
562 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
565 (defmacro ses-column-printers (printers)
566 "Load the vector of column printers from the spreadsheet file and checks
567 them for safety. This is a macro to prevent propagate-on-load viruses."
568 (or (and (vectorp printers) (= (length printers) ses--numcols))
569 (error "Bad column-printers vector"))
570 (dotimes (x ses--numcols)
571 (aset printers x (ses-safe-printer (aref printers x))))
572 (setq ses--col-printers printers)
573 (mapc 'ses-printer-record printers)
576 (defmacro ses-default-printer (def)
577 "Load the global default printer from the spreadsheet file and checks it
578 for safety. This is a macro to prevent propagate-on-load viruses."
579 (setq ses--default-printer (ses-safe-printer def))
580 (ses-printer-record def)
583 (defmacro ses-header-row (row)
584 "Load the header row from the spreadsheet file and checks it
585 for safety. This is a macro to prevent propagate-on-load viruses."
586 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
587 (error "Bad header-row"))
588 (setq ses--header-row row)
591 (defmacro ses-dorange (curcell &rest body)
592 "Execute BODY repeatedly, with the variables `row' and `col' set to each
593 cell in the range specified by CURCELL. The range is available in the
594 variables `minrow', `maxrow', `mincol', and `maxcol'."
595 (declare (indent defun) (debug (form body)))
596 (let ((cur (make-symbol "cur"))
597 (min (make-symbol "min"))
598 (max (make-symbol "max"))
599 (r (make-symbol "r"))
600 (c (make-symbol "c")))
601 `(let* ((,cur ,curcell)
602 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
603 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
604 (let ((minrow (car ,min))
609 (if (or (> minrow maxrow) (> mincol maxcol))
610 (error "Empty range"))
611 (dotimes (,r (- maxrow minrow -1))
612 (setq row (+ ,r minrow))
613 (dotimes (,c (- maxcol mincol -1))
614 (setq col (+ ,c mincol))
617 ;;Support for coverage testing.
618 (defmacro 1value (form)
619 "For code-coverage testing, indicate that FORM is expected to always have
622 (defmacro noreturn (form)
623 "For code-coverage testing, indicate that FORM will always signal an error."
627 ;;----------------------------------------------------------------------------
629 ;;----------------------------------------------------------------------------
631 (defun ses-vector-insert (array idx new)
632 "Create a new vector which is one larger than ARRAY and has NEW inserted
634 (let* ((len (length array))
635 (result (make-vector (1+ len) new)))
638 (if (< x idx) x (1+ x))
642 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
643 (defun ses-vector-delete (array idx count)
644 "Create a new vector which is a copy of ARRAY with COUNT objects removed
645 starting at element IDX. ARRAY is either a vector or a symbol whose value
646 is a vector--if a symbol, the new vector is assigned as the symbol's value."
647 (let* ((a (if (arrayp array) array (symbol-value array)))
648 (len (- (length a) count))
649 (result (make-vector len nil)))
651 (aset result x (aref a (if (< x idx) x (+ x count)))))
656 (defun ses-delete-line (count)
657 "Like `kill-line', but no kill ring."
660 (delete-region pos (point))))
662 (defun ses-printer-validate (printer)
663 "Signal an error if PRINTER is not a valid SES cell printer."
667 (and (stringp (car-safe printer)) (not (cdr printer)))
668 (error "Invalid printer function"))
671 (defun ses-printer-record (printer)
672 "Add PRINTER to `ses-read-printer-history' if not already there, after first
673 checking that it is a valid printer function."
674 (ses-printer-validate printer)
675 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
677 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
679 (defun ses-formula-record (formula)
680 "If FORMULA is of the form 'symbol, add it to the list of symbolic formulas
681 for this spreadsheet."
682 (when (and (eq (car-safe formula) 'quote)
683 (symbolp (cadr formula)))
684 (add-to-list 'ses--symbolic-formulas
685 (list (symbol-name (cadr formula))))))
687 (defun ses-column-letter (col)
688 "Return the alphabetic name of column number COL.
689 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
690 (let ((units (char-to-string (+ ?A (% col 26)))))
693 (concat (ses-column-letter (1- (/ col 26))) units))))
695 (defun ses-create-cell-symbol (row col)
696 "Produce a symbol that names the cell (ROW,COL). (0,0) => 'A1."
697 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
699 (defun ses-decode-cell-symbol (str)
700 "Decode a symbol \"A1\" => (0,0). Returns `nil' if STR is not a
701 canonical cell name. Does not save match data."
702 (let (case-fold-search)
703 (and (string-match "\\`\\([A-Z]+\\)\\([0-9]+\\)\\'" str)
704 (let* ((col-str (match-string-no-properties 1 str))
707 (col-idx (1- (length col-str)))
708 (row (1- (string-to-number (match-string-no-properties 2 str)))))
713 (setq col (+ col (* (- (aref col-str col-idx) ?A) col-base))
714 col-base (* col-base 26)
715 col-idx (1- col-idx))
717 (setq col (+ col col-base)))))
720 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
721 "Create buffer-local variables for cells. This is undoable."
722 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
725 (dotimes (row (1+ (- maxrow minrow)))
726 (dotimes (col (1+ (- maxcol mincol)))
727 (setq xrow (+ row minrow)
729 sym (ses-create-cell-symbol xrow xcol))
730 (put sym 'ses-cell (cons xrow xcol))
731 (make-local-variable sym)))))
733 (defun ses-create-cell-variable (sym row col)
734 "Create a buffer-local variable `SYM' for cell at position (ROW, COL).
736 SYM is the symbol for that variable, ROW and COL are integers for
737 row and column of the cell, with numbering starting from 0.
739 Return nil in case of failure."
740 (unless (local-variable-p sym)
741 (make-local-variable sym)
742 (if (let (case-fold-search) (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name sym)))
743 (put sym 'ses-cell (cons row col))
744 (put sym 'ses-cell :ses-named)
745 (setq ses--named-cell-hashmap (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
746 (puthash sym (cons row col) ses--named-cell-hashmap))))
748 ;; We do not delete the ses-cell properties for the cell-variables, in
749 ;; case a formula that refers to this cell is in the kill-ring and is
750 ;; later pasted back in.
751 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
752 "Destroy buffer-local variables for cells. This is undoable."
754 (dotimes (row (1+ (- maxrow minrow)))
755 (dotimes (col (1+ (- maxcol mincol)))
756 (let ((xrow (+ row minrow)) (xcol (+ col mincol)))
757 (setq sym (if (and (< xrow ses--numrows) (< xcol ses--numcols))
758 (ses-cell-symbol xrow xcol)
759 (ses-create-cell-symbol xrow xcol))))
761 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
763 (kill-local-variable sym))))
764 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
767 (defun ses-reset-header-string ()
768 "Flag the header string for update. Upon undo, the header string will be
770 (push '(apply ses-reset-header-string) buffer-undo-list)
771 (setq ses--header-hscroll -1))
773 ;;Split this code off into a function to avoid coverage-testing difficulties
774 (defun ses-time-check (format arg)
775 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
776 and (eval ARG) and reset `ses-start-time' to the current time."
777 (when (> (- (float-time) ses-start-time) 1.0)
778 (message format (eval arg))
779 (setq ses-start-time (float-time)))
783 ;;----------------------------------------------------------------------------
785 ;;----------------------------------------------------------------------------
787 (defun ses-set-cell (row col field val)
788 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
789 cell (ROW,COL). This is undoable. The cell's data will be updated through
790 `post-command-hook'."
791 (let ((cell (ses-get-cell row col))
792 (elt (plist-get '(value t symbol 0 formula 1 printer 2 references 3)
795 (or elt (signal 'args-out-of-range nil))
796 (setq change (if (eq elt t)
797 (ses-set-with-undo (ses-cell-symbol cell) val)
798 (ses-aset-with-undo cell elt val)))
800 (add-to-list 'ses--deferred-write (cons row col))))
801 nil) ; Make coverage-tester happy.
803 (defun ses-cell-set-formula (row col formula)
804 "Store a new formula for (ROW . COL) and enqueue the cell for
805 recalculation via `post-command-hook'. Updates the reference lists for the
806 cells that this cell refers to. Does not update cell value or reprint the
807 cell. To avoid inconsistencies, this function is not interruptible, which
808 means Emacs will crash if FORMULA contains a circular list."
809 (let* ((cell (ses-get-cell row col))
810 (old (ses-cell-formula cell)))
811 (let ((sym (ses-cell-symbol cell))
812 (oldref (ses-formula-references old))
813 (newref (ses-formula-references formula))
816 (add-to-list 'ses--deferred-recalc sym)
817 ;;Delete old references from this cell. Skip the ones that are also
820 (unless (memq ref newref)
821 (setq x (ses-sym-rowcol ref)
824 (ses-set-cell xrow xcol 'references
825 (delq sym (ses-cell-references xrow xcol)))))
826 ;;Add new ones. Skip ones left over from old list
828 (setq x (ses-sym-rowcol ref)
831 x (ses-cell-references xrow xcol))
833 (ses-set-cell xrow xcol 'references (cons sym x))))
834 (ses-formula-record formula)
835 (ses-set-cell row col 'formula formula))))
838 (defun ses-repair-cell-reference-all ()
839 "Repair cell reference and warn if there was some reference corruption."
842 ;; Step 1, reset :ses-repair-reference cell property in the whole sheet.
843 (dotimes (row ses--numrows)
844 (dotimes (col ses--numcols)
845 (let ((references (ses-cell-property-pop :ses-repair-reference
849 (ses-cell-symbol row col)
851 references) errors)))))
853 ;; Step 2, build new.
854 (dotimes (row ses--numrows)
855 (dotimes (col ses--numcols)
856 (let* ((cell (ses-get-cell row col))
857 (sym (ses-cell-symbol cell))
858 (formula (ses-cell-formula cell))
859 (new-ref (ses-formula-references formula)))
860 (dolist (ref new-ref)
861 (let* ((rowcol (ses-sym-rowcol ref))
862 (h (ses-cell-property-get-handle :ses-repair-reference
863 (car rowcol) (cdr rowcol))))
864 (unless (memq ref (ses-cell-property-handle-car h))
865 (ses-cell-property-handle-setcar
868 (ses-cell-property-handle-car h)))))))))
870 ;; Step 3, overwrite with check.
871 (dotimes (row ses--numrows)
872 (dotimes (col ses--numcols)
873 (let* ((cell (ses-get-cell row col))
874 (irrelevant (ses-cell-references cell))
875 (new-ref (ses-cell-property-pop :ses-repair-reference cell))
877 (dolist (ref new-ref)
878 (if (memq ref irrelevant)
879 (setq irrelevant (delq ref irrelevant))
881 (ses-set-cell row col 'references new-ref)
882 (when (or missing irrelevant)
883 (push `( ,(ses-cell-symbol cell)
884 ,@(and missing (list :missing missing))
885 ,@(and irrelevant (list :irrelevant irrelevant)))
888 (warn "----------------------------------------------------------------
889 Some references were corrupted.
891 The following is a list where each element ELT is such
892 that (car ELT) is the reference of cell CELL with corruption,
893 and (cdr ELT) is a property list where
895 * property `:corrupt-property' means that
896 property `:ses-repair-reference' of cell CELL was initially non
899 * property `:missing' is a list of missing references
901 * property `:irrelevant' is a list of non needed references
904 (message "No reference corruption found"))))
906 (defun ses-calculate-cell (row col force)
907 "Calculate and print the value for cell (ROW,COL) using the cell's formula
908 function and print functions, if any. Result is nil for normal operation, or
909 the error signal if the formula or print function failed. The old value is
910 left unchanged if it was *skip* and the new value is nil.
911 Any cells that depend on this cell are queued for update after the end of
912 processing for the current keystroke, unless the new value is the same as
913 the old and FORCE is nil."
914 (let ((cell (ses-get-cell row col))
915 cycle-error formula-error printer-error)
916 (let ((oldval (ses-cell-value cell))
917 (formula (ses-cell-formula cell))
919 this-cell-Dijkstra-attempt-h
920 this-cell-Dijkstra-attempt
921 this-cell-Dijkstra-attempt+1
922 ref-cell-Dijkstra-attempt-h
923 ref-cell-Dijkstra-attempt
925 (when (eq (car-safe formula) 'ses-safe-formula)
926 (setq formula (ses-safe-formula (cadr formula)))
927 (ses-set-cell row col 'formula formula))
929 (setq newval (eval formula))
931 ;; Variable `sig' can't be nil.
932 (nconc sig (list (ses-cell-symbol cell)))
933 (setq formula-error sig
935 (if (and (not newval) (eq oldval '*skip*))
936 ;; Don't lose the *skip* --- previous field spans this one.
937 (setq newval '*skip*))
939 (when (or force (not (eq newval oldval)))
940 (add-to-list 'ses--deferred-write (cons row col)) ; In case force=t.
941 (setq this-cell-Dijkstra-attempt-h
942 (ses-cell-property-get-handle :ses-Dijkstra-attempt cell);
943 this-cell-Dijkstra-attempt
944 (ses-cell-property-handle-car this-cell-Dijkstra-attempt-h))
945 (if (null this-cell-Dijkstra-attempt)
946 (ses-cell-property-handle-setcar
947 this-cell-Dijkstra-attempt-h
948 (setq this-cell-Dijkstra-attempt
949 (cons ses--Dijkstra-attempt-nb 0)))
950 (unless (= ses--Dijkstra-attempt-nb
951 (car this-cell-Dijkstra-attempt))
952 (setcar this-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
953 (setcdr this-cell-Dijkstra-attempt 0)))
954 (setq this-cell-Dijkstra-attempt+1
955 (1+ (cdr this-cell-Dijkstra-attempt)))
956 (ses-set-cell row col 'value newval)
957 (dolist (ref (ses-cell-references cell))
958 (add-to-list 'ses--deferred-recalc ref)
959 (setq ref-rowcol (ses-sym-rowcol ref)
960 ref-cell-Dijkstra-attempt-h
961 (ses-cell-property-get-handle
962 :ses-Dijkstra-attempt
963 (car ref-rowcol) (cdr ref-rowcol))
964 ref-cell-Dijkstra-attempt
965 (ses-cell-property-handle-car ref-cell-Dijkstra-attempt-h))
967 (if (null ref-cell-Dijkstra-attempt)
968 (ses-cell-property-handle-setcar
969 ref-cell-Dijkstra-attempt-h
970 (setq ref-cell-Dijkstra-attempt
971 (cons ses--Dijkstra-attempt-nb
972 this-cell-Dijkstra-attempt+1)))
973 (if (= (car ref-cell-Dijkstra-attempt) ses--Dijkstra-attempt-nb)
974 (setcdr ref-cell-Dijkstra-attempt
975 (max (cdr ref-cell-Dijkstra-attempt)
976 this-cell-Dijkstra-attempt+1))
977 (setcar ref-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
978 (setcdr ref-cell-Dijkstra-attempt
979 this-cell-Dijkstra-attempt+1)))
981 (when (> this-cell-Dijkstra-attempt+1 ses--Dijkstra-weight-bound)
982 ;; Update print of this cell.
983 (throw 'cycle (setq formula-error
984 `(error ,(format "Found cycle on cells %S"
985 (ses-cell-symbol cell)))
986 cycle-error formula-error)))))))
987 (setq printer-error (ses-print-cell row col))
990 (error (error-message-string cycle-error)))
991 formula-error printer-error)))
993 (defun ses-clear-cell (row col)
994 "Delete formula and printer for cell (ROW,COL)."
995 (ses-set-cell row col 'printer nil)
996 (ses-cell-set-formula row col nil))
998 (defcustom ses-self-reference-early-detection nil
999 "True if cycle detection is early for cells that refer to themselves."
1004 (defun ses-update-cells (list &optional force)
1005 "Recalculate cells in LIST, checking for dependency loops. Prints
1006 progress messages every second. Dependent cells are not recalculated
1007 if the cell's value is unchanged and FORCE is nil."
1008 (let ((ses--deferred-recalc list)
1011 curlist prevlist this-sym this-rowcol formula)
1012 (with-temp-message " "
1013 (while ses--deferred-recalc
1014 ;; In each loop, recalculate cells that refer only to other cells that
1015 ;; have already been recalculated or aren't in the recalculation region.
1016 ;; Repeat until all cells have been processed or until the set of cells
1017 ;; being worked on stops changing.
1019 (message "Recalculating... (%d cells left)"
1020 (length ses--deferred-recalc)))
1021 (setq curlist ses--deferred-recalc
1022 ses--deferred-recalc nil
1025 ;; this-sym has to be popped from curlist *BEFORE* the check, and not
1026 ;; after because of the case of cells referring to themselves.
1027 (setq this-sym (pop curlist)
1028 this-rowcol (ses-sym-rowcol this-sym)
1029 formula (ses-cell-formula (car this-rowcol)
1032 (dolist (ref (ses-formula-references formula))
1033 (if (and ses-self-reference-early-detection (eq ref this-sym))
1034 (error "Cycle found: cell %S is self-referring" this-sym)
1035 (when (or (memq ref curlist)
1036 (memq ref ses--deferred-recalc))
1037 ;; This cell refers to another that isn't done yet
1038 (add-to-list 'ses--deferred-recalc this-sym)
1040 ;; ses-update-cells is called from post-command-hook, so
1041 ;; inhibit-quit is implicitly bound to t.
1043 ;; Abort the recalculation. User will probably undo now.
1045 (ses-calculate-cell (car this-rowcol) (cdr this-rowcol) force)))
1046 (dolist (ref ses--deferred-recalc)
1047 (add-to-list 'nextlist ref)))
1048 (when ses--deferred-recalc
1049 ;; Just couldn't finish these.
1050 (dolist (x ses--deferred-recalc)
1051 (let ((this-rowcol (ses-sym-rowcol x)))
1052 (ses-set-cell (car this-rowcol) (cdr this-rowcol) 'value '*error*)
1053 (1value (ses-print-cell (car this-rowcol) (cdr this-rowcol)))))
1054 (error "Circular references: %s" ses--deferred-recalc))
1056 ;; Can't use save-excursion here: if the cell under point is updated,
1057 ;; save-excursion's marker will move past the cell.
1061 ;;----------------------------------------------------------------------------
1063 ;;----------------------------------------------------------------------------
1065 (defun ses-in-print-area ()
1066 "Return t if point is in print area of spreadsheet."
1067 (<= (point) ses--data-marker))
1069 ;; We turn off point-motion-hooks and explicitly position the cursor, in case
1070 ;; the intangible properties have gotten screwed up (e.g., when ses-goto-print
1071 ;; is called during a recursive ses-print-cell).
1072 (defun ses-goto-print (row col)
1073 "Move point to print area for cell (ROW,COL)."
1074 (let ((inhibit-point-motion-hooks t)
1076 (goto-char (point-min))
1078 ;; Calculate column position.
1080 (setq n (+ n (ses-col-width c) 1)))
1081 ;; Move to the position.
1082 (and (> n (move-to-column n))
1084 ;; Move point to the bol of next line (for TAB at the last cell).
1087 (defun ses-set-curcell ()
1088 "Set `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
1089 region, or nil if cursor is not at a cell."
1090 (if (or (not mark-active)
1092 (= (region-beginning) (region-end)))
1094 (setq ses--curcell (get-text-property (point) 'intangible))
1096 (let ((bcell (get-text-property (region-beginning) 'intangible))
1097 (ecell (get-text-property (1- (region-end)) 'intangible)))
1098 (when (= (region-end) ses--data-marker)
1099 ;; Correct for overflow.
1100 (setq ecell (get-text-property (- (region-end) 2) 'intangible)))
1101 (setq ses--curcell (if (and bcell ecell)
1106 (defun ses-check-curcell (&rest args)
1107 "Signal an error if `ses--curcell' is inappropriate.
1108 The end marker is appropriate if some argument is 'end.
1109 A range is appropriate if some argument is 'range.
1110 A single cell is appropriate unless some argument is 'needrange."
1111 (if (eq ses--curcell t)
1112 ;; curcell recalculation was postponed, but user typed ahead.
1116 (or (memq 'end args)
1117 (error "Not at cell")))
1118 ((consp ses--curcell)
1119 (or (memq 'range args)
1120 (memq 'needrange args)
1121 (error "Can't use a range")))
1122 ((memq 'needrange args)
1123 (error "Need a range"))))
1125 (defun ses-print-cell (row col)
1126 "Format and print the value of cell (ROW,COL) to the print area.
1127 Use the cell's printer function. If the cell's new print form is too wide,
1128 it will spill over into the following cell, but will not run off the end of the
1129 row or overwrite the next non-nil field. Result is nil for normal operation,
1130 or the error signal if the printer function failed and the cell was formatted
1131 with \"%s\". If the cell's value is *skip*, nothing is printed because the
1132 preceding cell has spilled over."
1133 (catch 'ses-print-cell
1134 (let* ((cell (ses-get-cell row col))
1135 (value (ses-cell-value cell))
1136 (printer (ses-cell-printer cell))
1138 text sig startpos x)
1139 ;; Create the string to print.
1142 ;; Don't print anything.
1143 (throw 'ses-print-cell nil))
1144 ((eq value '*error*)
1145 (setq text (make-string (ses-col-width col) ?#)))
1147 ;; Deferred safety-check on printer.
1148 (if (eq (car-safe printer) 'ses-safe-printer)
1149 (ses-set-cell row col 'printer
1150 (setq printer (ses-safe-printer (cadr printer)))))
1152 (setq text (ses-call-printer (or printer
1153 (ses-col-printer col)
1154 ses--default-printer)
1156 (if (consp ses-call-printer-return)
1157 ;; Printer returned an error.
1158 (setq sig ses-call-printer-return))))
1159 ;; Adjust print width to match column width.
1160 (let ((width (ses-col-width col))
1161 (len (string-width text)))
1164 ;; Fill field to length with spaces.
1165 (setq len (make-string (- width len) ?\s)
1166 text (if (eq ses-call-printer-return t)
1168 (concat len text))))
1170 ;; Spill over into following cells, if possible.
1171 (let ((maxwidth width))
1172 (while (and (> len maxwidth)
1173 (< maxcol ses--numcols)
1174 (or (not (setq x (ses-cell-value row maxcol)))
1177 ;; Set this cell to '*skip* so it won't overwrite our spillover.
1178 (ses-set-cell row maxcol 'value '*skip*))
1179 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
1180 maxcol (1+ maxcol)))
1181 (if (<= len maxwidth)
1182 ;; Fill to complete width of all the fields spanned.
1183 (setq text (concat text (make-string (- maxwidth len) ?\s)))
1184 ;; Not enough room to end of line or next non-nil field. Truncate
1185 ;; if string or decimal; otherwise fill with error indicator.
1186 (setq sig `(error "Too wide" ,text))
1189 (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
1190 ((and (numberp value)
1191 (string-match "\\.[0-9]+" text)
1194 (- (match-end 0) (match-beginning 0))))))
1195 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
1196 (setq text (concat (substring text
1198 (- (match-beginning 0) width))
1199 (substring text (match-end 0)))))
1201 (setq text (make-string maxwidth ?#)))))))))
1202 ;; Substitute question marks for tabs and newlines. Newlines are used as
1203 ;; row-separators; tabs could confuse the reimport logic.
1204 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
1205 (ses-goto-print row col)
1206 (setq startpos (point))
1207 ;; Install the printed result. This is not interruptible.
1208 (let ((inhibit-read-only t)
1210 (let ((inhibit-point-motion-hooks t))
1211 (delete-region (point) (progn
1212 (move-to-column (+ (current-column)
1213 (string-width text)))
1215 ;; We use concat instead of inserting separate strings in order to
1216 ;; reduce the number of cells in the undo list.
1217 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
1218 ;; We use set-text-properties to prevent a wacky print function from
1219 ;; inserting rogue properties, and to ensure that the keymap property is
1220 ;; inherited (is it a bug that only unpropertized strings actually
1221 ;; inherit from surrounding text?)
1222 (set-text-properties 0 (length x) nil x)
1223 (insert-and-inherit x)
1224 (put-text-property startpos (point) 'intangible
1225 (ses-cell-symbol cell))
1226 (when (and (zerop row) (zerop col))
1227 ;; Reconstruct special beginning-of-buffer attributes.
1228 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
1229 (put-text-property (point-min) (point) 'read-only 'ses)
1230 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)))
1231 (if (= row (1- ses--header-row))
1232 ;; This line is part of the header --- force recalc.
1233 (ses-reset-header-string))
1234 ;; If this cell (or a preceding one on the line) previously spilled over
1235 ;; and has gotten shorter, redraw following cells on line recursively.
1236 (when (and (< maxcol ses--numcols)
1237 (eq (ses-cell-value row maxcol) '*skip*))
1238 (ses-set-cell row maxcol 'value nil)
1239 (ses-print-cell row maxcol))
1240 ;; Return to start of cell.
1241 (goto-char startpos)
1244 (defun ses-call-printer (printer &optional value)
1245 "Invoke PRINTER (a string or parenthesized string or function-symbol or
1246 lambda of one argument) on VALUE. Result is the printed cell as a string.
1247 The variable `ses-call-printer-return' is set to t if the printer used
1248 parenthesis to request left-justification, or the error-signal if the
1249 printer signaled one (and \"%s\" is used as the default printer), else nil."
1250 (setq ses-call-printer-return nil)
1251 (condition-case signal
1255 (format printer value)
1257 ((stringp (car-safe printer))
1258 (setq ses-call-printer-return t)
1260 (format (car printer) value)
1263 (setq value (funcall printer (or value "")))
1266 (or (stringp (car-safe value))
1267 (error "Printer should return \"string\" or (\"string\")"))
1268 (setq ses-call-printer-return t)
1271 (setq ses-call-printer-return signal)
1272 (prin1-to-string value t))))
1274 (defun ses-adjust-print-width (col change)
1275 "Insert CHANGE spaces in front of column COL, or at end of line if
1276 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
1277 `inhibit-quit' to t."
1278 (let ((inhibit-read-only t)
1279 (blank (if (> change 0) (make-string change ?\s)))
1280 (at-end (= col ses--numcols)))
1281 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
1282 ;; ses-set-with-undo always returns t for strings.
1283 (1value (ses-set-with-undo 'ses--blank-line
1284 (concat (make-string ses--linewidth ?\s) "\n")))
1285 (dotimes (row ses--numrows)
1286 (ses-goto-print row col)
1288 ;; Insert new columns before newline.
1289 (let ((inhibit-point-motion-hooks t))
1293 (delete-char (- change))))))
1295 (defun ses-print-cell-new-width (row col)
1296 "Same as `ses-print-cell', except if the cell's value is *skip*,
1297 the preceding nonskipped cell is reprinted. This function is used
1298 when the width of cell (ROW,COL) has changed."
1299 (if (not (eq (ses-cell-value row col) '*skip*))
1300 (ses-print-cell row col)
1301 ;;Cell was skipped over - reprint previous
1302 (ses-goto-print row col)
1304 (let ((rowcol (ses-sym-rowcol (get-text-property (point) 'intangible))))
1305 (ses-print-cell (car rowcol) (cdr rowcol)))))
1308 ;;----------------------------------------------------------------------------
1310 ;;----------------------------------------------------------------------------
1313 "Turn off narrowing, to be reenabled at end of command loop."
1314 (if (buffer-narrowed-p)
1315 (setq ses--deferred-narrow t))
1318 (defun ses-goto-data (def &optional col)
1319 "Move point to data area for (DEF,COL). If DEF is a row
1320 number, COL is the column number for a data cell -- otherwise DEF
1321 is one of the symbols ses--col-widths, ses--col-printers,
1322 ses--default-printer, ses--numrows, or ses--numcols."
1324 (let ((inhibit-point-motion-hooks t)) ; In case intangible attrs are wrong.
1328 (goto-char ses--data-marker)
1329 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
1330 ;; Convert def-symbol to offset.
1331 (setq def (plist-get ses-paramlines-plist def))
1332 (or def (signal 'args-out-of-range nil))
1333 (goto-char ses--params-marker)
1334 (forward-line def))))
1336 (defun ses-set-parameter (def value &optional elem)
1337 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1338 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1339 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
1341 ;; We call ses-goto-data early, using the old values of numrows and numcols
1342 ;; in case one of them is being changed.
1344 (let ((inhibit-read-only t)
1345 (fmt (plist-get '(ses--col-widths "(ses-column-widths %S)"
1346 ses--col-printers "(ses-column-printers %S)"
1347 ses--default-printer "(ses-default-printer %S)"
1348 ses--header-row "(ses-header-row %S)"
1349 ses--file-format " %S ;SES file-format"
1350 ses--numrows " %S ;numrows"
1351 ses--numcols " %S ;numcols")
1356 (setq oldval (aref (symbol-value def) elem))
1357 (aset (symbol-value def) elem value))
1358 (setq oldval (symbol-value def))
1360 ;; Special undo since it's outside the narrowed buffer.
1361 (let (buffer-undo-list)
1362 (delete-region (point) (line-end-position))
1363 (insert (format fmt (symbol-value def))))
1364 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1367 (defun ses-write-cells ()
1368 "Write cells in `ses--deferred-write' from local variables to data area.
1369 Newlines in the data are escaped."
1370 (let* ((inhibit-read-only t)
1371 (print-escape-newlines t)
1372 rowcol row col cell sym formula printer text)
1373 (setq ses-start-time (float-time))
1374 (with-temp-message " "
1376 (while ses--deferred-write
1377 (ses-time-check "Writing... (%d cells left)"
1378 '(length ses--deferred-write))
1379 (setq rowcol (pop ses--deferred-write)
1382 cell (ses-get-cell row col)
1383 sym (ses-cell-symbol cell)
1384 formula (ses-cell-formula cell)
1385 printer (ses-cell-printer cell))
1386 (if (eq (car-safe formula) 'ses-safe-formula)
1387 (setq formula (cadr formula)))
1388 (if (eq (car-safe printer) 'ses-safe-printer)
1389 (setq printer (cadr printer)))
1390 ;; This is noticeably faster than (format "%S %S %S %S %S")
1391 (setq text (concat "(ses-cell "
1394 (prin1-to-string (symbol-value sym))
1396 (prin1-to-string formula)
1398 (prin1-to-string printer)
1400 (if (atom (ses-cell-references cell))
1403 (mapconcat 'symbol-name
1404 (ses-cell-references cell)
1408 (ses-goto-data row col)
1409 (delete-region (point) (line-end-position))
1414 ;;----------------------------------------------------------------------------
1415 ;; Formula relocation
1416 ;;----------------------------------------------------------------------------
1418 (defun ses-formula-references (formula &optional result-so-far)
1419 "Produce a list of symbols for cells that this FORMULA's value
1420 refers to. For recursive calls, RESULT-SO-FAR is the list being
1421 constructed, or t to get a wrong-type-argument error when the
1422 first reference is found."
1423 (if (ses-sym-rowcol formula)
1424 ;;Entire formula is one symbol
1425 (add-to-list 'result-so-far formula)
1428 ((eq (car formula) 'ses-range)
1430 (cdr (funcall 'macroexpand
1431 (list 'ses-range (nth 1 formula)
1433 (add-to-list 'result-so-far cur)))
1434 ((null (eq (car formula) 'quote))
1435 ;;Recursive call for subformulas
1436 (dolist (cur formula)
1437 (setq result-so-far (ses-formula-references cur result-so-far))))
1439 ;;Ignore other stuff
1441 ;; other type of atom are ignored
1445 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1446 "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
1447 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1448 by (ROWINCR,COLINCR)."
1449 (let ((row (car rowcol))
1451 (if (or (< row startrow) (< col startcol))
1453 (setq row (+ row rowincr)
1454 col (+ col colincr))
1455 (if (and (>= row startrow) (>= col startcol)
1456 (< row ses--numrows) (< col ses--numcols))
1457 ;;Relocate this variable
1458 (ses-create-cell-symbol row col)
1459 ;;Delete reference to a deleted cell
1462 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1463 "Produce a copy of FORMULA where all symbols that refer to cells in row
1464 STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
1465 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1466 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1468 If ROWINCR or COLINCR is negative, references to cells being deleted are
1470 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1472 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1473 (let (rowcol result)
1474 (if (or (atom formula) (eq (car formula) 'quote))
1475 (if (and (setq rowcol (ses-sym-rowcol formula))
1476 (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name formula)))
1477 (ses-relocate-symbol formula rowcol
1478 startrow startcol rowincr colincr)
1479 formula) ; Pass through as-is.
1480 (dolist (cur formula)
1481 (setq rowcol (ses-sym-rowcol cur))
1484 (setq cur (ses-relocate-symbol cur rowcol
1485 startrow startcol rowincr colincr))
1488 ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
1489 ;; don't change the flag if it's already 'range, since range implies
1491 (unless ses-relocate-return
1492 (setq ses-relocate-return 'delete))))
1493 ((eq (car-safe cur) 'ses-range)
1494 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1497 ((or (atom cur) (eq (car cur) 'quote))
1498 ;; Constants pass through unchanged.
1501 ;; Recursively copy and alter subformulas.
1502 (push (ses-relocate-formula cur startrow startcol
1505 (nreverse result))))
1507 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1508 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1509 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1510 new range, or nil if the entire range is deleted. If new rows are being added
1511 just beyond the end of a row range, or new columns just beyond a column range,
1512 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1513 if the range was altered."
1514 (let* ((minorig (cadr range))
1515 (minrowcol (ses-sym-rowcol minorig))
1516 (min (ses-relocate-symbol minorig minrowcol
1519 (maxorig (nth 2 range))
1520 (maxrowcol (ses-sym-rowcol maxorig))
1521 (max (ses-relocate-symbol maxorig maxrowcol
1526 ((and (not min) (not max))
1527 (setq range nil)) ; The entire range is deleted.
1529 ;; Inserting or deleting rows.
1532 ;; Chopped off beginning of range.
1533 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1534 ses-relocate-return 'range))
1537 ;; Trying to insert a nonexistent row.
1538 (setq max (ses-create-cell-symbol (1- ses--numrows)
1540 ;; End of range is being deleted.
1541 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1542 ses-relocate-return 'range))
1544 (= (car maxrowcol) (1- startrow))
1545 (= (cdr minrowcol) (cdr maxrowcol))
1546 ;; Insert after ending row of vertical range --- include it.
1547 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1548 (cdr maxrowcol))))))
1550 ;; Inserting or deleting columns.
1553 ;; Chopped off beginning of range.
1554 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1555 ses-relocate-return 'range))
1558 ;; Trying to insert a nonexistent column.
1559 (setq max (ses-create-cell-symbol (car maxrowcol)
1561 ;; End of range is being deleted.
1562 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1563 ses-relocate-return 'range))
1565 (= (cdr maxrowcol) (1- startcol))
1566 (= (car minrowcol) (car maxrowcol))
1567 ;; Insert after ending column of horizontal range --- include it.
1568 (setq max (ses-create-cell-symbol (car maxrowcol)
1569 (+ startcol colincr -1)))))))
1571 (if (/= (- (funcall field maxrowcol)
1572 (funcall field minrowcol))
1573 (- (funcall field (ses-sym-rowcol max))
1574 (funcall field (ses-sym-rowcol min))))
1575 ;; This range has changed size.
1576 (setq ses-relocate-return 'range))
1577 `(ses-range ,min ,max ,@(cl-cdddr range)))))
1579 (defun ses-relocate-all (minrow mincol rowincr colincr)
1580 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1581 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1584 (let (mycell newval xrow)
1585 (dotimes-with-progress-reporter
1586 (row ses--numrows) "Relocating formulas..."
1587 (dotimes (col ses--numcols)
1588 (setq ses-relocate-return nil
1589 mycell (ses-get-cell row col)
1590 newval (ses-relocate-formula (ses-cell-formula mycell)
1591 minrow mincol rowincr colincr)
1592 xrow (- row rowincr))
1593 (ses-set-cell row col 'formula newval)
1594 (if (eq ses-relocate-return 'range)
1595 ;; This cell contains a (ses-range X Y) where a cell has been
1596 ;; inserted or deleted in the middle of the range.
1597 (push (cons row col) reform))
1598 (if ses-relocate-return
1599 ;; This cell referred to a cell that's been deleted or is no
1600 ;; longer part of the range. We can't fix that now because
1601 ;; reference lists cells have been partially updated.
1602 (add-to-list 'ses--deferred-recalc
1603 (ses-create-cell-symbol row col)))
1604 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1605 minrow mincol rowincr colincr))
1606 (ses-set-cell row col 'references newval)
1607 (and (>= row minrow) (>= col mincol)
1608 (let ((sym (ses-cell-symbol row col))
1609 (xcol (- col colincr)))
1615 (ses-create-cell-symbol xrow xcol))))
1616 ;; This is a renamed cell, do not update the cell
1617 ;; name, but just update the coordinate property.
1618 (put sym 'ses-cell (cons row col))
1619 (ses-set-cell row col 'symbol
1620 (setq sym (ses-create-cell-symbol row col)))
1621 (unless (and (boundp sym) (local-variable-p sym))
1622 (set (make-local-variable sym) nil)
1623 (put sym 'ses-cell (cons row col)))))) )))
1624 ;; Relocate the cell values.
1625 (let (oldval myrow mycol xrow xcol)
1627 ((and (<= rowincr 0) (<= colincr 0))
1628 ;; Deletion of rows and/or columns.
1629 (dotimes-with-progress-reporter
1630 (row (- ses--numrows minrow)) "Relocating variables..."
1631 (setq myrow (+ row minrow))
1632 (dotimes (col (- ses--numcols mincol))
1633 (setq mycol (+ col mincol)
1634 xrow (- myrow rowincr)
1635 xcol (- mycol colincr))
1636 (let ((sym (ses-cell-symbol myrow mycol))
1637 (xsym (ses-create-cell-symbol xrow xcol)))
1638 ;; Make the value relocation only when if the cell is not
1639 ;; a renamed cell. Otherwise this is not needed.
1641 (ses-set-cell myrow mycol 'value
1642 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1643 (ses-cell-value xrow xcol)
1644 ;;Cell is off the end of the array
1645 (symbol-value xsym))))))))
1647 ((and (wholenump rowincr) (wholenump colincr))
1648 ;; Insertion of rows and/or columns. Run the loop backwards.
1649 (let ((disty (1- ses--numrows))
1650 (distx (1- ses--numcols))
1652 (dotimes-with-progress-reporter
1653 (row (- ses--numrows minrow)) "Relocating variables..."
1654 (setq myrow (- disty row))
1655 (dotimes (col (- ses--numcols mincol))
1656 (setq mycol (- distx col)
1657 xrow (- myrow rowincr)
1658 xcol (- mycol colincr))
1659 (if (or (< xrow minrow) (< xcol mincol))
1660 ;; Newly-inserted value.
1662 ;; Transfer old value.
1663 (setq oldval (ses-cell-value xrow xcol)))
1664 (ses-set-cell myrow mycol 'value oldval)))
1665 t)) ; Make testcover happy by returning non-nil here.
1667 (error "ROWINCR and COLINCR must have the same sign"))))
1668 ;; Reconstruct reference lists for cells that contain ses-ranges that have
1671 (message "Fixing ses-ranges...")
1673 (setq ses-start-time (float-time))
1675 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1676 (setq row (caar reform)
1678 reform (cdr reform))
1679 (ses-cell-set-formula row col (ses-cell-formula row col))))
1683 ;;----------------------------------------------------------------------------
1685 ;;----------------------------------------------------------------------------
1687 (defun ses-begin-change ()
1688 "For undo, remember point before we start changing hidden stuff."
1689 (let ((inhibit-read-only t))
1690 (insert-and-inherit "X")
1691 (delete-region (1- (point)) (point))))
1693 (defun ses-set-with-undo (sym newval)
1694 "Like set, but undoable. Result is t if value has changed."
1695 ;; We try to avoid adding redundant entries to the undo list, but this is
1696 ;; unavoidable for strings because equal ignores text properties and there's
1697 ;; no easy way to get the whole property list to see if it's different!
1698 (unless (and (boundp sym)
1699 (equal (symbol-value sym) newval)
1700 (not (stringp newval)))
1701 (push (if (boundp sym)
1702 `(apply ses-set-with-undo ,sym ,(symbol-value sym))
1703 `(apply ses-unset-with-undo ,sym))
1708 (defun ses-unset-with-undo (sym)
1709 "Set SYM to be unbound. This is undoable."
1710 (when (1value (boundp sym)) ; Always bound, except after a programming error.
1711 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
1714 (defun ses-aset-with-undo (array idx newval)
1715 "Like `aset', but undoable.
1716 Result is t if element has changed."
1717 (unless (equal (aref array idx) newval)
1718 (push `(apply ses-aset-with-undo ,array ,idx
1719 ,(aref array idx)) buffer-undo-list)
1720 (aset array idx newval)
1724 ;;----------------------------------------------------------------------------
1725 ;; Startup for major mode
1726 ;;----------------------------------------------------------------------------
1729 "Parse the current buffer and set up buffer-local variables.
1730 Does not execute cell formulas or print functions."
1732 ;; Read our global parameters, which should be a 3-element list.
1733 (goto-char (point-max))
1734 (search-backward ";; Local Variables:\n" nil t)
1736 (setq ses--params-marker (point-marker))
1737 (let ((params (ignore-errors (read (current-buffer)))))
1738 (or (and (= (safe-length params) 3)
1739 (numberp (car params))
1740 (numberp (cadr params))
1741 (>= (cadr params) 0)
1742 (numberp (nth 2 params))
1743 (> (nth 2 params) 0))
1744 (error "Invalid SES file"))
1745 (setq ses--file-format (car params)
1746 ses--numrows (cadr params)
1747 ses--numcols (nth 2 params))
1748 (when (= ses--file-format 1)
1749 (let (buffer-undo-list) ; This is not undoable.
1750 (ses-goto-data 'ses--header-row)
1751 (insert "(ses-header-row 0)\n")
1752 (ses-set-parameter 'ses--file-format 2)
1753 (message "Upgrading from SES-1 file format")))
1754 (or (= ses--file-format 2)
1755 (error "This file needs a newer version of the SES library code"))
1756 ;; Initialize cell array.
1757 (setq ses--cells (make-vector ses--numrows nil))
1758 (dotimes (row ses--numrows)
1759 (aset ses--cells row (make-vector ses--numcols nil))))
1760 ;; Skip over print area, which we assume is correct.
1761 (goto-char (point-min))
1762 (forward-line ses--numrows)
1763 (or (looking-at-p ses-print-data-boundary)
1764 (error "Missing marker between print and data areas"))
1766 (setq ses--data-marker (point-marker))
1767 (forward-char (1- (length ses-print-data-boundary)))
1768 ;; Initialize printer and symbol lists.
1769 (mapc 'ses-printer-record ses-standard-printer-functions)
1770 (setq ses--symbolic-formulas nil)
1771 ;; Load cell definitions.
1772 (dotimes (row ses--numrows)
1773 (dotimes (col ses--numcols)
1774 (let* ((x (read (current-buffer)))
1775 (sym (car-safe (cdr-safe x))))
1776 (or (and (looking-at-p "\n")
1777 (eq (car-safe x) 'ses-cell)
1778 (ses-create-cell-variable sym row col))
1779 (error "Cell-def error"))
1781 (or (looking-at-p "\n\n")
1782 (error "Missing blank line between rows")))
1783 ;; Load global parameters.
1784 (let ((widths (read (current-buffer)))
1785 (n1 (char-after (point)))
1786 (printers (read (current-buffer)))
1787 (n2 (char-after (point)))
1788 (def-printer (read (current-buffer)))
1789 (n3 (char-after (point)))
1790 (head-row (read (current-buffer)))
1791 (n4 (char-after (point))))
1792 (or (and (eq (car-safe widths) 'ses-column-widths)
1794 (eq (car-safe printers) 'ses-column-printers)
1796 (eq (car-safe def-printer) 'ses-default-printer)
1798 (eq (car-safe head-row) 'ses-header-row)
1800 (error "Invalid SES global parameters"))
1801 (1value (eval widths))
1802 (1value (eval def-printer))
1803 (1value (eval printers))
1804 (1value (eval head-row)))
1805 ;; Should be back at global-params.
1807 (or (looking-at-p (replace-regexp-in-string "1" "[0-9]+"
1808 ses-initial-global-parameters))
1809 (error "Problem with column-defs or global-params"))
1810 ;; Check for overall newline count in definitions area.
1812 (let ((start (point)))
1813 (ses-goto-data 'ses--numrows)
1814 (or (= (point) start)
1815 (error "Extraneous newlines someplace?"))))
1818 "Set up for display of only the printed cell values.
1820 Narrows the buffer to show only the print area. Gives it `read-only' and
1821 `intangible' properties. Sets up highlighting for current cell."
1823 (let ((end (point-min))
1824 (inhibit-read-only t)
1825 (inhibit-point-motion-hooks t)
1826 (was-modified (buffer-modified-p))
1828 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1829 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1830 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1831 ;; The print area is read-only (except for our special commands) and uses a
1833 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1834 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1835 ;; For the beginning of the buffer, we want the read-only and keymap
1836 ;; attributes to be inherited from the first character.
1837 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1838 ;; Create intangible properties, which also indicate which cell the text
1840 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1841 (dotimes (col ses--numcols)
1843 sym (ses-cell-symbol row col))
1844 ;; Include skipped cells following this one.
1845 (while (and (< col (1- ses--numcols))
1846 (eq (ses-cell-value row (1+ col)) '*skip*))
1847 (setq end (+ end (ses-col-width col) 1)
1849 (setq end (save-excursion
1851 (move-to-column (+ (current-column) (- end pos)
1852 (ses-col-width col)))
1854 (+ end (ses-col-width col) 1)
1857 (put-text-property pos end 'intangible sym)))
1858 ;; Adding these properties did not actually alter the text.
1859 (unless was-modified
1860 (restore-buffer-modified-p nil)
1861 (buffer-disable-undo)
1862 (buffer-enable-undo)))
1863 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1864 ;; because column A must be at least 1 column wide.
1865 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1866 (overlay-put ses--curcell-overlay 'face 'underline))
1868 (defun ses-cleanup ()
1869 "Cleanup when changing a buffer from SES mode to something else.
1870 Delete overlays, remove special text properties."
1872 (let ((inhibit-read-only t)
1873 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1874 ;; user "the file is modified, do you really want to make modifications
1875 ;; to this buffer", where the "modifications" refer to the irrelevant
1876 ;; set-text-properties below.
1877 (buffer-file-name nil)
1878 (was-modified (buffer-modified-p)))
1879 ;; Delete read-only, keymap, and intangible properties.
1880 (set-text-properties (point-min) (point-max) nil)
1882 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1883 (unless was-modified
1884 (restore-buffer-modified-p nil))))
1888 "Major mode for Simple Emacs Spreadsheet.
1890 When you invoke SES in a new buffer, it is divided into cells
1891 that you can enter data into. You can navigate the cells with
1892 the arrow keys and add more cells with the tab key. The contents
1893 of these cells can be numbers, text, or Lisp expressions. (To
1894 enter text, enclose it in double quotes.)
1896 In an expression, you can use cell coordinates to refer to the
1897 contents of another cell. For example, you can sum a range of
1898 cells with `(+ A1 A2 A3)'. There are specialized functions like
1899 `ses+' (addition for ranges with empty cells), `ses-average' (for
1900 performing calculations on cells), and `ses-range' and `ses-select'
1901 \(for extracting ranges of cells).
1903 Each cell also has a print function that controls how it is
1906 Each SES buffer is divided into a print area and a data area.
1907 Normally, you can simply use SES to look at and manipulate the print
1908 area, and let SES manage the data area outside the visible region.
1910 See \"ses-example.ses\" (in `data-directory') for an example
1911 spreadsheet, and the Info node `(ses)Top.'
1913 In the following, note the separate keymaps for cell editing mode
1914 and print mode specifications. Key definitions:
1917 These key definitions are active only in the print area (the visible
1919 \\{ses-mode-print-map}
1920 These are active only in the minibuffer, when entering or editing a
1922 \\{ses-mode-edit-map}"
1924 (unless (and (boundp 'ses--deferred-narrow)
1925 (eq ses--deferred-narrow 'ses-mode))
1926 (kill-all-local-variables)
1928 (setq major-mode 'ses-mode
1930 next-line-add-newlines nil
1932 ;; SES deliberately puts lots of trailing whitespace in its buffer.
1933 show-trailing-whitespace nil
1934 ;; Cell ranges do not work reasonably without this.
1935 transient-mark-mode t
1936 ;; Not to use tab characters for safe (tabs may do bad for column
1938 indent-tabs-mode nil)
1939 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1940 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1941 (setq header-line-format '(:eval (progn
1942 (when (/= (window-hscroll)
1943 ses--header-hscroll)
1944 ;; Reset ses--header-hscroll first,
1945 ;; to avoid recursion problems when
1946 ;; debugging ses-create-header-string
1947 (setq ses--header-hscroll
1949 (ses-create-header-string))
1950 ses--header-string)))
1951 (let ((was-empty (zerop (buffer-size)))
1952 (was-modified (buffer-modified-p)))
1955 ;; Initialize buffer to contain one cell, for now.
1956 (insert ses-initial-file-contents))
1960 (unless (equal ses-initial-default-printer
1961 (1value ses--default-printer))
1962 (1value (ses-read-default-printer ses-initial-default-printer)))
1963 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1964 (1value (ses-set-column-width 0 ses-initial-column-width)))
1966 (if (> (car ses-initial-size) (1value ses--numrows))
1967 (1value (ses-insert-row (1- (car ses-initial-size)))))
1968 (if (> (cdr ses-initial-size) (1value ses--numcols))
1969 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1971 (restore-buffer-modified-p was-modified)
1972 (buffer-disable-undo)
1973 (buffer-enable-undo)
1974 (goto-char (point-min))))
1975 (use-local-map ses-mode-map)
1976 ;; Set the deferred narrowing flag (we can't narrow until after
1977 ;; after-find-file completes). If .ses is on the auto-load alist and the
1978 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
1979 ;; special flag to detect this (will be reset by ses-command-hook). For
1980 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
1981 ;; so use an idle timer to make sure.
1982 (setq ses--deferred-narrow 'ses-mode)
1983 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1984 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1985 (run-mode-hooks 'ses-mode-hook)))
1987 (put 'ses-mode 'mode-class 'special)
1989 (defun ses-command-hook ()
1990 "Invoked from `post-command-hook'. If point has moved to a different cell,
1991 moves the underlining overlay. Performs any recalculations or cell-data
1992 writes that have been deferred. If buffer-narrowing has been deferred,
1993 narrows the buffer now."
1995 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
1996 (when ses--deferred-recalc
1997 ;; We reset the deferred list before starting on the recalc --- in
1998 ;; case of error, we don't want to retry the recalc after every
2000 (ses-initialize-Dijkstra-attempt)
2001 (let ((old ses--deferred-recalc))
2002 (setq ses--deferred-recalc nil)
2003 (ses-update-cells old)))
2004 (when ses--deferred-write
2005 ;; We don't reset the deferred list before starting --- the most
2006 ;; likely error is keyboard-quit, and we do want to keep trying these
2007 ;; writes after a quit.
2009 (push '(apply ses-widen) buffer-undo-list))
2010 (when ses--deferred-narrow
2011 ;; We're not allowed to narrow the buffer until after-find-file has
2012 ;; read the local variables at the end of the file. Now it's safe to
2013 ;; do the narrowing.
2014 (narrow-to-region (point-min) ses--data-marker)
2015 (setq ses--deferred-narrow nil))
2016 ;; Update the mode line.
2017 (let ((oldcell ses--curcell))
2019 (unless (eq ses--curcell oldcell)
2022 (setq mode-line-process nil))
2023 ((atom ses--curcell)
2024 (setq mode-line-process (list " cell "
2025 (symbol-name ses--curcell))))
2027 (setq mode-line-process (list " range "
2028 (symbol-name (car ses--curcell))
2030 (symbol-name (cdr ses--curcell))))))
2031 (force-mode-line-update)))
2032 ;; Use underline overlay for single-cells only, turn off otherwise.
2033 (if (listp ses--curcell)
2034 (move-overlay ses--curcell-overlay 2 2)
2035 (let ((next (next-single-property-change (point) 'intangible)))
2036 (move-overlay ses--curcell-overlay (point) (1- next))))
2037 (when (not (pos-visible-in-window-p))
2038 ;; Scrolling will happen later.
2039 (run-with-idle-timer 0.01 nil 'ses-command-hook)
2040 (setq ses--curcell t)))
2041 ;; Prevent errors in this post-command-hook from silently erasing the hook!
2043 (unless executing-kbd-macro
2045 (message "%s" (error-message-string err))))
2046 nil) ; Make coverage-tester happy.
2048 (defun ses-create-header-string ()
2049 "Set up `ses--header-string' as the buffer's header line.
2050 Based on the current set of columns and `window-hscroll' position."
2051 (let ((totwidth (- (window-hscroll)))
2053 ;; Leave room for the left-side fringe and scrollbar.
2054 (push (propertize " " 'display '((space :align-to 0))) result)
2055 (dotimes (col ses--numcols)
2056 (setq width (ses-col-width col)
2057 totwidth (+ totwidth width 1))
2059 ;; Scrolled so intercolumn space is leftmost.
2061 (when (> totwidth 1)
2062 (if (> ses--header-row 0)
2064 (ses-goto-print (1- ses--header-row) col)
2065 (setq x (buffer-substring-no-properties (point)
2067 ;; Strip trailing space.
2068 (if (string-match "[ \t]+\\'" x)
2069 (setq x (substring x 0 (match-beginning 0))))
2070 ;; Cut off excess text.
2071 (if (>= (length x) totwidth)
2072 (setq x (substring x 0 (- totwidth -1)))))
2073 (setq x (ses-column-letter col)))
2074 (push (propertize x 'face ses-box-prop) result)
2075 (push (propertize "."
2076 'display `((space :align-to ,(1- totwidth)))
2079 ;; Allow the following space to be squished to make room for the 3-D box
2080 ;; Coverage test ignores properties, thinks this is always a space!
2081 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2083 (if (> ses--header-row 0)
2084 (push (propertize (format " [row %d]" ses--header-row)
2085 'display '((height (- 1))))
2087 (setq ses--header-string (apply 'concat (nreverse result)))))
2090 ;;----------------------------------------------------------------------------
2091 ;; Redisplay and recalculation
2092 ;;----------------------------------------------------------------------------
2094 (defun ses-jump (sym)
2095 "Move point to cell SYM."
2096 (interactive "SJump to cell: ")
2097 (let ((rowcol (ses-sym-rowcol sym)))
2098 (or rowcol (error "Invalid cell name"))
2099 (if (eq (symbol-value sym) '*skip*)
2100 (error "Cell is covered by preceding cell"))
2101 (ses-goto-print (car rowcol) (cdr rowcol))))
2103 (defun ses-jump-safe (cell)
2104 "Like `ses-jump', but no error if invalid cell."
2108 (defun ses-reprint-all (&optional nonarrow)
2109 "Recreate the display area. Calls all printer functions. Narrows to
2110 print area if NONARROW is nil."
2114 (setq ses--deferred-narrow t))
2115 (let ((startcell (get-text-property (point) 'intangible))
2116 (inhibit-read-only t))
2118 (goto-char (point-min))
2119 (search-forward ses-print-data-boundary)
2120 (backward-char (length ses-print-data-boundary))
2121 (delete-region (point-min) (point))
2122 ;; Insert all blank lines before printing anything, so ses-print-cell can
2123 ;; find the data area when inserting or deleting *skip* values for cells.
2124 (dotimes (row ses--numrows)
2125 (insert-and-inherit ses--blank-line))
2126 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2127 (if (eq (ses-cell-value row 0) '*skip*)
2128 ;; Column deletion left a dangling skip.
2129 (ses-set-cell row 0 'value nil))
2130 (dotimes (col ses--numcols)
2131 (ses-print-cell row col))
2132 (beginning-of-line 2))
2133 (ses-jump-safe startcell)))
2135 (defun ses-initialize-Dijkstra-attempt ()
2136 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2137 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2139 (defun ses-recalculate-cell ()
2140 "Recalculate and reprint the current cell or range.
2142 For an individual cell, shows the error if the formula or printer
2143 signals one, or otherwise shows the cell's complete value. For a range, the
2144 cells are recalculated in \"natural\" order, so cells that other cells refer
2145 to are recalculated first."
2147 (ses-check-curcell 'range)
2149 (ses-initialize-Dijkstra-attempt)
2150 (let (sig cur-rowcol)
2151 (setq ses-start-time (float-time))
2152 (if (atom ses--curcell)
2154 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2156 (ses-cell-property-set :ses-Dijkstra-attempt
2157 (cons ses--Dijkstra-attempt-nb 0)
2158 (car cur-rowcol) (cdr cur-rowcol) )
2159 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2160 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2161 (cdr cur-rowcol)))))
2162 ;; First, recalculate all cells that don't refer to other cells and
2163 ;; produce a list of cells with references.
2164 (ses-dorange ses--curcell
2165 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
2168 ;; The t causes an error if the cell has references. If no
2169 ;; references, the t will be the result value.
2170 (1value (ses-formula-references (ses-cell-formula row col) t))
2171 (ses-cell-property-set :ses-Dijkstra-attempt
2172 (cons ses--Dijkstra-attempt-nb 0)
2174 (when (setq sig (ses-calculate-cell row col t))
2175 (nconc sig (list (ses-cell-symbol row col)))))
2176 (wrong-type-argument
2177 ;; The formula contains a reference.
2178 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
2179 ;; Do the update now, so we can force recalculation.
2180 (let ((x ses--deferred-recalc))
2181 (setq ses--deferred-recalc nil)
2182 (condition-case hold
2183 (ses-update-cells x t)
2184 (error (setq sig hold))))
2187 (message "%s" (error-message-string sig)))
2188 ((consp ses--curcell)
2191 (princ (symbol-value ses--curcell))))))
2193 (defun ses-recalculate-all ()
2194 "Recalculate and reprint all cells."
2196 (let ((startcell (get-text-property (point) 'intangible))
2197 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2198 (1- ses--numcols)))))
2199 (ses-recalculate-cell)
2200 (ses-jump-safe startcell)))
2202 (defun ses-truncate-cell ()
2203 "Reprint current cell, but without spillover into any following blank cells."
2206 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2209 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
2210 (eq (ses-cell-value row (1+ col)) '*skip*))
2211 ;; This cell has spill-over. We'll momentarily pretend the following cell
2213 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
2214 (ses-print-cell row col)))
2215 ;; Now remove the *skip*. ses-print-cell is always nil here.
2216 (ses-set-cell row (1+ col) 'value nil)
2217 (1value (ses-print-cell row (1+ col))))))
2219 (defun ses-reconstruct-all ()
2220 "Reconstruct buffer based on cell data stored in Emacs variables."
2223 ;;Reconstruct reference lists.
2225 ;;Delete old reference lists
2226 (dotimes-with-progress-reporter
2227 (row ses--numrows) "Deleting references..."
2228 (dotimes (col ses--numcols)
2229 (ses-set-cell row col 'references nil)))
2230 ;;Create new reference lists
2231 (dotimes-with-progress-reporter
2232 (row ses--numrows) "Computing references..."
2233 (dotimes (col ses--numcols)
2234 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2235 (setq x (ses-sym-rowcol ref)
2238 (ses-set-cell yrow ycol 'references
2239 (cons (ses-cell-symbol row col)
2240 (ses-cell-references yrow ycol)))))))
2241 ;; Delete everything and reconstruct basic data area.
2243 (let ((inhibit-read-only t))
2244 (goto-char (point-max))
2245 (if (search-backward ";; Local Variables:\n" nil t)
2246 (delete-region (point-min) (point))
2247 ;; Buffer is quite screwed up --- can't even save the user-specified
2249 (delete-region (point-min) (point-max))
2250 (insert ses-initial-file-trailer)
2251 (goto-char (point-min)))
2252 ;; Create a blank display area.
2253 (dotimes (row ses--numrows)
2254 (insert ses--blank-line))
2255 (insert ses-print-data-boundary)
2256 (backward-char (1- (length ses-print-data-boundary)))
2257 (setq ses--data-marker (point-marker))
2258 (forward-char (1- (length ses-print-data-boundary)))
2259 ;; Placeholders for cell data.
2260 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2261 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
2263 (insert ses-initial-global-parameters)
2264 (backward-char (1- (length ses-initial-global-parameters)))
2265 (setq ses--params-marker (point-marker))
2266 (forward-char (1- (length ses-initial-global-parameters))))
2267 (ses-set-parameter 'ses--col-widths ses--col-widths)
2268 (ses-set-parameter 'ses--col-printers ses--col-printers)
2269 (ses-set-parameter 'ses--default-printer ses--default-printer)
2270 (ses-set-parameter 'ses--header-row ses--header-row)
2271 (ses-set-parameter 'ses--numrows ses--numrows)
2272 (ses-set-parameter 'ses--numcols ses--numcols)
2273 ;;Keep our old narrowing
2275 (ses-recalculate-all)
2276 (goto-char (point-min)))
2279 ;;----------------------------------------------------------------------------
2280 ;; Input of cell formulas
2281 ;;----------------------------------------------------------------------------
2283 (defun ses-edit-cell (row col newval)
2284 "Display current cell contents in minibuffer, for editing. Returns nil if
2285 cell formula was unsafe and user declined confirmation."
2288 (barf-if-buffer-read-only)
2290 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2293 (formula (ses-cell-formula row col))
2295 (if (eq (car-safe formula) 'ses-safe-formula)
2296 (setq formula (cadr formula)))
2297 (if (eq (car-safe formula) 'quote)
2298 (setq initial (format "'%S" (cadr formula)))
2299 (setq initial (prin1-to-string formula)))
2300 (if (stringp formula)
2301 ;; Position cursor inside close-quote.
2302 (setq initial (cons initial (length initial))))
2304 (read-from-minibuffer (format "Cell %s: " ses--curcell)
2307 t ; Convert to Lisp object.
2308 'ses-read-cell-history)))))
2309 (when (ses-warn-unsafe newval 'unsafep)
2311 (ses-cell-set-formula row col newval)
2314 (defun ses-read-cell (row col newval)
2315 "Self-insert for initial character of cell function."
2317 (let* ((initial (this-command-keys))
2318 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2319 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
2320 (barf-if-buffer-read-only)
2323 (read-from-minibuffer
2324 (format "Cell %s: " ses--curcell)
2325 (cons (if (equal initial "\"") "\"\""
2326 (if (equal initial "(") "()" initial)) 2)
2328 t ; Convert to Lisp object.
2329 'ses-read-cell-history
2330 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2333 (when (ses-edit-cell row col newval)
2334 (ses-command-hook) ; Update cell widths before movement.
2335 (dolist (x ses-after-entry-functions)
2338 (defun ses-read-symbol (row col symb)
2339 "Self-insert for a symbol as a cell formula. The set of all symbols that
2340 have been used as formulas in this spreadsheet is available for completions."
2342 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2344 (barf-if-buffer-read-only)
2345 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2346 ses--symbolic-formulas))
2349 (if (string= newval "")
2350 nil ; Don't create zero-length symbols!
2351 (list 'quote (intern newval))))))
2352 (when (ses-edit-cell row col symb)
2353 (ses-command-hook) ; Update cell widths before movement.
2354 (dolist (x ses-after-entry-functions)
2357 (defun ses-clear-cell-forward (count)
2358 "Delete formula and printer for current cell and then move to next cell.
2359 With prefix, deletes several cells."
2362 (1value (ses-clear-cell-backward (- count)))
2367 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2368 (or rowcol (signal 'end-of-buffer nil))
2369 (ses-clear-cell (car rowcol) (cdr rowcol)))
2372 (defun ses-clear-cell-backward (count)
2373 "Move to previous cell and then delete it. With prefix, deletes several
2377 (1value (ses-clear-cell-forward (- count)))
2378 (ses-check-curcell 'end)
2381 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
2383 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2384 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2387 ;;----------------------------------------------------------------------------
2388 ;; Input of cell-printer functions
2389 ;;----------------------------------------------------------------------------
2391 (defun ses-read-printer (prompt default)
2392 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
2393 PROMPT should end with \": \". Result is t if operation was canceled."
2394 (barf-if-buffer-read-only)
2397 (setq prompt (format "%s [currently %S]: "
2398 (substring prompt 0 -2)
2400 (let ((new (read-from-minibuffer prompt
2401 nil ; Initial contents.
2403 t ; Evaluate the result.
2404 'ses-read-printer-history
2405 (prin1-to-string default))))
2406 (if (equal new default)
2407 ;; User changed mind, decided not to change printer.
2409 (ses-printer-validate new)
2412 (stringp (car-safe new))
2413 (ses-warn-unsafe new 'unsafep-function)
2417 (defun ses-read-cell-printer (newval)
2418 "Set the printer function for the current cell or range.
2420 A printer function is either a string (a format control-string with one
2421 %-sequence -- result from format will be right-justified), or a list of one
2422 string (result from format will be left-justified), or a lambda-expression of
2423 one argument, or a symbol that names a function of one argument. In the
2424 latter two cases, the function's result should be either a string (will be
2425 right-justified) or a list of one string (will be left-justified)."
2429 (ses-check-curcell 'range)
2430 ;;Default is none if not all cells in range have same printer
2431 (catch 'ses-read-cell-printer
2432 (ses-dorange ses--curcell
2433 (setq x (ses-cell-printer row col))
2434 (if (eq (car-safe x) 'ses-safe-printer)
2438 (unless (equal default x)
2439 ;;Range contains differing printer functions
2441 (throw 'ses-read-cell-printer t)))))
2442 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2444 (unless (eq newval t)
2446 (ses-dorange ses--curcell
2447 (ses-set-cell row col 'printer newval)
2448 (ses-print-cell row col))))
2450 (defun ses-read-column-printer (col newval)
2451 "Set the printer function for the current column.
2452 See `ses-read-cell-printer' for input forms."
2454 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2456 (list col (ses-read-printer (format "Column %s printer: "
2457 (ses-column-letter col))
2458 (ses-col-printer col)))))
2460 (unless (eq newval t)
2462 (ses-set-parameter 'ses--col-printers newval col)
2464 (dotimes (row ses--numrows)
2465 (ses-print-cell row col)))))
2467 (defun ses-read-default-printer (newval)
2468 "Set the default printer function for cells that have no other.
2469 See `ses-read-cell-printer' for input forms."
2471 (list (ses-read-printer "Default printer: " ses--default-printer)))
2472 (unless (eq newval t)
2474 (ses-set-parameter 'ses--default-printer newval)
2475 (ses-reprint-all t)))
2478 ;;----------------------------------------------------------------------------
2479 ;; Spreadsheet size adjustments
2480 ;;----------------------------------------------------------------------------
2482 (defun ses-insert-row (count)
2483 "Insert a new row before the current one.
2484 With prefix, insert COUNT rows before current one."
2486 (ses-check-curcell 'end)
2487 (or (> count 0) (signal 'args-out-of-range nil))
2489 (let ((inhibit-quit t)
2490 (inhibit-read-only t)
2491 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2493 ;;Create a new set of cell-variables
2494 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2495 0 (1- ses--numcols))
2496 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2498 (ses-goto-print row 0)
2499 (dotimes-with-progress-reporter (x count) "Inserting row..."
2500 ;;Create a row of empty cells. The `symbol' fields will be set by
2501 ;;the call to ses-relocate-all.
2502 (setq newrow (make-vector ses--numcols nil))
2503 (dotimes (col ses--numcols)
2504 (aset newrow col (ses-make-cell)))
2505 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2506 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2507 (insert ses--blank-line))
2508 ;;Insert empty lines in cell data area (will be replaced by
2510 (ses-goto-data row 0)
2511 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2512 (ses-relocate-all row 0 count 0)
2513 ;;If any cell printers insert constant text, insert that text
2515 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2516 (global (ses-call-printer ses--default-printer)))
2517 (if (or (> (length cols) 0) (> (length global) 0))
2519 (dotimes (col ses--numcols)
2520 ;;These cells are always nil, only constant formatting printed
2521 (1value (ses-print-cell (+ x row) col))))))
2522 (when (> ses--header-row row)
2523 ;;Inserting before header
2524 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2525 (ses-reset-header-string)))
2526 ;;Reconstruct text attributes
2529 (push '(apply ses-widen) buffer-undo-list)
2530 ;;Return to current cell
2532 (ses-jump-safe ses--curcell)
2533 (ses-goto-print (1- ses--numrows) 0)))
2535 (defun ses-delete-row (count)
2536 "Delete the current row.
2537 With prefix, deletes COUNT rows starting from the current one."
2540 (or (> count 0) (signal 'args-out-of-range nil))
2541 (let ((inhibit-quit t)
2542 (inhibit-read-only t)
2543 (row (car (ses-sym-rowcol ses--curcell))))
2544 (setq count (min count (- ses--numrows row)))
2546 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2547 ;;Delete lines from print area
2548 (ses-goto-print row 0)
2549 (ses-delete-line count)
2550 ;;Delete lines from cell data area
2551 (ses-goto-data row 0)
2552 (ses-delete-line (* count (1+ ses--numcols)))
2553 ;;Relocate variables and formulas
2554 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2555 (ses-relocate-all row 0 (- count) 0)
2556 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2557 0 (1- ses--numcols))
2558 (when (> ses--header-row row)
2559 (if (<= ses--header-row (+ row count))
2560 ;;Deleting the header row
2561 (ses-set-parameter 'ses--header-row 0)
2562 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2563 (ses-reset-header-string)))
2564 ;;Reconstruct attributes
2567 (push '(apply ses-widen) buffer-undo-list)
2568 (ses-jump-safe ses--curcell))
2570 (defun ses-insert-column (count &optional col width printer)
2571 "Insert a new column before COL (default is the current one).
2572 With prefix, insert COUNT columns before current one.
2573 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2574 \(otherwise they're taken from the current column)."
2577 (or (> count 0) (signal 'args-out-of-range nil))
2579 (setq col (cdr (ses-sym-rowcol ses--curcell))
2580 width (ses-col-width col)
2581 printer (ses-col-printer col)))
2583 (let ((inhibit-quit t)
2584 (inhibit-read-only t)
2585 (widths ses--col-widths)
2586 (printers ses--col-printers)
2588 ;;Create a new set of cell-variables
2589 (ses-create-cell-variable-range 0 (1- ses--numrows)
2590 ses--numcols (+ ses--numcols count -1))
2591 ;;Insert each column.
2592 (dotimes-with-progress-reporter (x count) "Inserting column..."
2593 ;;Create a column of empty cells. The `symbol' fields will be set by
2594 ;;the call to ses-relocate-all.
2595 (ses-adjust-print-width col (1+ width))
2596 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2597 (dotimes (row ses--numrows)
2598 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2599 ;;Inserting in the middle of a spill-over
2601 (ses-aset-with-undo ses--cells row
2602 (ses-vector-insert (aref ses--cells row)
2603 col (ses-make-cell)))
2604 ;;Insert empty lines in cell data area (will be replaced by
2606 (ses-goto-data row col)
2608 ;; Insert column width and printer.
2609 (setq widths (ses-vector-insert widths col width)
2610 printers (ses-vector-insert printers col printer)))
2611 (ses-set-parameter 'ses--col-widths widths)
2612 (ses-set-parameter 'ses--col-printers printers)
2613 (ses-reset-header-string)
2614 (ses-relocate-all 0 col 0 count)
2617 (when (or (> (length (ses-call-printer printer)) 0)
2618 (> (length (ses-call-printer ses--default-printer)) 0))
2619 ;; Either column printer or global printer inserts some constant text.
2620 ;; Reprint the new columns to insert that text.
2621 (dotimes (x ses--numrows)
2623 ;; Always nil here --- this is a blank column.
2624 (1value (ses-print-cell-new-width x (+ y col))))))
2626 (ses-jump-safe ses--curcell))
2628 (defun ses-delete-column (count)
2629 "Delete the current column.
2630 With prefix, deletes COUNT columns starting from the current one."
2633 (or (> count 0) (signal 'args-out-of-range nil))
2634 (let ((inhibit-quit t)
2635 (inhibit-read-only t)
2636 (rowcol (ses-sym-rowcol ses--curcell))
2638 col origrow has-skip)
2639 (setq origrow (car rowcol)
2641 count (min count (- ses--numcols col)))
2642 (if (= count ses--numcols)
2643 (error "Can't delete all columns!"))
2644 ;;Determine width of column(s) being deleted
2646 (setq width (+ width (ses-col-width (+ col x)) 1)))
2648 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2649 (ses-adjust-print-width col (- width))
2650 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2651 ;;Delete lines from cell data area
2652 (ses-goto-data row col)
2653 (ses-delete-line count)
2654 ;;Delete cells. Check if deletion area begins or ends with a skip.
2655 (if (or (eq (ses-cell-value row col) '*skip*)
2656 (and (< col ses--numcols)
2657 (eq (ses-cell-value row (+ col count)) '*skip*)))
2659 (ses-aset-with-undo ses--cells row
2660 (ses-vector-delete (aref ses--cells row) col count)))
2662 (ses-set-parameter 'ses--col-widths
2663 (ses-vector-delete ses--col-widths col count))
2664 (ses-set-parameter 'ses--col-printers
2665 (ses-vector-delete ses--col-printers col count))
2666 (ses-reset-header-string)
2667 ;;Relocate variables and formulas
2668 (ses-relocate-all 0 col 0 (- count))
2669 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2670 ses--numcols (+ ses--numcols count -1))
2674 (if (>= col ses--numcols)
2675 (setq col (1- col)))
2676 (ses-goto-print origrow col)))
2678 (defun ses-forward-or-insert (&optional count)
2679 "Move to next cell in row, or inserts a new cell if already in last one, or
2680 inserts a new row if at bottom of print area. Repeat COUNT times."
2682 (ses-check-curcell 'end)
2683 (setq deactivate-mark t) ; Doesn't combine well with ranges.
2686 (if (not ses--curcell)
2687 (progn ; At bottom of print area.
2688 (barf-if-buffer-read-only)
2690 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2692 (char-before (next-single-property-change (point)
2694 ;; We're already in last nonskipped cell on line. Need to create a
2696 (barf-if-buffer-read-only)
2697 (ses-insert-column (- count x)
2700 (ses-col-printer col)))))
2703 (defun ses-append-row-jump-first-column ()
2704 "Insert a new row after current one and jump to its first column."
2708 (beginning-of-line 2)
2712 (defun ses-set-column-width (col newwidth)
2713 "Set the width of the current column."
2715 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2716 (barf-if-buffer-read-only)
2718 (if current-prefix-arg
2719 (prefix-numeric-value current-prefix-arg)
2720 (read-from-minibuffer (format "Column %s width [currently %d]: "
2721 (ses-column-letter col)
2722 (ses-col-width col))
2723 nil ; No initial contents.
2724 nil ; No override keymap.
2725 t ; Convert to Lisp object.
2728 (ses-col-width col))))))) ; Default value.
2730 (error "Invalid column width"))
2732 (ses-reset-header-string)
2734 (let ((inhibit-quit t))
2735 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2736 (ses-set-parameter 'ses--col-widths newwidth col))
2737 (dotimes (row ses--numrows)
2738 (ses-print-cell-new-width row col))))
2741 ;;----------------------------------------------------------------------------
2742 ;; Cut and paste, import and export
2743 ;;----------------------------------------------------------------------------
2745 (defun ses--advice-copy-region-as-kill (crak-fun beg end &rest args)
2746 ;; FIXME: Why doesn't it make sense to copy read-only or
2747 ;; intangible attributes? They're removed upon yank!
2748 "It doesn't make sense to copy read-only or intangible attributes into the
2749 kill ring. It probably doesn't make sense to copy keymap properties.
2750 We'll assume copying front-sticky properties doesn't make sense, either.
2752 This advice also includes some SES-specific code because otherwise it's too
2753 hard to override how mouse-1 works."
2758 (if (not (and (derived-mode-p 'ses-mode)
2759 (eq (get-text-property beg 'read-only) 'ses)
2760 (eq (get-text-property (1- end) 'read-only) 'ses)))
2761 (apply crak-fun beg end args) ; Normal copy-region-as-kill.
2762 (kill-new (ses-copy-region beg end))
2763 (if transient-mark-mode
2764 (setq deactivate-mark t))
2766 (advice-add 'copy-region-as-kill :around #'ses--advice-copy-region-as-kill)
2768 (defun ses-copy-region (beg end)
2769 "Treat the region as rectangular. Convert the intangible attributes to
2770 SES attributes recording the contents of the cell as of the time of copying."
2771 (when (= end ses--data-marker)
2772 ;;Avoid overflow situation
2773 (setq end (1- ses--data-marker)))
2774 (let* ((inhibit-point-motion-hooks t)
2775 (x (mapconcat 'ses-copy-region-helper
2776 (extract-rectangle beg (1- end)) "\n")))
2777 (remove-text-properties 0 (length x)
2785 (defun ses-copy-region-helper (line)
2786 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2787 external form by attaching to each print cell a 'ses attribute that records
2788 the corresponding data cell."
2789 (or (> (length line) 1)
2790 (error "Empty range"))
2791 (let ((inhibit-read-only t)
2793 mycell next sym rowcol)
2795 (setq sym (get-text-property pos 'intangible line)
2796 next (next-single-property-change pos 'intangible line)
2797 rowcol (ses-sym-rowcol sym)
2798 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2799 (put-text-property pos (or next (length line))
2801 (list (ses-cell-symbol mycell)
2802 (ses-cell-formula mycell)
2803 (ses-cell-printer mycell))
2808 (defun ses-kill-override (beg end)
2809 "Generic override for any commands that kill text.
2810 We clear the killed cells instead of deleting them."
2812 (ses-check-curcell 'needrange)
2813 ;; For some reason, the text-read-only error is not caught by `delete-region',
2814 ;; so we have to use subterfuge.
2815 (let ((buffer-read-only t))
2816 (1value (condition-case nil
2817 (noreturn (funcall (lookup-key (current-global-map)
2818 (this-command-keys))
2820 (buffer-read-only nil)))) ; The expected error.
2821 ;; Because the buffer was marked read-only, the kill command turned itself
2822 ;; into a copy. Now we clear the cells or signal the error. First we check
2823 ;; whether the buffer really is read-only.
2824 (barf-if-buffer-read-only)
2826 (ses-dorange ses--curcell
2827 (ses-clear-cell row col))
2828 (ses-jump (car ses--curcell)))
2830 (defun ses--advice-yank (yank-fun &optional arg &rest args)
2831 "In SES mode, the yanked text is inserted as cells.
2833 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2834 SES buffer), the formulas and print functions are restored for the cells. If
2835 the text contains tabs, this is an insertion of tab-separated formulas.
2836 Otherwise the text is inserted as the formula for the current cell.
2838 When inserting cells, the formulas are usually relocated to keep the same
2839 relative references to neighboring cells. This is best if the formulas
2840 generally refer to other cells within the yanked text. You can use the C-u
2841 prefix to specify insertion without relocation, which is best when the
2842 formulas refer to cells outside the yanked text.
2844 When inserting formulas, the text is treated as a string constant if it doesn't
2845 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2846 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2848 (if (not (and (derived-mode-p 'ses-mode)
2849 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2850 (apply yank-fun arg args) ; Normal non-SES yank.
2851 (ses-check-curcell 'end)
2853 (let ((text (current-kill (cond
2857 (or (ses-yank-cells text arg)
2858 (ses-yank-tsf text arg)
2859 (ses-yank-one (ses-yank-resize 1 1)
2862 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2863 ;; Just one cell --- delete final tab or newline.
2867 (exchange-point-and-mark))))
2868 (advice-add 'yank :around #'ses--advice-yank)
2870 (defun ses-yank-pop (arg)
2871 "Replace just-yanked stretch of killed text with a different stretch.
2872 This command is allowed only immediately after a `yank' or a `yank-pop',
2873 when the region contains a stretch of reinserted previously-killed text.
2874 We replace it with a different stretch of killed text.
2875 Unlike standard `yank-pop', this function uses `undo' to delete the
2876 previous insertion."
2878 (or (eq last-command 'yank)
2879 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2881 (noreturn (error "Previous command was not a yank")))
2884 (yank (1+ (or arg 1)))
2885 (setq this-command 'yank))
2887 (defun ses-yank-cells (text arg)
2888 "If the TEXT has a proper set of 'ses attributes, insert the text as
2889 cells, else return nil. The cells are reprinted--the supplied text is
2890 ignored because the column widths, default printer, etc. at yank time might
2891 be different from those at kill-time. ARG is a list to indicate that
2892 formulas are to be inserted without relocation."
2893 (let ((first (get-text-property 0 'ses text))
2894 (last (get-text-property (1- (length text)) 'ses text)))
2895 (when (and first last) ;;Otherwise not proper set of attributes
2896 (setq first (ses-sym-rowcol (car first))
2897 last (ses-sym-rowcol (car last)))
2898 (let* ((needrows (- (car last) (car first) -1))
2899 (needcols (- (cdr last) (cdr first) -1))
2900 (rowcol (ses-yank-resize needrows needcols))
2901 (rowincr (- (car rowcol) (car first)))
2902 (colincr (- (cdr rowcol) (cdr first)))
2905 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2906 (setq myrow (+ row (car rowcol)))
2907 (dotimes (col needcols)
2908 (setq mycol (+ col (cdr rowcol))
2909 last (get-text-property pos 'ses text)
2910 pos (next-single-property-change pos 'ses text)
2911 x (ses-sym-rowcol (car last)))
2913 ;; Newline --- all remaining cells on row are skipped.
2914 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2915 last (list nil nil nil)
2917 (if (/= (car x) (- myrow rowincr))
2918 (error "Cell row error"))
2919 (if (< (- mycol colincr) (cdr x))
2920 ;; Some columns were skipped.
2921 (let ((oldcol mycol))
2922 (while (< (- mycol colincr) (cdr x))
2923 (ses-clear-cell myrow mycol)
2926 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
2927 (when (car last) ; Skip this for *skip* cells.
2928 (setq x (nth 2 last))
2929 (unless (equal x (ses-cell-printer myrow mycol))
2932 (eq (car-safe x) 'ses-safe-printer)
2933 (setq x `(ses-safe-printer ,x)))
2934 (ses-set-cell myrow mycol 'printer x))
2935 (setq x (cadr last))
2937 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2939 (eq (car-safe x) 'ses-safe-formula)
2940 (setq x `(ses-safe-formula ,x)))
2941 (ses-cell-set-formula myrow mycol x)))
2943 (if (get-text-property pos 'ses text)
2944 (error "Missing newline between rows"))
2945 (setq pos (next-single-property-change pos 'ses text))))
2948 (defun ses-yank-one (rowcol text from to arg)
2949 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2950 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2951 (let ((val (condition-case nil
2952 (read-from-string text from to)
2953 (error (cons nil from)))))
2955 ((< (cdr val) (or to (length text)))
2956 ;; Invalid sexp --- leave it as a string.
2957 (setq val (substring text from to)))
2958 ((and (car val) (symbolp (car val)))
2960 (setq val (list 'quote (car val))) ; Keep symbol.
2961 (setq val (substring text from to)))) ; Treat symbol as text.
2963 (setq val (car val))))
2964 (let ((row (car rowcol))
2967 (setq val `(ses-safe-formula ,val)))
2968 (ses-cell-set-formula row col val))))
2970 (defun ses-yank-tsf (text arg)
2971 "If TEXT contains tabs and/or newlines, treat the tabs as
2972 column-separators and the newlines as row-separators and insert the text as
2973 cell formulas--else return nil. Treat plain symbols as strings unless ARG
2974 is a list. Ignore a final newline."
2975 (if (or (not (string-match "[\t\n]" text))
2976 (= (match-end 0) (length text)))
2979 (if (/= (aref text (1- (length text))) ?\n)
2980 (setq text (concat text "\n")))
2986 ;;Find all the tabs and newlines
2987 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
2989 (setq cols (1+ cols))
2990 (when (eq (aref text pos) ?\n)
2992 (setq needcols cols)
2993 (or (= needcols cols)
2994 (error "Inconsistent row lengths")))
2996 needrows (1+ needrows))))
2997 ;;Insert the formulas
2998 (setq rowcol (ses-yank-resize needrows needcols))
2999 (dotimes (row needrows)
3000 (dotimes (col needcols)
3001 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
3002 (+ (cdr rowcol) needcols (- col) -1))
3003 text (1+ (cadr spots)) (car spots) arg)
3004 (setq spots (cdr spots))))
3005 (ses-goto-print (+ (car rowcol) needrows -1)
3006 (+ (cdr rowcol) needcols -1))
3009 (defun ses-yank-resize (needrows needcols)
3010 "If this yank will require inserting rows and/or columns, ask for
3011 confirmation and then insert them. Result is (row,col) for top left of yank
3012 spot, or error signal if user requests cancel."
3014 (let ((rowcol (if ses--curcell
3015 (ses-sym-rowcol ses--curcell)
3016 (cons ses--numrows 0)))
3018 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
3019 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
3020 rowbool (> needrows 0)
3021 colbool (> needcols 0))
3022 (when (or rowbool colbool)
3023 ;;Need to insert. Get confirm
3024 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
3025 (if rowbool (format "%d rows" needrows) "")
3026 (if (and rowbool colbool) " and " "")
3027 (if colbool (format "%d columns" needcols) "")))
3032 (ses-goto-print ses--numrows 0)
3033 (ses-insert-row needrows))))
3035 (ses-insert-column needcols
3037 (ses-col-width (1- ses--numcols))
3038 (ses-col-printer (1- ses--numcols)))))
3041 (defun ses-export-tsv (_beg _end)
3042 "Export values from the current range, with tabs between columns and
3043 newlines between rows. Result is placed in kill ring."
3045 (ses-export-tab nil))
3047 (defun ses-export-tsf (_beg _end)
3048 "Export formulas from the current range, with tabs between columns and
3049 newlines between rows. Result is placed in kill ring."
3053 (defun ses-export-tab (want-formulas)
3054 "Export the current range with tabs between columns and newlines between rows.
3055 Result is placed in kill ring. The export is values unless WANT-FORMULAS
3056 is non-nil. Newlines and tabs in the export text are escaped."
3057 (ses-check-curcell 'needrange)
3058 (let ((print-escape-newlines t)
3060 (ses-dorange ses--curcell
3061 (setq item (if want-formulas
3062 (ses-cell-formula row col)
3063 (ses-cell-value row col)))
3064 (if (eq (car-safe item) 'ses-safe-formula)
3065 ;;Hide our deferred safety-check marker
3066 (setq item (cadr item)))
3067 (if (or (not item) (eq item '*skip*))
3069 (when (eq (car-safe item) 'quote)
3071 (setq item (cadr item)))
3072 (setq item (prin1-to-string item t))
3073 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
3079 (push "\n" result))))
3080 (setq result (apply 'concat (nreverse result)))
3084 ;;----------------------------------------------------------------------------
3085 ;; Other user commands
3086 ;;----------------------------------------------------------------------------
3088 (defun ses-unset-header-row ()
3089 "Select the default header row."
3091 (ses-set-header-row 0))
3093 (defun ses-set-header-row (row)
3094 "Set the ROW to display in the header-line.
3095 With a numerical prefix arg, use that row.
3096 With no prefix arg, use the current row.
3097 With a \\[universal-argument] prefix arg, prompt the user.
3098 The top row is row 1. Selecting row 0 displays the default header row."
3100 (list (if (numberp current-prefix-arg) current-prefix-arg
3101 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3102 (if current-prefix-arg
3103 (read-number "Header row: " currow)
3105 (if (or (< row 0) (> row ses--numrows))
3106 (error "Invalid header-row"))
3108 (let ((oldval ses--header-row))
3109 (let (buffer-undo-list)
3110 (ses-set-parameter 'ses--header-row row))
3111 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
3112 (ses-reset-header-string))
3114 (defun ses-mark-row ()
3115 "Mark the entirety of current row as a range."
3117 (ses-check-curcell 'range)
3118 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
3120 (ses-goto-print (1+ row) 0)
3121 (push-mark (point) nil t)
3122 (ses-goto-print row 0)))
3124 (defun ses-mark-column ()
3125 "Mark the entirety of current column as a range."
3127 (ses-check-curcell 'range)
3128 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
3131 (ses-goto-print (1- ses--numrows) col)
3133 (push-mark (point) nil t)
3134 (while (eq '*skip* (ses-cell-value row col))
3135 ;;Skip over initial cells in column that can't be selected
3136 (setq row (1+ row)))
3137 (ses-goto-print row col)))
3139 (defun ses-end-of-line ()
3140 "Move point to last cell on line."
3142 (ses-check-curcell 'end 'range)
3143 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3145 (let ((col (1- ses--numcols))
3147 (if (symbolp ses--curcell)
3149 (setq row (car (ses-sym-rowcol ses--curcell)))
3150 ;; Range --- use whichever end of the range the point is at.
3151 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
3153 (cdr ses--curcell))))
3154 ;; If range already includes the last cell in a row, point is actually
3155 ;; in the following row.
3156 (if (<= (cdr rowcol) (1- col))
3157 (setq row (car rowcol))
3158 (setq row (1+ (car rowcol)))
3159 (if (= row ses--numrows)
3160 ;;Already at end - can't go anywhere
3162 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
3163 (while (eq (ses-cell-value row col) '*skip*)
3164 ;; Back to beginning of multi-column cell.
3165 (setq col (1- col)))
3166 (ses-goto-print row col)))))
3168 (defun ses-renarrow-buffer ()
3169 "Narrow the buffer so only the print area is visible.
3170 Use after \\[widen]."
3172 (setq ses--deferred-narrow t))
3174 (defun ses-sort-column (sorter &optional reverse)
3175 "Sort the range by a specified column.
3176 With prefix, sorts in REVERSE order."
3177 (interactive "*sSort column: \nP")
3178 (ses-check-curcell 'needrange)
3179 (let ((min (ses-sym-rowcol (car ses--curcell)))
3180 (max (ses-sym-rowcol (cdr ses--curcell))))
3181 (let ((minrow (car min))
3186 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3187 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3188 (error "Invalid sort column"))
3189 ;;Get key columns and sort them
3190 (dotimes (x (- maxrow minrow -1))
3191 (ses-goto-print (+ minrow x) sorter)
3192 (setq end (next-single-property-change (point) 'intangible))
3193 (push (cons (buffer-substring-no-properties (point) end)
3196 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3197 ;;Extract the lines in reverse sorted order
3199 (setq keys (nreverse keys)))
3201 (ses-goto-print (cdr x) (1+ maxcol))
3203 (ses-goto-print (cdr x) mincol)
3204 (push (ses-copy-region (point) end) extracts))
3206 ;;Paste the lines sequentially
3207 (dotimes (x (- maxrow minrow -1))
3208 (ses-goto-print (+ minrow x) mincol)
3210 (ses-yank-cells (pop extracts) nil)))))
3212 (defun ses-sort-column-click (event reverse)
3213 "Mouse version of `ses-sort-column'."
3214 (interactive "*e\nP")
3215 (setq event (event-end event))
3216 (select-window (posn-window event))
3217 (setq event (car (posn-col-row event))) ; Click column.
3219 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3220 (setq event (- event (ses-col-width col) 1)
3222 (if (>= col ses--numcols)
3224 (ses-sort-column (ses-column-letter col) reverse))))
3226 (defun ses-insert-range ()
3227 "Insert into minibuffer the list of cells currently highlighted in the
3231 (with-current-buffer (window-buffer minibuffer-scroll-window)
3232 (ses-command-hook) ; For ses-coverage.
3233 (ses-check-curcell 'needrange)
3234 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3235 ,(cdr ses--curcell))))))
3236 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3238 (defun ses-insert-ses-range ()
3239 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
3240 highlighted range in the spreadsheet."
3243 (with-current-buffer (window-buffer minibuffer-scroll-window)
3244 (ses-command-hook) ; For ses-coverage.
3245 (ses-check-curcell 'needrange)
3246 (setq x (format "(ses-range %S %S)"
3248 (cdr ses--curcell))))
3251 (defun ses-insert-range-click (event)
3252 "Mouse version of `ses-insert-range'."
3254 (mouse-set-point event)
3257 (defun ses-insert-ses-range-click (event)
3258 "Mouse version of `ses-insert-ses-range'."
3260 (mouse-set-point event)
3261 (ses-insert-ses-range))
3263 (defun ses-replace-name-in-formula (formula old-name new-name)
3264 (let ((new-formula formula))
3265 (unless (and (consp formula)
3266 (eq (car-safe formula) 'quote))
3268 (let ((elt (car-safe formula)))
3271 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3273 (eq (car-safe formula) old-name))
3274 (setcar formula new-name))))
3275 (setq formula (cdr formula))))
3278 (defun ses-rename-cell (new-name &optional cell)
3279 "Rename current cell."
3280 (interactive "*SEnter new name: ")
3282 (and (local-variable-p new-name)
3283 (ses-is-cell-sym-p new-name)
3284 (error "Already a cell name"))
3285 (and (boundp new-name)
3286 (null (yes-or-no-p (format "`%S' is already bound outside this buffer, continue? "
3288 (error "Already a bound cell name")))
3290 (sym (if (ses-cell-p cell)
3291 (ses-cell-symbol cell)
3296 (rowcol (ses-sym-rowcol sym))
3299 new-rowcol old-name)
3300 (setq cell (or cell (ses-get-cell row col))
3301 old-name (ses-cell-symbol cell)
3302 new-rowcol (ses-decode-cell-symbol (symbol-name new-name)))
3304 (if (equal new-rowcol rowcol)
3305 (put new-name 'ses-cell rowcol)
3306 (error "Not a valid name for this cell location"))
3307 (setq ses--named-cell-hashmap (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
3308 (put new-name 'ses-cell :ses-named)
3309 (puthash new-name rowcol ses--named-cell-hashmap))
3310 (push `(ses-rename-cell ,old-name ,cell) buffer-undo-list)
3311 ;; replace name by new name in formula of cells refering to renamed cell
3312 (dolist (ref (ses-cell-references cell))
3313 (let* ((x (ses-sym-rowcol ref))
3314 (xcell (ses-get-cell (car x) (cdr x))))
3315 (ses-cell-formula-aset xcell
3316 (ses-replace-name-in-formula
3317 (ses-cell-formula xcell)
3320 ;; replace name by new name in reference list of cells to which renamed cell refers to
3321 (dolist (ref (ses-formula-references (ses-cell-formula cell)))
3322 (let* ((x (ses-sym-rowcol ref))
3323 (xcell (ses-get-cell (car x) (cdr x))))
3324 (ses-cell-references-aset xcell
3325 (cons new-name (delq sym
3326 (ses-cell-references xcell))))))
3327 (push new-name ses--renamed-cell-symb-list)
3328 (set new-name (symbol-value sym))
3329 (aset cell 0 new-name)
3331 (and curcell (setq ses--curcell new-name))
3332 (let* ((pos (point))
3333 (inhibit-read-only t)
3334 (col (current-column))
3335 (end (save-excursion
3336 (move-to-column (1+ col))
3338 (+ pos (ses-col-width col) 1)
3340 (put-text-property pos end 'intangible new-name))
3342 (setq mode-line-process (list " cell "
3343 (symbol-name new-name)))
3344 (force-mode-line-update)))
3346 ;;----------------------------------------------------------------------------
3347 ;; Checking formulas for safety
3348 ;;----------------------------------------------------------------------------
3350 (defun ses-safe-printer (printer)
3351 "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
3352 (if (or (stringp printer)
3353 (stringp (car-safe printer))
3355 (ses-warn-unsafe printer 'unsafep-function))
3359 (defun ses-safe-formula (formula)
3360 "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
3361 (if (ses-warn-unsafe formula 'unsafep)
3363 `(ses-unsafe ',formula)))
3365 (defun ses-warn-unsafe (formula checker)
3366 "Apply CHECKER to FORMULA.
3367 If result is non-nil, asks user for confirmation about FORMULA,
3368 which might be unsafe. Returns t if formula is safe or user allows
3369 execution anyway. Always returns t if `safe-functions' is t."
3370 (if (eq safe-functions t)
3372 (setq checker (funcall checker formula))
3375 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3376 formula checker)))))
3379 ;;----------------------------------------------------------------------------
3380 ;; Standard formulas
3381 ;;----------------------------------------------------------------------------
3383 (defun ses--clean-! (&rest x)
3384 "Clean by `delq' list X from any occurrence of `nil' or `*skip*'."
3385 (delq nil (delq '*skip* x)))
3387 (defun ses--clean-_ (x y)
3388 "Clean list X by replacing by Y any occurrence of `nil' or `*skip*'.
3390 This will change X by making `setcar' on its cons cells."
3391 (let ((ret x) ret-elt)
3393 (setq ret-elt (car ret))
3394 (when (memq ret-elt '(nil *skip*))
3396 (setq ret (cdr ret))))
3399 (defmacro ses-range (from to &rest rest)
3400 "Expand to a list of cell-symbols for the range going from
3401 FROM up to TO. The range automatically expands to include any
3402 new row or column inserted into its middle. The SES library code
3403 specifically looks for the symbol `ses-range', so don't create an
3404 alias for this macro!
3406 By passing in REST some flags one can configure the way the range
3407 is read and how it is formatted.
3409 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3412 Readout direction is specified by a `>v', '`>^', `<v', `<^',
3413 `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3414 of such a flag, a default direction of `^<' is assumed. This
3415 way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3416 while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3418 If the range is one row, then `>' can be used as a shorthand to
3419 `>v' or `>^', and `<' to `<v' or `<^'.
3421 If the range is one column, then `v' can be used as a shorthand to
3422 `v>' or `v<', and `^' to `^>' or `v<'.
3424 A `!' flag will remove all cells whose value is nil or `*skip*'.
3426 A `_' flag will replace nil or `*skip*' by the value following
3427 the `_' flag. If the `_' flag is the last argument, then they are
3428 replaced by integer 0.
3430 A `*', `*1' or `*2' flag will vectorize the range in the sense of
3431 Calc. See info node `(Calc) Top'. Flag `*' will output either a
3432 vector or a matrix depending on the number of rows, `*1' will
3433 flatten the result to a one row vector, and `*2' will make a
3434 matrix whatever the number of rows.
3436 Warning: interaction with Calc is experimental and may produce
3437 confusing results if you are not aware of Calc data format.
3438 Use `math-format-value' as a printer for Calc objects."
3446 (ses-dorange (cons from to)
3447 (when (/= prev-row row)
3448 (push result-row result)
3449 (setq result-row nil))
3450 (push (ses-cell-symbol row col) result-row)
3451 (setq prev-row row))
3452 (push result-row result)
3454 (let ((x (pop rest)))
3456 (`>v (setq transpose nil reorient-x nil reorient-y nil))
3457 (`>^ (setq transpose nil reorient-x nil reorient-y t))
3458 (`<^ (setq transpose nil reorient-x t reorient-y t))
3459 (`<v (setq transpose nil reorient-x t reorient-y nil))
3460 (`v> (setq transpose t reorient-x nil reorient-y t))
3461 (`^> (setq transpose t reorient-x nil reorient-y nil))
3462 (`^< (setq transpose t reorient-x t reorient-y nil))
3463 (`v< (setq transpose t reorient-x t reorient-y t))
3464 ((or `* `*2 `*1) (setq vectorize x))
3465 (`! (setq clean 'ses--clean-!))
3466 (`_ (setq clean `(lambda (&rest x)
3467 (ses--clean-_ x ,(if rest (pop rest) 0)))))
3470 ; shorthands one row
3471 ((and (null (cddr result)) (memq x '(> <)))
3472 (push (intern (concat (symbol-name x) "v")) rest))
3473 ; shorthands one col
3474 ((and (null (cdar result)) (memq x '(v ^)))
3475 (push (intern (concat (symbol-name x) ">")) rest))
3476 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3478 (setcdr (last result 2) nil)
3479 (setq result (cdr (nreverse result))))
3481 (setq result (mapcar 'nreverse result)))
3483 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3486 (dolist (elt (pop result))
3487 (setcar iter (cons elt (car iter)))
3488 (setq iter (cdr iter))))
3491 (cl-flet ((vectorize-*1
3493 (cons clean (cons (quote 'vec) (apply 'append result))))
3496 (cons clean (cons (quote 'vec)
3498 (cons clean (cons (quote 'vec) x)))
3501 (`nil (cons clean (apply 'append result)))
3502 (`*1 (vectorize-*1 clean result))
3503 (`*2 (vectorize-*2 clean result))
3504 (`* (funcall (if (cdr result)
3509 (defun ses-delete-blanks (&rest args)
3510 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3513 (unless (memq cur '(nil *skip*))
3517 (defun ses+ (&rest args)
3518 "Compute the sum of the arguments, ignoring blanks."
3519 (apply '+ (apply 'ses-delete-blanks args)))
3521 (defun ses-average (list)
3522 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3523 are ignored. Result is always floating-point, even if all args are integers."
3524 (setq list (apply 'ses-delete-blanks list))
3525 (/ (float (apply '+ list)) (length list)))
3527 (defmacro ses-select (fromrange test torange)
3528 "Select cells in FROMRANGE that are `equal' to TEST.
3529 For each match, return the corresponding cell from TORANGE.
3530 The ranges are macroexpanded but not evaluated so they should be
3531 either (ses-range BEG END) or (list ...). The TEST is evaluated."
3532 (setq fromrange (cdr (macroexpand fromrange))
3533 torange (cdr (macroexpand torange))
3535 (or (= (length fromrange) (length torange))
3536 (error "ses-select: Ranges not same length"))
3538 (dolist (x fromrange)
3539 (if (equal test (symbol-value x))
3540 (push (car torange) result))
3541 (setq torange (cdr torange)))
3542 (cons 'list result)))
3544 ;;All standard formulas are safe
3545 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3547 (put x 'side-effect-free t))
3550 ;;----------------------------------------------------------------------------
3551 ;; Standard print functions
3552 ;;----------------------------------------------------------------------------
3554 ;; These functions use the variables 'row' and 'col' that are dynamically bound
3555 ;; by ses-print-cell. We define these variables at compile-time to make the
3560 (defun ses-center (value &optional span fill)
3561 "Print VALUE, centered within column.
3562 FILL is the fill character for centering (default = space).
3563 SPAN indicates how many additional rightward columns to include
3564 in width (default = 0)."
3565 (let ((printer (or (ses-col-printer col) ses--default-printer))
3566 (width (ses-col-width col))
3568 (or fill (setq fill ?\s))
3569 (or span (setq span 0))
3570 (setq value (ses-call-printer printer value))
3572 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
3573 ;; Set column width.
3574 (setq width (- width (string-width value)))
3576 value ; Too large for field, anyway.
3577 (setq half (make-string (/ width 2) fill))
3578 (concat half value half
3579 (if (> (% width 2) 0) (char-to-string fill))))))
3581 (defun ses-center-span (value &optional fill)
3582 "Print VALUE, centered within the span that starts in the current column
3583 and continues until the next nonblank column.
3584 FILL specifies the fill character (default = space)."
3585 (let ((end (1+ col)))
3586 (while (and (< end ses--numcols)
3587 (memq (ses-cell-value row end) '(nil *skip*)))
3588 (setq end (1+ end)))
3589 (ses-center value (- end col 1) fill)))
3591 (defun ses-dashfill (value &optional span)
3592 "Print VALUE centered using dashes.
3593 SPAN indicates how many rightward columns to include in width (default = 0)."
3594 (ses-center value span ?-))
3596 (defun ses-dashfill-span (value)
3597 "Print VALUE, centered using dashes within the span that starts in the
3598 current column and continues until the next nonblank column."
3599 (ses-center-span value ?-))
3601 (defun ses-tildefill-span (value)
3602 "Print VALUE, centered using tildes within the span that starts in the
3603 current column and continues until the next nonblank column."
3604 (ses-center-span value ?~))
3606 (defun ses-unsafe (_value)
3607 "Substitute for an unsafe formula or printer."
3608 (error "Unsafe formula or printer"))
3610 ;;All standard printers are safe, including ses-unsafe!
3611 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3612 (put x 'side-effect-free t))
3614 (defun ses-unload-function ()
3615 "Unload the Simple Emacs Spreadsheet."
3616 (advice-remove 'yank #'ses--advice-yank)
3617 (advice-remove 'copy-region-as-kill #'ses--advice-copy-region-as-kill)
3618 ;; Continue standard unloading.
3623 ;;; ses.el ends here