1 ;;; ses.el -- Simple Emacs Spreadsheet -*- coding: utf-8 -*-
3 ;; Copyright (C) 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
5 ;; Author: Jonathan Yavner <jyavner@member.fsf.org>
6 ;; Maintainer: Jonathan Yavner <jyavner@member.fsf.org>
7 ;; Keywords: spreadsheet
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 2, or (at your option)
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; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
30 ;; * Use $ or … for truncated fields
31 ;; * Add command to make a range of columns be temporarily invisible.
32 ;; * Allow paste of one cell to a range of cells -- copy formula to each.
33 ;; * Do something about control characters & octal codes in cell print
34 ;; areas. Use string-width?
35 ;; * Input validation functions. How specified?
36 ;; * Faces (colors & styles) in print cells.
37 ;; * Move a column by dragging its letter in the header line.
38 ;; * Left-margin column for row number.
39 ;; * Move a row by dragging its number in the left-margin.
47 ;;----------------------------------------------------------------------------
48 ;; User-customizable variables
49 ;;----------------------------------------------------------------------------
52 "Simple Emacs Spreadsheet."
57 (defcustom ses-initial-size
'(1 .
1)
58 "Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
60 :type
'(cons (integer :tag
"numrows") (integer :tag
"numcols")))
62 (defcustom ses-initial-column-width
7
63 "Initial width of columns in a new spreadsheet."
65 :type
'(integer :match
(lambda (widget value
) (> value
0))))
67 (defcustom ses-initial-default-printer
"%.7g"
68 "Initial default printer for a new spreadsheet."
71 (list :tag
"Parenthesized string" string
)
74 (defcustom ses-after-entry-functions
'(forward-char)
75 "Things to do after entering a value into a cell.
76 An abnormal hook that usually runs a cursor-movement function.
77 Each function is called with ARG=1."
80 :options
'(forward-char backward-char next-line previous-line
))
82 (defcustom ses-mode-hook nil
83 "Hook functions to be run upon entering SES mode."
88 ;;----------------------------------------------------------------------------
89 ;; Global variables and constants
90 ;;----------------------------------------------------------------------------
92 (defvar ses-read-cell-history nil
93 "List of formulas that have been typed in.")
95 (defvar ses-read-printer-history nil
96 "List of printer functions that have been typed in.")
98 (easy-menu-define ses-header-line-menu nil
99 "Context menu when mouse-3 is used on the header-line in an SES buffer."
101 ["Set current row" ses-set-header-row t
]
102 ["Unset row" ses-unset-header-row
(> ses--header-row
0)]))
104 (defconst ses-mode-map
105 (let ((keys `("\C-c\M-\C-l" ses-reconstruct-all
106 "\C-c\C-l" ses-recalculate-all
107 "\C-c\C-n" ses-renarrow-buffer
108 "\C-c\C-c" ses-recalculate-cell
109 "\C-c\M-\C-s" ses-sort-column
110 "\C-c\M-\C-h" ses-set-header-row
111 "\C-c\C-t" ses-truncate-cell
113 "\C-c\C-p" ses-read-default-printer
114 "\M-\C-l" ses-reprint-all
115 [?\S-\C-l
] ses-reprint-all
116 [header-line down-mouse-3
] ,ses-header-line-menu
117 [header-line mouse-2
] ses-sort-column-click
))
118 (newmap (make-sparse-keymap)))
120 (define-key (1value newmap
) (car keys
) (cadr keys
))
121 (setq keys
(cddr keys
)))
123 "Local keymap for Simple Emacs Spreadsheet.")
125 (easy-menu-define ses-menu ses-mode-map
126 "Menu bar menu for SES."
128 ["Insert row" ses-insert-row
(ses-in-print-area)]
129 ["Delete row" ses-delete-row
(ses-in-print-area)]
130 ["Insert column" ses-insert-column
(ses-in-print-area)]
131 ["Delete column" ses-delete-column
(ses-in-print-area)]
132 ["Set column printer" ses-read-column-printer t
]
133 ["Set column width" ses-set-column-width t
]
134 ["Set default printer" ses-read-default-printer t
]
135 ["Jump to cell" ses-jump t
]
136 ["Set cell printer" ses-read-cell-printer t
]
137 ["Recalculate cell" ses-recalculate-cell t
]
138 ["Truncate cell display" ses-truncate-cell t
]
139 ["Export values" ses-export-tsv t
]
140 ["Export formulas" ses-export-tsf t
]))
142 (defconst ses-mode-edit-map
143 (let ((keys '("\C-c\C-r" ses-insert-range
144 "\C-c\C-s" ses-insert-ses-range
145 [S-mouse-3
] ses-insert-range-click
146 [C-S-mouse-3
] ses-insert-ses-range-click
147 "\M-\C-i" lisp-complete-symbol
))
148 (newmap (make-sparse-keymap)))
149 (set-keymap-parent newmap minibuffer-local-map
)
151 (define-key newmap
(pop keys
) (pop keys
)))
153 "Local keymap for SES minibuffer cell-editing.")
155 ;Local keymap for SES print area
156 (defalias 'ses-mode-print-map
157 (let ((keys '([backtab] backward-char
158 [tab] ses-forward-or-insert
159 "\C-i" ses-forward-or-insert ;Needed for ses-coverage.el?
160 "\M-o" ses-insert-column
161 "\C-o" ses-insert-row
163 "\M-k" ses-delete-column
165 "\C-k" ses-delete-row
166 "\C-j" ses-append-row-jump-first-column
168 "\M-H" ses-mark-column
169 "\C-d" ses-clear-cell-forward
170 "\C-?" ses-clear-cell-backward
176 "p" ses-read-cell-printer
177 "w" ses-set-column-width
178 "x" ses-export-keymap
179 "\M-p" ses-read-column-printer))
180 (repl '(;;We'll replace these wherever they appear in the keymap
181 clipboard-kill-region ses-kill-override
182 end-of-line ses-end-of-line
183 kill-line ses-delete-row
184 kill-region ses-kill-override
185 open-line ses-insert-row))
186 (numeric "0123456789.-")
187 (newmap (make-keymap)))
188 ;;Get rid of printables
189 (suppress-keymap newmap t)
190 ;;These keys insert themselves as the beginning of a numeric value
191 (dotimes (x (length numeric))
192 (define-key newmap (substring numeric x (1+ x)) 'ses-read-cell))
193 ;;Override these global functions wherever they're bound
195 (substitute-key-definition (car repl) (cadr repl) newmap
196 (current-global-map))
197 (setq repl (cddr repl)))
198 ;;Apparently substitute-key-definition doesn't catch this?
199 (define-key newmap [(menu-bar) edit cut] 'ses-kill-override)
200 ;;Define our other local keys
202 (define-key newmap (car keys) (cadr keys))
203 (setq keys (cddr keys)))
206 ;;Helptext for ses-mode wants keymap as variable, not function
207 (defconst ses-mode-print-map (symbol-function 'ses-mode-print-map))
209 ;;Key map used for 'x' key.
210 (defalias 'ses-export-keymap
211 (let ((map (make-sparse-keymap "SES export")))
212 (define-key map "T" (cons " tab-formulas" 'ses-export-tsf))
213 (define-key map "t" (cons " tab-values" 'ses-export-tsv))
216 (defconst ses-print-data-boundary "\n\014\n"
217 "Marker string denoting the boundary between print area and data area.")
219 (defconst ses-initial-global-parameters
220 "\n( ;Global parameters (these are read first)\n 2 ;SES file-format\n 1 ;numrows\n 1 ;numcols\n)\n\n"
221 "Initial contents for the three-element list at the bottom of the data area.")
223 (defconst ses-initial-file-trailer
224 ";; Local Variables:\n;; mode: ses\n;; End:\n"
225 "Initial contents for the file-trailer area at the bottom of the file.")
227 (defconst ses-initial-file-contents
228 (concat " \n" ;One blank cell in print area
229 ses-print-data-boundary
230 "(ses-cell A1 nil nil nil nil)\n" ;One blank cell in data area
231 "\n" ;End-of-row terminator for the one row in data area
232 "(ses-column-widths [7])\n"
233 "(ses-column-printers [nil])\n"
234 "(ses-default-printer \"%.7g\")\n"
235 "(ses-header-row 0)\n"
236 ses-initial-global-parameters
237 ses-initial-file-trailer)
238 "The initial contents of an empty spreadsheet.")
240 (defconst ses-paramlines-plist
241 '(ses--col-widths 2 ses--col-printers 3 ses--default-printer 4
242 ses--header-row 5 ses--file-format 8 ses--numrows 9
244 "Offsets from last cell line to various parameter lines in the data area
247 (defconst ses-box-prop '(:box (:line-width 2 :style released-button))
248 "Display properties to create a raised box for cells in the header line.")
250 (defconst ses-standard-printer-functions
251 '(ses-center ses-center-span ses-dashfill ses-dashfill-span
253 "List of print functions to be included in initial history of printer
254 functions. None of these standard-printer functions is suitable for use as a
255 column printer or a global-default printer because they invoke the column or
256 default printer and then modify its output.")
259 (defconst ses-localvars
260 '(ses--blank-line ses--cells ses--col-printers ses--col-widths ses--curcell
261 ses--curcell-overlay ses--default-printer ses--deferred-narrow
262 ses--deferred-recalc ses--deferred-write ses--file-format
263 ses--header-hscroll ses--header-row ses--header-string ses--linewidth
264 ses--numcols ses--numrows ses--symbolic-formulas
265 ;;Global variables that we override
266 mode-line-process next-line-add-newlines transient-mark-mode)
267 "Buffer-local variables used by SES."))
269 ;;When compiling, create all the buffer locals and give them values
271 (dolist (x ses-localvars)
272 (make-local-variable x)
277 ;; "Side-effect variables". They are set in one function, altered in
278 ;; another as a side effect, then read back by the first, as a way of
279 ;; passing back more than one value. These declarations are just to make
280 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
281 ;; think the make-local-variable trick above is cleaner).
284 (defvar ses-relocate-return nil
285 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
286 `ses-relocate-all'. Set to 'delete if a cell-reference was deleted from a
287 formula--so the formula needs recalculation. Set to 'range if the size of a
288 `ses-range' was changed--so both the formula's value and list of dependents
289 need to be recalculated.")
291 (defvar ses-call-printer-return nil
292 "Set to t if last cell printer invoked by `ses-call-printer' requested
293 left-justification of the result. Set to error-signal if ses-call-printer
294 encountered an error during printing. Nil otherwise.")
296 (defvar ses-start-time nil
297 "Time when current operation started. Used by `ses-time-check' to decide
298 when to emit a progress message.")
301 ;;----------------------------------------------------------------------------
303 ;;----------------------------------------------------------------------------
305 (defmacro ses-get-cell (row col)
306 "Return the cell structure that stores information about cell (ROW,COL)."
307 `(aref (aref ses--cells ,row) ,col))
309 ;; We might want to use defstruct here, but cells are explicitly used as
310 ;; arrays in ses-set-cell, so we'd need to fix this first. --Stef
311 (defsubst ses-make-cell (&optional symbol formula printer references)
312 (vector symbol formula printer references))
314 (defmacro ses-cell-symbol (row &optional col)
315 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
316 `(aref ,(if col `(ses-get-cell ,row ,col) row) 0))
318 (defmacro ses-cell-formula (row &optional col)
319 "From a CELL or a pair (ROW,COL), get the function that computes its value."
320 `(aref ,(if col `(ses-get-cell ,row ,col) row) 1))
322 (defmacro ses-cell-printer (row &optional col)
323 "From a CELL or a pair (ROW,COL), get the function that prints its value."
324 `(aref ,(if col `(ses-get-cell ,row ,col) row) 2))
326 (defmacro ses-cell-references (row &optional col)
327 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
328 functions refer to its value."
329 `(aref ,(if col `(ses-get-cell ,row ,col) row) 3))
331 (defmacro ses-cell-value (row &optional col)
332 "From a CELL or a pair (ROW,COL), get the current value for that cell."
333 `(symbol-value (ses-cell-symbol ,row ,col)))
335 (defmacro ses-col-width (col)
336 "Return the width for column COL."
337 `(aref ses--col-widths ,col))
339 (defmacro ses-col-printer (col)
340 "Return the default printer for column COL."
341 `(aref ses--col-printers ,col))
343 (defmacro ses-sym-rowcol (sym)
344 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0). Result
345 is nil if SYM is not a symbol that names a cell."
346 `(and (symbolp ,sym) (get ,sym 'ses-cell)))
348 (defmacro ses-cell (sym value formula printer references)
349 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
350 FORMULA, does not reprint using PRINTER, does not check REFERENCES. This is a
351 macro to prevent propagate-on-load viruses. Safety-checking for FORMULA and
352 PRINTER are deferred until first use."
353 (let ((rowcol (ses-sym-rowcol sym)))
354 (ses-formula-record formula)
355 (ses-printer-record printer)
357 (eq safe-functions t)
358 (setq formula `(ses-safe-formula ,formula)))
361 (eq safe-functions t)
362 (setq printer `(ses-safe-printer ,printer)))
363 (aset (aref ses--cells (car rowcol))
365 (ses-make-cell sym formula printer references)))
369 (defmacro ses-column-widths (widths)
370 "Load the vector of column widths from the spreadsheet file. This is a
371 macro to prevent propagate-on-load viruses."
372 (or (and (vectorp widths) (= (length widths) ses--numcols))
373 (error "Bad column-width vector"))
374 ;;To save time later, we also calculate the total width of each line in the
375 ;;print area (excluding the terminating newline)
376 (setq ses--col-widths widths
377 ses--linewidth (apply '+ -1 (mapcar '1+ widths))
378 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
381 (defmacro ses-column-printers (printers)
382 "Load the vector of column printers from the spreadsheet file and checks
383 them for safety. This is a macro to prevent propagate-on-load viruses."
384 (or (and (vectorp printers) (= (length printers) ses--numcols))
385 (error "Bad column-printers vector"))
386 (dotimes (x ses--numcols)
387 (aset printers x (ses-safe-printer (aref printers x))))
388 (setq ses--col-printers printers)
389 (mapc 'ses-printer-record printers)
392 (defmacro ses-default-printer (def)
393 "Load the global default printer from the spreadsheet file and checks it
394 for safety. This is a macro to prevent propagate-on-load viruses."
395 (setq ses--default-printer (ses-safe-printer def))
396 (ses-printer-record def)
399 (defmacro ses-header-row (row)
400 "Load the header row from the spreadsheet file and checks it
401 for safety. This is a macro to prevent propagate-on-load viruses."
402 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
403 (error "Bad header-row"))
404 (setq ses--header-row row)
407 (defmacro ses-dorange (curcell &rest body)
408 "Execute BODY repeatedly, with the variables `row' and `col' set to each
409 cell in the range specified by CURCELL. The range is available in the
410 variables `minrow', `maxrow', `mincol', and `maxcol'."
411 (let ((cur (make-symbol "cur"))
412 (min (make-symbol "min"))
413 (max (make-symbol "max"))
414 (r (make-symbol "r"))
415 (c (make-symbol "c")))
416 `(let* ((,cur ,curcell)
417 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
418 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
419 (let ((minrow (car ,min))
424 (if (or (> minrow maxrow) (> mincol maxcol))
425 (error "Empty range"))
426 (dotimes (,r (- maxrow minrow -1))
427 (setq row (+ ,r minrow))
428 (dotimes (,c (- maxcol mincol -1))
429 (setq col (+ ,c mincol))
432 (put 'ses-dorange 'lisp-indent-function 'defun)
433 (def-edebug-spec ses-dorange (form body))
435 ;;Support for coverage testing.
436 (defmacro 1value (form)
437 "For code-coverage testing, indicate that FORM is expected to always have
440 (defmacro noreturn (form)
441 "For code-coverage testing, indicate that FORM will always signal an error."
445 ;;----------------------------------------------------------------------------
447 ;;----------------------------------------------------------------------------
449 (defun ses-vector-insert (array idx new)
450 "Create a new vector which is one larger than ARRAY and has NEW inserted
452 (let* ((len (length array))
453 (result (make-vector (1+ len) new)))
456 (if (< x idx) x (1+ x))
460 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
461 (defun ses-vector-delete (array idx count)
462 "Create a new vector which is a copy of ARRAY with COUNT objects removed
463 starting at element IDX. ARRAY is either a vector or a symbol whose value
464 is a vector--if a symbol, the new vector is assigned as the symbol's value."
465 (let* ((a (if (arrayp array) array (symbol-value array)))
466 (len (- (length a) count))
467 (result (make-vector len nil)))
469 (aset result x (aref a (if (< x idx) x (+ x count)))))
474 (defun ses-delete-line (count)
475 "Like `kill-line', but no kill ring."
478 (delete-region pos (point))))
480 (defun ses-printer-validate (printer)
481 "Signals an error if PRINTER is not a valid SES cell printer."
485 (and (stringp (car-safe printer)) (not (cdr printer)))
486 (error "Invalid printer function"))
489 (defun ses-printer-record (printer)
490 "Add PRINTER to `ses-read-printer-history' if not already there, after first
491 checking that it is a valid printer function."
492 (ses-printer-validate printer)
493 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
495 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
497 (defun ses-formula-record (formula)
498 "If FORMULA is of the form 'symbol, adds it to the list of symbolic formulas
499 for this spreadsheet."
500 (when (and (eq (car-safe formula) 'quote)
501 (symbolp (cadr formula)))
502 (add-to-list 'ses--symbolic-formulas
503 (list (symbol-name (cadr formula))))))
505 (defun ses-column-letter (col)
506 "Converts a column number to A..Z or AA..ZZ"
508 (char-to-string (+ ?A col))
509 (string (+ ?@ (/ col 26)) (+ ?A (% col 26)))))
511 (defun ses-create-cell-symbol (row col)
512 "Produce a symbol that names the cell (ROW,COL). (0,0) => 'A1."
513 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
515 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
516 "Create buffer-local variables for cells. This is undoable."
517 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
520 (dotimes (row (1+ (- maxrow minrow)))
521 (dotimes (col (1+ (- maxcol mincol)))
522 (setq xrow (+ row minrow)
524 sym (ses-create-cell-symbol xrow xcol))
525 (put sym 'ses-cell (cons xrow xcol))
526 (make-local-variable sym)))))
528 ;;We do not delete the ses-cell properties for the cell-variables, in case a
529 ;;formula that refers to this cell is in the kill-ring and is later pasted
531 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
532 "Destroy buffer-local variables for cells. This is undoable."
534 (dotimes (row (1+ (- maxrow minrow)))
535 (dotimes (col (1+ (- maxcol mincol)))
536 (setq sym (ses-create-cell-symbol (+ row minrow) (+ col mincol)))
538 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
540 (kill-local-variable sym))))
541 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
544 (defun ses-reset-header-string ()
545 "Flags the header string for update. Upon undo, the header string will be
547 (push '(apply ses-reset-header-string) buffer-undo-list)
548 (setq ses--header-hscroll -1))
550 ;;Split this code off into a function to avoid coverage-testing difficulties
551 (defun ses-time-check (format arg)
552 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
553 and (eval ARG) and reset `ses-start-time' to the current time."
554 (when (> (- (float-time) ses-start-time) 1.0)
555 (message format (eval arg))
556 (setq ses-start-time (float-time)))
560 ;;----------------------------------------------------------------------------
562 ;;----------------------------------------------------------------------------
564 (defun ses-set-cell (row col field val)
565 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
566 cell (ROW,COL). This is undoable. The cell's data will be updated through
567 `post-command-hook'."
568 (let ((cell (ses-get-cell row col))
569 (elt (plist-get '(value t symbol 0 formula 1 printer 2 references 3)
572 (or elt (signal 'args-out-of-range nil))
573 (setq change (if (eq elt t)
574 (ses-set-with-undo (ses-cell-symbol cell) val)
575 (ses-aset-with-undo cell elt val)))
577 (add-to-list 'ses--deferred-write (cons row col))))
578 nil) ;Make coverage-tester happy
580 (defun ses-cell-set-formula (row col formula)
581 "Store a new formula for (ROW . COL) and enqueues the cell for
582 recalculation via `post-command-hook'. Updates the reference lists for the
583 cells that this cell refers to. Does not update cell value or reprint the
584 cell. To avoid inconsistencies, this function is not interruptible, which
585 means Emacs will crash if FORMULA contains a circular list."
586 (let* ((cell (ses-get-cell row col))
587 (old (ses-cell-formula cell)))
588 (let ((sym (ses-cell-symbol cell))
589 (oldref (ses-formula-references old))
590 (newref (ses-formula-references formula))
593 (add-to-list 'ses--deferred-recalc sym)
594 ;;Delete old references from this cell. Skip the ones that are also
597 (unless (memq ref newref)
598 (setq x (ses-sym-rowcol ref)
601 (ses-set-cell xrow xcol 'references
602 (delq sym (ses-cell-references xrow xcol)))))
603 ;;Add new ones. Skip ones left over from old list
605 (setq x (ses-sym-rowcol ref)
608 x (ses-cell-references xrow xcol))
610 (ses-set-cell xrow xcol 'references (cons sym x))))
611 (ses-formula-record formula)
612 (ses-set-cell row col 'formula formula))))
614 (defun ses-calculate-cell (row col force)
615 "Calculate and print the value for cell (ROW,COL) using the cell's formula
616 function and print functions, if any. Result is nil for normal operation, or
617 the error signal if the formula or print function failed. The old value is
618 left unchanged if it was *skip* and the new value is nil.
619 Any cells that depend on this cell are queued for update after the end of
620 processing for the current keystroke, unless the new value is the same as
621 the old and FORCE is nil."
622 (let ((cell (ses-get-cell row col))
623 formula-error printer-error)
624 (let ((oldval (ses-cell-value cell))
625 (formula (ses-cell-formula cell))
627 (if (eq (car-safe formula) 'ses-safe-formula)
628 (ses-set-cell row col 'formula (ses-safe-formula (cadr formula))))
630 (setq newval (eval formula))
632 (setq formula-error sig
634 (if (and (not newval) (eq oldval '*skip*))
635 ;;Don't lose the *skip* - previous field spans this one
636 (setq newval '*skip*))
637 (when (or force (not (eq newval oldval)))
638 (add-to-list 'ses--deferred-write (cons row col)) ;In case force=t
639 (ses-set-cell row col 'value newval)
640 (dolist (ref (ses-cell-references cell))
641 (add-to-list 'ses--deferred-recalc ref))))
642 (setq printer-error (ses-print-cell row col))
643 (or formula-error printer-error)))
645 (defun ses-clear-cell (row col)
646 "Delete formula and printer for cell (ROW,COL)."
647 (ses-set-cell row col 'printer nil)
648 (ses-cell-set-formula row col nil))
650 (defun ses-update-cells (list &optional force)
651 "Recalculate cells in LIST, checking for dependency loops. Prints
652 progress messages every second. Dependent cells are not recalculated
653 if the cell's value is unchanged if FORCE is nil."
654 (let ((ses--deferred-recalc list)
657 curlist prevlist rowcol formula)
658 (with-temp-message " "
659 (while (and ses--deferred-recalc (not (equal nextlist prevlist)))
660 ;;In each loop, recalculate cells that refer only to other cells that
661 ;;have already been recalculated or aren't in the recalculation
662 ;;region. Repeat until all cells have been processed or until the
663 ;;set of cells being worked on stops changing.
665 (message "Recalculating... (%d cells left)"
666 (length ses--deferred-recalc)))
667 (setq curlist ses--deferred-recalc
668 ses--deferred-recalc nil
671 (setq rowcol (ses-sym-rowcol (car curlist))
672 formula (ses-cell-formula (car rowcol) (cdr rowcol)))
674 (dolist (ref (ses-formula-references formula))
675 (when (or (memq ref curlist)
676 (memq ref ses--deferred-recalc))
677 ;;This cell refers to another that isn't done yet
678 (add-to-list 'ses--deferred-recalc (car curlist))
680 ;;ses-update-cells is called from post-command-hook, so
681 ;;inhibit-quit is implicitly bound to t.
683 ;;Abort the recalculation. User will probably undo now.
685 (ses-calculate-cell (car rowcol) (cdr rowcol) force))
686 (setq curlist (cdr curlist)))
687 (dolist (ref ses--deferred-recalc)
688 (add-to-list 'nextlist ref))
689 (setq nextlist (sort (copy-sequence nextlist) 'string<))
690 (if (equal nextlist prevlist)
691 ;;We'll go around the loop one more time.
692 (add-to-list 'nextlist t)))
693 (when ses--deferred-recalc
694 ;;Just couldn't finish these
695 (dolist (x ses--deferred-recalc)
696 (let ((rowcol (ses-sym-rowcol x)))
697 (ses-set-cell (car rowcol) (cdr rowcol) 'value '*error*)
698 (1value (ses-print-cell (car rowcol) (cdr rowcol)))))
699 (error "Circular references: %s" ses--deferred-recalc))
701 ;;Can't use save-excursion here: if the cell under point is
702 ;;updated, save-excusion's marker will move past the cell.
706 ;;----------------------------------------------------------------------------
708 ;;----------------------------------------------------------------------------
710 (defun ses-in-print-area ()
711 "Returns t if point is in print area of spreadsheet."
712 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map))
714 ;;We turn off point-motion-hooks and explicitly position the cursor, in case
715 ;;the intangible properties have gotten screwed up (e.g., when
716 ;;ses-goto-print is called during a recursive ses-print-cell).
717 (defun ses-goto-print (row col)
718 "Move point to print area for cell (ROW,COL)."
719 (let ((inhibit-point-motion-hooks t))
720 (goto-char (point-min))
723 (forward-char (1+ (ses-col-width c))))))
725 (defun ses-set-curcell ()
726 "Sets `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
727 region, or nil if cursor is not at a cell."
728 (if (or (not mark-active)
730 (= (region-beginning) (region-end)))
732 (setq ses--curcell (get-text-property (point) 'intangible))
734 (let ((bcell (get-text-property (region-beginning) 'intangible))
735 (ecell (get-text-property (1- (region-end)) 'intangible)))
736 (setq ses--curcell (if (and bcell ecell)
741 (defun ses-check-curcell (&rest args)
742 "Signal an error if ses--curcell is inappropriate. The end marker is
743 appropriate if some argument is 'end. A range is appropriate if some
744 argument is 'range. A single cell is appropriate unless some argument is
746 (if (eq ses--curcell t)
747 ;;curcell recalculation was postponed, but user typed ahead
752 (error "Not at cell")))
753 ((consp ses--curcell)
754 (or (memq 'range args)
755 (memq 'needrange args)
756 (error "Can't use a range")))
757 ((memq 'needrange args)
758 (error "Need a range"))))
760 (defun ses-print-cell (row col)
761 "Format and print the value of cell (ROW,COL) to the print area.
762 Use the cell's printer function. If the cell's new print form is too wide,
763 it will spill over into the following cell, but will not run off the end of the
764 row or overwrite the next non-nil field. Result is nil for normal operation,
765 or the error signal if the printer function failed and the cell was formatted
766 with \"%s\". If the cell's value is *skip*, nothing is printed because the
767 preceding cell has spilled over."
768 (catch 'ses-print-cell
769 (let* ((cell (ses-get-cell row col))
770 (value (ses-cell-value cell))
771 (printer (ses-cell-printer cell))
774 ;;Create the string to print
777 ;;Don't print anything
778 (throw 'ses-print-cell nil))
780 (setq text (make-string (ses-col-width col) ?#)))
782 ;;Deferred safety-check on printer
783 (if (eq (car-safe printer) 'ses-safe-printer)
784 (ses-set-cell row col 'printer
785 (setq printer (ses-safe-printer (cadr printer)))))
787 (setq text (ses-call-printer (or printer
788 (ses-col-printer col)
789 ses--default-printer)
791 (if (consp ses-call-printer-return)
792 ;;Printer returned an error
793 (setq sig ses-call-printer-return))))
794 ;;Adjust print width to match column width
795 (let ((width (ses-col-width col))
799 ;;Fill field to length with spaces
800 (setq len (make-string (- width len) ?\s)
801 text (if (eq ses-call-printer-return t)
805 ;;Spill over into following cells, if possible
806 (let ((maxwidth width))
807 (while (and (> len maxwidth)
808 (< maxcol ses--numcols)
809 (or (not (setq x (ses-cell-value row maxcol)))
812 ;;Set this cell to '*skip* so it won't overwrite our spillover
813 (ses-set-cell row maxcol 'value '*skip*))
814 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
816 (if (<= len maxwidth)
817 ;;Fill to complete width of all the fields spanned
818 (setq text (concat text (make-string (- maxwidth len) ?\s)))
819 ;;Not enough room to end of line or next non-nil field. Truncate
820 ;;if string or decimal; otherwise fill with error indicator
821 (setq sig `(error "Too wide" ,text))
824 (setq text (substring text 0 maxwidth)))
825 ((and (numberp value)
826 (string-match "\\.[0-9]+" text)
829 (- (match-end 0) (match-beginning 0))))))
830 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
831 (setq text (concat (substring text
833 (- (match-beginning 0) width))
834 (substring text (match-end 0)))))
836 (setq text (make-string maxwidth ?#)))))))))
837 ;;Substitute question marks for tabs and newlines. Newlines are
838 ;;used as row-separators; tabs could confuse the reimport logic.
839 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
840 (ses-goto-print row col)
841 (setq startpos (point))
842 ;;Install the printed result. This is not interruptible.
843 (let ((inhibit-read-only t)
845 (delete-char (1+ (length text)))
846 ;;We use concat instead of inserting separate strings in order to
847 ;;reduce the number of cells in the undo list.
848 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
849 ;;We use set-text-properties to prevent a wacky print function
850 ;;from inserting rogue properties, and to ensure that the keymap
851 ;;property is inherited (is it a bug that only unpropertied strings
852 ;;actually inherit from surrounding text?)
853 (set-text-properties 0 (length x) nil x)
854 (insert-and-inherit x)
855 (put-text-property startpos (point) 'intangible
856 (ses-cell-symbol cell))
857 (when (and (zerop row) (zerop col))
858 ;;Reconstruct special beginning-of-buffer attributes
859 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
860 (put-text-property (point-min) (point) 'read-only 'ses)
861 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)))
862 (if (= row (1- ses--header-row))
863 ;;This line is part of the header - force recalc
864 (ses-reset-header-string))
865 ;;If this cell (or a preceding one on the line) previously spilled over
866 ;;and has gotten shorter, redraw following cells on line recursively.
867 (when (and (< maxcol ses--numcols)
868 (eq (ses-cell-value row maxcol) '*skip*))
869 (ses-set-cell row maxcol 'value nil)
870 (ses-print-cell row maxcol))
871 ;;Return to start of cell
875 (defun ses-call-printer (printer &optional value)
876 "Invokes PRINTER (a string or parenthesized string or function-symbol or
877 lambda of one argument) on VALUE. Result is the the printed cell as a
878 string. The variable `ses-call-printer-return' is set to t if the printer
879 used parenthesis to request left-justification, or the error-signal if the
880 printer signaled one (and \"%s\" is used as the default printer), else nil."
881 (setq ses-call-printer-return nil)
884 (condition-case signal
887 (format printer value))
888 ((stringp (car-safe printer))
889 (setq ses-call-printer-return t)
890 (format (car printer) value))
892 (setq value (funcall printer value))
895 (or (stringp (car-safe value))
896 (error "Printer should return \"string\" or (\"string\")"))
897 (setq ses-call-printer-return t)
900 (setq ses-call-printer-return signal)
901 (prin1-to-string value t))))
903 (defun ses-adjust-print-width (col change)
904 "Insert CHANGE spaces in front of column COL, or at end of line if
905 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
907 (let ((inhibit-read-only t)
908 (blank (if (> change 0) (make-string change ?\s)))
909 (at-end (= col ses--numcols)))
910 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
911 ;;ses-set-with-undo always returns t for strings.
912 (1value (ses-set-with-undo 'ses--blank-line
913 (concat (make-string ses--linewidth ?\s) "\n")))
914 (dotimes (row ses--numrows)
915 (ses-goto-print row col)
917 ;;Insert new columns before newline
918 (let ((inhibit-point-motion-hooks t))
922 (delete-char (- change))))))
924 (defun ses-print-cell-new-width (row col)
925 "Same as ses-print-cell, except if the cell's value is *skip*, the preceding
926 nonskipped cell is reprinted. This function is used when the width of
927 cell (ROW,COL) has changed."
928 (if (not (eq (ses-cell-value row col) '*skip*))
929 (ses-print-cell row col)
930 ;;Cell was skipped over - reprint previous
931 (ses-goto-print row col)
933 (let ((rowcol (ses-sym-rowcol (get-text-property (point) 'intangible))))
934 (ses-print-cell (car rowcol) (cdr rowcol)))))
937 ;;----------------------------------------------------------------------------
939 ;;----------------------------------------------------------------------------
941 (defun ses-narrowed-p () (/= (- (point-max) (point-min)) (buffer-size)))
944 "Turn off narrowing, to be reenabled at end of command loop."
946 (setq ses--deferred-narrow t))
949 (defun ses-goto-data (def &optional col)
950 "Move point to data area for (DEF,COL). If DEF is a row
951 number, COL is the column number for a data cell -- otherwise DEF
952 is one of the symbols ses--col-widths, ses--col-printers,
953 ses--default-printer, ses--numrows, or ses--numcols."
955 (let ((inhibit-point-motion-hooks t)) ;In case intangible attrs are wrong
956 (goto-char (point-min))
959 (forward-line (+ ses--numrows 2 (* def (1+ ses--numcols)) col))
960 ;;Convert def-symbol to offset
961 (setq def (plist-get ses-paramlines-plist def))
962 (or def (signal 'args-out-of-range nil))
963 (forward-line (+ (* ses--numrows (+ ses--numcols 2)) def)))))
965 (defun ses-set-parameter (def value &optional elem)
966 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
967 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
968 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
970 ;;We call ses-goto-data early, using the old values of numrows and
971 ;;numcols in case one of them is being changed.
973 (let ((inhibit-read-only t)
974 (fmt (plist-get '(ses--col-widths "(ses-column-widths %S)"
975 ses--col-printers "(ses-column-printers %S)"
976 ses--default-printer "(ses-default-printer %S)"
977 ses--header-row "(ses-header-row %S)"
978 ses--file-format " %S ;SES file-format"
979 ses--numrows " %S ;numrows"
980 ses--numcols " %S ;numcols")
985 (setq oldval (aref (symbol-value def) elem))
986 (aset (symbol-value def) elem value))
987 (setq oldval (symbol-value def))
989 ;;Special undo since it's outside the narrowed buffer
990 (let (buffer-undo-list)
991 (delete-region (point) (line-end-position))
992 (insert (format fmt (symbol-value def))))
993 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
996 (defun ses-write-cells ()
997 "Write cells in `ses--deferred-write' from local variables to data area.
998 Newlines in the data are escaped."
999 (let* ((inhibit-read-only t)
1000 (print-escape-newlines t)
1001 rowcol row col cell sym formula printer text)
1002 (setq ses-start-time (float-time))
1003 (with-temp-message " "
1005 (while ses--deferred-write
1006 (ses-time-check "Writing... (%d cells left)"
1007 '(length ses--deferred-write))
1008 (setq rowcol (pop ses--deferred-write)
1011 cell (ses-get-cell row col)
1012 sym (ses-cell-symbol cell)
1013 formula (ses-cell-formula cell)
1014 printer (ses-cell-printer cell))
1015 (if (eq (car-safe formula) 'ses-safe-formula)
1016 (setq formula (cadr formula)))
1017 (if (eq (car-safe printer) 'ses-safe-printer)
1018 (setq printer (cadr printer)))
1019 ;;This is noticably faster than (format "%S %S %S %S %S")
1020 (setq text (concat "(ses-cell "
1023 (prin1-to-string (symbol-value sym))
1025 (prin1-to-string formula)
1027 (prin1-to-string printer)
1029 (if (atom (ses-cell-references cell))
1032 (mapconcat 'symbol-name
1033 (ses-cell-references cell)
1037 (ses-goto-data row col)
1038 (delete-region (point) (line-end-position))
1043 ;;----------------------------------------------------------------------------
1044 ;; Formula relocation
1045 ;;----------------------------------------------------------------------------
1047 (defun ses-formula-references (formula &optional result-so-far)
1048 "Produce a list of symbols for cells that this formula's value
1049 refers to. For recursive calls, RESULT-SO-FAR is the list being constructed,
1050 or t to get a wrong-type-argument error when the first reference is found."
1052 (if (ses-sym-rowcol formula)
1053 ;;Entire formula is one symbol
1054 (add-to-list 'result-so-far formula)
1055 ) ;;Ignore other atoms
1056 (dolist (cur formula)
1058 ((ses-sym-rowcol cur)
1059 ;;Save this reference
1060 (add-to-list 'result-so-far cur))
1061 ((eq (car-safe cur) 'ses-range)
1062 ;;All symbols in range are referenced
1063 (dolist (x (cdr (macroexpand cur)))
1064 (add-to-list 'result-so-far x)))
1065 ((and (consp cur) (not (eq (car cur) 'quote)))
1066 ;;Recursive call for subformulas
1067 (setq result-so-far (ses-formula-references cur result-so-far)))
1069 ;;Ignore other stuff
1073 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1074 "Produce a copy of FORMULA where all symbols that refer to cells in row
1075 STARTROW or above and col STARTCOL or above are altered by adding ROWINCR
1076 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1077 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1079 If ROWINCR or COLINCR is negative, references to cells being deleted are
1081 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1083 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1084 (let (rowcol result)
1085 (if (or (atom formula) (eq (car formula) 'quote))
1086 (if (setq rowcol (ses-sym-rowcol formula))
1087 (ses-relocate-symbol formula rowcol
1088 startrow startcol rowincr colincr)
1089 formula) ;Pass through as-is
1090 (dolist (cur formula)
1091 (setq rowcol (ses-sym-rowcol cur))
1094 (setq cur (ses-relocate-symbol cur rowcol
1095 startrow startcol rowincr colincr))
1098 ;;Reference to a deleted cell. Set a flag in ses-relocate-return.
1099 ;;don't change the flag if it's already 'range, since range
1101 (unless ses-relocate-return
1102 (setq ses-relocate-return 'delete))))
1103 ((eq (car-safe cur) 'ses-range)
1104 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1107 ((or (atom cur) (eq (car cur) 'quote))
1108 ;;Constants pass through unchanged
1111 ;;Recursively copy and alter subformulas
1112 (push (ses-relocate-formula cur startrow startcol
1115 (nreverse result))))
1117 (defun ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1118 "Relocate one symbol SYM, whichs corresponds to ROWCOL (a cons of ROW and
1119 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1120 by (ROWINCR,COLINCR)."
1121 (let ((row (car rowcol))
1123 (if (or (< row startrow) (< col startcol))
1125 (setq row (+ row rowincr)
1126 col (+ col colincr))
1127 (if (and (>= row startrow) (>= col startcol)
1128 (< row ses--numrows) (< col ses--numcols))
1129 ;;Relocate this variable
1130 (ses-create-cell-symbol row col)
1131 ;;Delete reference to a deleted cell
1134 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1135 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1136 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1137 new range, or nil if the entire range is deleted. If new rows are being added
1138 just beyond the end of a row range, or new columns just beyond a column range,
1139 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1140 if the range was altered."
1141 (let* ((minorig (cadr range))
1142 (minrowcol (ses-sym-rowcol minorig))
1143 (min (ses-relocate-symbol minorig minrowcol
1146 (maxorig (nth 2 range))
1147 (maxrowcol (ses-sym-rowcol maxorig))
1148 (max (ses-relocate-symbol maxorig maxrowcol
1153 ((and (not min) (not max))
1154 (setq range nil)) ;;The entire range is deleted
1156 ;;Inserting or deleting rows
1159 ;;Chopped off beginning of range
1160 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1161 ses-relocate-return 'range))
1164 ;;Trying to insert a nonexistent row
1165 (setq max (ses-create-cell-symbol (1- ses--numrows)
1167 ;;End of range is being deleted
1168 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1169 ses-relocate-return 'range))
1171 (= (car maxrowcol) (1- startrow))
1172 (= (cdr minrowcol) (cdr maxrowcol))
1173 ;;Insert after ending row of vertical range - include it
1174 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1175 (cdr maxrowcol))))))
1177 ;;Inserting or deleting columns
1180 ;;Chopped off beginning of range
1181 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1182 ses-relocate-return 'range))
1185 ;;Trying to insert a nonexistent column
1186 (setq max (ses-create-cell-symbol (car maxrowcol)
1188 ;;End of range is being deleted
1189 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1190 ses-relocate-return 'range))
1192 (= (cdr maxrowcol) (1- startcol))
1193 (= (car minrowcol) (car maxrowcol))
1194 ;;Insert after ending column of horizontal range - include it
1195 (setq max (ses-create-cell-symbol (car maxrowcol)
1196 (+ startcol colincr -1)))))))
1198 (if (/= (- (funcall field maxrowcol)
1199 (funcall field minrowcol))
1200 (- (funcall field (ses-sym-rowcol max))
1201 (funcall field (ses-sym-rowcol min))))
1202 ;;This range has changed size
1203 (setq ses-relocate-return 'range))
1204 (list 'ses-range min max))))
1206 (defun ses-relocate-all (minrow mincol rowincr colincr)
1207 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1208 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1211 (let (mycell newval)
1212 (dotimes-with-progress-reporter
1213 (row ses--numrows) "Relocating formulas..."
1214 (dotimes (col ses--numcols)
1215 (setq ses-relocate-return nil
1216 mycell (ses-get-cell row col)
1217 newval (ses-relocate-formula (ses-cell-formula mycell)
1218 minrow mincol rowincr colincr))
1219 (ses-set-cell row col 'formula newval)
1220 (if (eq ses-relocate-return 'range)
1221 ;;This cell contains a (ses-range X Y) where a cell has been
1222 ;;inserted or deleted in the middle of the range.
1223 (push (cons row col) reform))
1224 (if ses-relocate-return
1225 ;;This cell referred to a cell that's been deleted or is no
1226 ;;longer part of the range. We can't fix that now because
1227 ;;reference lists cells have been partially updated.
1228 (add-to-list 'ses--deferred-recalc
1229 (ses-create-cell-symbol row col)))
1230 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1231 minrow mincol rowincr colincr))
1232 (ses-set-cell row col 'references newval)
1233 (and (>= row minrow) (>= col mincol)
1234 (ses-set-cell row col 'symbol
1235 (ses-create-cell-symbol row col))))))
1236 ;;Relocate the cell values
1237 (let (oldval myrow mycol xrow xcol)
1239 ((and (<= rowincr 0) (<= colincr 0))
1240 ;;Deletion of rows and/or columns
1241 (dotimes-with-progress-reporter
1242 (row (- ses--numrows minrow)) "Relocating variables..."
1243 (setq myrow (+ row minrow))
1244 (dotimes (col (- ses--numcols mincol))
1245 (setq mycol (+ col mincol)
1246 xrow (- myrow rowincr)
1247 xcol (- mycol colincr))
1248 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1249 (setq oldval (ses-cell-value xrow xcol))
1250 ;;Cell is off the end of the array
1251 (setq oldval (symbol-value (ses-create-cell-symbol xrow xcol))))
1252 (ses-set-cell myrow mycol 'value oldval))))
1253 ((and (wholenump rowincr) (wholenump colincr))
1254 ;;Insertion of rows and/or columns. Run the loop backwards.
1255 (let ((disty (1- ses--numrows))
1256 (distx (1- ses--numcols))
1258 (dotimes-with-progress-reporter
1259 (row (- ses--numrows minrow)) "Relocating variables..."
1260 (setq myrow (- disty row))
1261 (dotimes (col (- ses--numcols mincol))
1262 (setq mycol (- distx col)
1263 xrow (- myrow rowincr)
1264 xcol (- mycol colincr))
1265 (if (or (< xrow minrow) (< xcol mincol))
1266 ;;Newly-inserted value
1268 ;;Transfer old value
1269 (setq oldval (ses-cell-value xrow xcol)))
1270 (ses-set-cell myrow mycol 'value oldval)))
1271 t)) ;Make testcover happy by returning non-nil here
1273 (error "ROWINCR and COLINCR must have the same sign"))))
1274 ;;Reconstruct reference lists for cells that contain ses-ranges that
1275 ;;have changed size.
1277 (message "Fixing ses-ranges...")
1279 (setq ses-start-time (float-time))
1281 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1282 (setq row (caar reform)
1284 reform (cdr reform))
1285 (ses-cell-set-formula row col (ses-cell-formula row col))))
1289 ;;----------------------------------------------------------------------------
1291 ;;----------------------------------------------------------------------------
1293 (defun ses-begin-change ()
1294 "For undo, remember point before we start changing hidden stuff."
1295 (let ((inhibit-read-only t))
1296 (insert-and-inherit "X")
1297 (delete-region (1- (point)) (point))))
1299 (defun ses-set-with-undo (sym newval)
1300 "Like set, but undoable. Result is t if value has changed."
1301 ;;We try to avoid adding redundant entries to the undo list, but this is
1302 ;;unavoidable for strings because equal ignores text properties and there's
1303 ;;no easy way to get the whole property list to see if it's different!
1304 (unless (and (boundp sym)
1305 (equal (symbol-value sym) newval)
1306 (not (stringp newval)))
1307 (push (if (boundp sym)
1308 `(apply ses-set-with-undo ,sym ,(symbol-value sym))
1309 `(apply ses-unset-with-undo ,sym))
1314 (defun ses-unset-with-undo (sym)
1315 "Set SYM to be unbound. This is undoable."
1316 (when (1value (boundp sym)) ;;Always bound, except after a programming error
1317 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
1320 (defun ses-aset-with-undo (array idx newval)
1321 "Like aset, but undoable. Result is t if element has changed"
1322 (unless (equal (aref array idx) newval)
1323 (push `(apply ses-aset-with-undo ,array ,idx ,(aref array idx)) buffer-undo-list)
1324 (aset array idx newval)
1328 ;;----------------------------------------------------------------------------
1329 ;; Startup for major mode
1330 ;;----------------------------------------------------------------------------
1333 "Parse the current buffer and sets up buffer-local variables. Does not
1334 execute cell formulas or print functions."
1336 ;;Read our global parameters, which should be a 3-element list
1337 (goto-char (point-max))
1338 (search-backward ";; Local Variables:\n" nil t)
1340 (let ((params (condition-case nil (read (current-buffer)) (error nil))))
1341 (or (and (= (safe-length params) 3)
1342 (numberp (car params))
1343 (numberp (cadr params))
1344 (>= (cadr params) 0)
1345 (numberp (nth 2 params))
1346 (> (nth 2 params) 0))
1347 (error "Invalid SES file"))
1348 (setq ses--file-format (car params)
1349 ses--numrows (cadr params)
1350 ses--numcols (nth 2 params))
1351 (when (= ses--file-format 1)
1352 (let (buffer-undo-list) ;This is not undoable
1353 (ses-goto-data 'ses--header-row)
1354 (insert "(ses-header-row 0)\n")
1355 (ses-set-parameter 'ses--file-format 2)
1356 (message "Upgrading from SES-1 file format")))
1357 (or (= ses--file-format 2)
1358 (error "This file needs a newer version of the SES library code"))
1359 (ses-create-cell-variable-range 0 (1- ses--numrows) 0 (1- ses--numcols))
1360 ;;Initialize cell array
1361 (setq ses--cells (make-vector ses--numrows nil))
1362 (dotimes (row ses--numrows)
1363 (aset ses--cells row (make-vector ses--numcols nil))))
1364 ;;Skip over print area, which we assume is correct
1365 (goto-char (point-min))
1366 (forward-line ses--numrows)
1367 (or (looking-at ses-print-data-boundary)
1368 (error "Missing marker between print and data areas"))
1369 (forward-char (length ses-print-data-boundary))
1370 ;;Initialize printer and symbol lists
1371 (mapc 'ses-printer-record ses-standard-printer-functions)
1372 (setq ses--symbolic-formulas nil)
1373 ;;Load cell definitions
1374 (dotimes (row ses--numrows)
1375 (dotimes (col ses--numcols)
1376 (let* ((x (read (current-buffer)))
1377 (rowcol (ses-sym-rowcol (car-safe (cdr-safe x)))))
1378 (or (and (looking-at "\n")
1379 (eq (car-safe x) 'ses-cell)
1380 (eq row (car rowcol))
1381 (eq col (cdr rowcol)))
1382 (error "Cell-def error"))
1384 (or (looking-at "\n\n")
1385 (error "Missing blank line between rows")))
1386 ;;Load global parameters
1387 (let ((widths (read (current-buffer)))
1388 (n1 (char-after (point)))
1389 (printers (read (current-buffer)))
1390 (n2 (char-after (point)))
1391 (def-printer (read (current-buffer)))
1392 (n3 (char-after (point)))
1393 (head-row (read (current-buffer)))
1394 (n4 (char-after (point))))
1395 (or (and (eq (car-safe widths) 'ses-column-widths)
1397 (eq (car-safe printers) 'ses-column-printers)
1399 (eq (car-safe def-printer) 'ses-default-printer)
1401 (eq (car-safe head-row) 'ses-header-row)
1403 (error "Invalid SES global parameters"))
1404 (1value (eval widths))
1405 (1value (eval def-printer))
1406 (1value (eval printers))
1407 (1value (eval head-row)))
1408 ;;Should be back at global-params
1410 (or (looking-at (replace-regexp-in-string "1" "[0-9]+"
1411 ses-initial-global-parameters))
1412 (error "Problem with column-defs or global-params"))
1413 ;;Check for overall newline count in definitions area
1415 (let ((start (point)))
1416 (ses-goto-data 'ses--numrows)
1417 (or (= (point) start)
1418 (error "Extraneous newlines someplace?"))))
1421 "Set up for display of only the printed cell values.
1423 Narrows the buffer to show only the print area. Gives it `read-only' and
1424 `intangible' properties. Sets up highlighting for current cell."
1426 (let ((end (point-min))
1427 (inhibit-read-only t)
1428 (was-modified (buffer-modified-p))
1430 (ses-goto-data 0 0) ;;Include marker between print-area and data-area
1431 (set-text-properties (point) (point-max) nil) ;Delete garbage props
1432 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1433 ;;The print area is read-only (except for our special commands) and uses a
1435 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1436 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1437 ;;For the beginning of the buffer, we want the read-only and keymap
1438 ;;attributes to be inherited from the first character
1439 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1440 ;;Create intangible properties, which also indicate which cell the text
1442 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1443 (dotimes (col ses--numcols)
1445 sym (ses-cell-symbol row col))
1446 ;;Include skipped cells following this one
1447 (while (and (< col (1- ses--numcols))
1448 (eq (ses-cell-value row (1+ col)) '*skip*))
1449 (setq end (+ end (ses-col-width col) 1)
1451 (setq end (+ end (ses-col-width col) 1))
1452 (put-text-property pos end 'intangible sym)))
1453 ;;Adding these properties did not actually alter the text
1454 (unless was-modified
1455 (restore-buffer-modified-p nil)
1456 (buffer-disable-undo)
1457 (buffer-enable-undo)))
1458 ;;Create the underlining overlay. It's impossible for (point) to be 2,
1459 ;;because column A must be at least 1 column wide.
1460 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1461 (overlay-put ses--curcell-overlay 'face 'underline))
1463 (defun ses-cleanup ()
1464 "Cleanup when changing a buffer from SES mode to something else. Delete
1465 overlay, remove special text properties."
1467 (let ((inhibit-read-only t)
1468 (was-modified (buffer-modified-p)))
1469 ;;Delete read-only, keymap, and intangible properties
1470 (set-text-properties (point-min) (point-max) nil)
1472 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1473 (unless was-modified
1474 (set-buffer-modified-p nil))))
1478 "Major mode for Simple Emacs Spreadsheet.
1479 See \"ses-example.ses\" (in the etc data directory) for more info.
1483 These key definitions are active only in the print area (the visible part):
1484 \\{ses-mode-print-map}
1485 These are active only in the minibuffer, when entering or editing a formula:
1486 \\{ses-mode-edit-map}"
1488 (unless (and (boundp 'ses--deferred-narrow)
1489 (eq ses--deferred-narrow 'ses-mode))
1490 (kill-all-local-variables)
1491 (mapc 'make-local-variable ses-localvars)
1492 (setq major-mode 'ses-mode
1494 next-line-add-newlines nil
1496 ;;SES deliberately puts lots of trailing whitespace in its buffer
1497 show-trailing-whitespace nil
1498 ;;Cell ranges do not work reasonably without this
1499 transient-mark-mode t)
1500 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1501 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1502 (setq ses--curcell nil
1503 ses--deferred-recalc nil
1504 ses--deferred-write nil
1505 ses--header-hscroll -1 ;Flag for "initial recalc needed"
1506 header-line-format '(:eval (progn
1507 (when (/= (window-hscroll)
1508 ses--header-hscroll)
1509 ;;Reset ses--header-hscroll first, to
1510 ;;avoid recursion problems when
1511 ;;debugging ses-create-header-string
1512 (setq ses--header-hscroll
1514 (ses-create-header-string))
1515 ses--header-string)))
1516 (let ((was-empty (zerop (buffer-size)))
1517 (was-modified (buffer-modified-p)))
1520 ;;Initialize buffer to contain one cell, for now
1521 (insert ses-initial-file-contents))
1525 (unless (equal ses-initial-default-printer (1value ses--default-printer))
1526 (1value (ses-read-default-printer ses-initial-default-printer)))
1527 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1528 (1value (ses-set-column-width 0 ses-initial-column-width)))
1530 (if (> (car ses-initial-size) (1value ses--numrows))
1531 (1value (ses-insert-row (1- (car ses-initial-size)))))
1532 (if (> (cdr ses-initial-size) (1value ses--numcols))
1533 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1535 (restore-buffer-modified-p was-modified)
1536 (buffer-disable-undo)
1537 (buffer-enable-undo)
1538 (goto-char (point-min))))
1539 (use-local-map ses-mode-map)
1540 ;;Set the deferred narrowing flag (we can't narrow until after
1541 ;;after-find-file completes). If .ses is on the auto-load alist and the
1542 ;;file has "mode: ses", our ses-mode function will be called twice! Use
1543 ;;a special flag to detect this (will be reset by ses-command-hook).
1544 ;;For find-alternate-file, post-command-hook doesn't get run for some
1545 ;;reason, so use an idle timer to make sure.
1546 (setq ses--deferred-narrow 'ses-mode)
1547 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1548 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1549 (run-mode-hooks 'ses-mode-hook)))
1551 (put 'ses-mode 'mode-class 'special)
1553 (defun ses-command-hook ()
1554 "Invoked from `post-command-hook'. If point has moved to a different cell,
1555 moves the underlining overlay. Performs any recalculations or cell-data
1556 writes that have been deferred. If buffer-narrowing has been deferred,
1557 narrows the buffer now."
1559 (when (eq major-mode 'ses-mode) ;Otherwise, not our buffer anymore
1560 (when ses--deferred-recalc
1561 ;;We reset the deferred list before starting on the recalc -- in case
1562 ;;of error, we don't want to retry the recalc after every keystroke!
1563 (let ((old ses--deferred-recalc))
1564 (setq ses--deferred-recalc nil)
1565 (ses-update-cells old)))
1566 (when ses--deferred-write
1567 ;;We don't reset the deferred list before starting -- the most
1568 ;;likely error is keyboard-quit, and we do want to keep trying
1569 ;;these writes after a quit.
1571 (push '(apply ses-widen) buffer-undo-list))
1572 (when ses--deferred-narrow
1573 ;;We're not allowed to narrow the buffer until after-find-file has
1574 ;;read the local variables at the end of the file. Now it's safe to
1577 (goto-char (point-min))
1578 (forward-line ses--numrows)
1579 (narrow-to-region (point-min) (point)))
1580 (setq ses--deferred-narrow nil))
1581 ;;Update the modeline
1582 (let ((oldcell ses--curcell))
1584 (unless (eq ses--curcell oldcell)
1587 (setq mode-line-process nil))
1588 ((atom ses--curcell)
1589 (setq mode-line-process (list " cell "
1590 (symbol-name ses--curcell))))
1592 (setq mode-line-process (list " range "
1593 (symbol-name (car ses--curcell))
1595 (symbol-name (cdr ses--curcell))))))
1596 (force-mode-line-update)))
1597 ;;Use underline overlay for single-cells only, turn off otherwise
1598 (if (listp ses--curcell)
1599 (move-overlay ses--curcell-overlay 2 2)
1600 (let ((next (next-single-property-change (point) 'intangible)))
1601 (move-overlay ses--curcell-overlay (point) (1- next))))
1602 (when (not (pos-visible-in-window-p))
1603 ;;Scrolling will happen later
1604 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1605 (setq ses--curcell t)))
1606 ;;Prevent errors in this post-command-hook from silently erasing the hook!
1608 (unless executing-kbd-macro
1610 (message "%s" (error-message-string err))))
1611 nil) ;Make coverage-tester happy
1613 (defun ses-create-header-string ()
1614 "Set up `ses--header-string' as the buffer's header line.
1615 Based on the current set of columns and `window-hscroll' position."
1616 (let ((totwidth (- (window-hscroll)))
1618 ;;Leave room for the left-side fringe and scrollbar
1619 (push (propertize " " 'display '((space :align-to 0))) result)
1620 (dotimes (col ses--numcols)
1621 (setq width (ses-col-width col)
1622 totwidth (+ totwidth width 1))
1624 ;;Scrolled so intercolumn space is leftmost
1626 (when (> totwidth 1)
1627 (if (> ses--header-row 0)
1629 (ses-goto-print (1- ses--header-row) col)
1630 (setq x (buffer-substring-no-properties (point)
1632 ;; Strip trailing space.
1633 (if (string-match "[ \t]+\\'" x)
1634 (setq x (substring x 0 (match-beginning 0))))
1635 ;; Cut off excess text.
1636 (if (>= (length x) totwidth)
1637 (setq x (substring x 0 (- totwidth -1)))))
1638 (setq x (ses-column-letter col)))
1639 (push (propertize x 'face ses-box-prop) result)
1640 (push (propertize "."
1641 'display `((space :align-to ,(1- totwidth)))
1644 ;;Allow the following space to be squished to make room for the 3-D box
1645 ;;Coverage test ignores properties, thinks this is always a space!
1646 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
1648 (if (> ses--header-row 0)
1649 (push (propertize (format " [row %d]" ses--header-row)
1650 'display '((height (- 1))))
1652 (setq ses--header-string (apply 'concat (nreverse result)))))
1655 ;;----------------------------------------------------------------------------
1656 ;; Redisplay and recalculation
1657 ;;----------------------------------------------------------------------------
1659 (defun ses-jump (sym)
1660 "Move point to cell SYM."
1661 (interactive "SJump to cell: ")
1662 (let ((rowcol (ses-sym-rowcol sym)))
1663 (or rowcol (error "Invalid cell name"))
1664 (if (eq (symbol-value sym) '*skip*)
1665 (error "Cell is covered by preceding cell"))
1666 (ses-goto-print (car rowcol) (cdr rowcol))))
1668 (defun ses-jump-safe (cell)
1669 "Like `ses-jump', but no error if invalid cell."
1674 (defun ses-reprint-all (&optional nonarrow)
1675 "Recreate the display area. Calls all printer functions. Narrows to
1676 print area if NONARROW is nil."
1680 (setq ses--deferred-narrow t))
1681 (let ((startcell (get-text-property (point) 'intangible))
1682 (inhibit-read-only t))
1684 (goto-char (point-min))
1685 (search-forward ses-print-data-boundary)
1686 (backward-char (length ses-print-data-boundary))
1687 (delete-region (point-min) (point))
1688 ;;Insert all blank lines before printing anything, so ses-print-cell can
1689 ;;find the data area when inserting or deleting *skip* values for cells
1690 (dotimes (row ses--numrows)
1691 (insert-and-inherit ses--blank-line))
1692 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
1693 (if (eq (ses-cell-value row 0) '*skip*)
1694 ;;Column deletion left a dangling skip
1695 (ses-set-cell row 0 'value nil))
1696 (dotimes (col ses--numcols)
1697 (ses-print-cell row col))
1698 (beginning-of-line 2))
1699 (ses-jump-safe startcell)))
1701 (defun ses-recalculate-cell ()
1702 "Recalculate and reprint the current cell or range.
1704 For an individual cell, shows the error if the formula or printer
1705 signals one, or otherwise shows the cell's complete value. For a range, the
1706 cells are recalculated in \"natural\" order, so cells that other cells refer
1707 to are recalculated first."
1709 (ses-check-curcell 'range)
1712 (setq ses-start-time (float-time))
1713 (if (atom ses--curcell)
1714 (setq sig (ses-sym-rowcol ses--curcell)
1715 sig (ses-calculate-cell (car sig) (cdr sig) t))
1716 ;;First, recalculate all cells that don't refer to other cells and
1717 ;;produce a list of cells with references.
1718 (ses-dorange ses--curcell
1719 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
1722 ;;The t causes an error if the cell has references.
1723 ;;If no references, the t will be the result value.
1724 (1value (ses-formula-references (ses-cell-formula row col) t))
1725 (setq sig (ses-calculate-cell row col t)))
1726 (wrong-type-argument
1727 ;;The formula contains a reference
1728 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
1729 ;;Do the update now, so we can force recalculation
1730 (let ((x ses--deferred-recalc))
1731 (setq ses--deferred-recalc nil)
1732 (condition-case hold
1733 (ses-update-cells x t)
1734 (error (setq sig hold))))
1737 (message "%s" (error-message-string sig)))
1738 ((consp ses--curcell)
1741 (princ (symbol-value ses--curcell))))))
1743 (defun ses-recalculate-all ()
1744 "Recalculate and reprint all cells."
1746 (let ((startcell (get-text-property (point) 'intangible))
1747 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
1748 (1- ses--numcols)))))
1749 (ses-recalculate-cell)
1750 (ses-jump-safe startcell)))
1752 (defun ses-truncate-cell ()
1753 "Reprint current cell, but without spillover into any following blank
1757 (let* ((rowcol (ses-sym-rowcol ses--curcell))
1760 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
1761 (eq (ses-cell-value row (1+ col)) '*skip*))
1762 ;;This cell has spill-over. We'll momentarily pretend the following
1763 ;;cell has a `t' in it.
1764 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
1765 (ses-print-cell row col)))
1766 ;;Now remove the *skip*. ses-print-cell is always nil here
1767 (ses-set-cell row (1+ col) 'value nil)
1768 (1value (ses-print-cell row (1+ col))))))
1770 (defun ses-reconstruct-all ()
1771 "Reconstruct buffer based on cell data stored in Emacs variables."
1774 ;;Reconstruct reference lists.
1776 ;;Delete old reference lists
1777 (dotimes-with-progress-reporter
1778 (row ses--numrows) "Deleting references..."
1779 (dotimes (col ses--numcols)
1780 (ses-set-cell row col 'references nil)))
1781 ;;Create new reference lists
1782 (dotimes-with-progress-reporter
1783 (row ses--numrows) "Computing references..."
1784 (dotimes (col ses--numcols)
1785 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
1786 (setq x (ses-sym-rowcol ref)
1789 (ses-set-cell yrow ycol 'references
1790 (cons (ses-cell-symbol row col)
1791 (ses-cell-references yrow ycol)))))))
1792 ;;Delete everything and reconstruct basic data area
1794 (let ((inhibit-read-only t))
1795 (goto-char (point-max))
1796 (if (search-backward ";; Local Variables:\n" nil t)
1797 (delete-region (point-min) (point))
1798 ;;Buffer is quite screwed up - can't even save the user-specified locals
1799 (delete-region (point-min) (point-max))
1800 (insert ses-initial-file-trailer)
1801 (goto-char (point-min)))
1802 ;;Create a blank display area
1803 (dotimes (row ses--numrows)
1804 (insert ses--blank-line))
1805 (insert ses-print-data-boundary)
1806 ;;Placeholders for cell data
1807 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
1808 ;;Placeholders for col-widths, col-printers, default-printer, header-row
1810 (insert ses-initial-global-parameters))
1811 (ses-set-parameter 'ses--col-widths ses--col-widths)
1812 (ses-set-parameter 'ses--col-printers ses--col-printers)
1813 (ses-set-parameter 'ses--default-printer ses--default-printer)
1814 (ses-set-parameter 'ses--header-row ses--header-row)
1815 (ses-set-parameter 'ses--numrows ses--numrows)
1816 (ses-set-parameter 'ses--numcols ses--numcols)
1817 ;;Keep our old narrowing
1819 (ses-recalculate-all)
1820 (goto-char (point-min)))
1823 ;;----------------------------------------------------------------------------
1824 ;; Input of cell formulas
1825 ;;----------------------------------------------------------------------------
1827 (defun ses-edit-cell (row col newval)
1828 "Display current cell contents in minibuffer, for editing. Returns nil if
1829 cell formula was unsafe and user declined confirmation."
1832 (barf-if-buffer-read-only)
1834 (let* ((rowcol (ses-sym-rowcol ses--curcell))
1837 (formula (ses-cell-formula row col))
1839 (if (eq (car-safe formula) 'ses-safe-formula)
1840 (setq formula (cadr formula)))
1841 (if (eq (car-safe formula) 'quote)
1842 (setq initial (format "'%S" (cadr formula)))
1843 (setq initial (prin1-to-string formula)))
1844 (if (stringp formula)
1845 ;;Position cursor inside close-quote
1846 (setq initial (cons initial (length initial))))
1848 (read-from-minibuffer (format "Cell %s: " ses--curcell)
1851 t ;Convert to Lisp object
1852 'ses-read-cell-history)))))
1853 (when (ses-warn-unsafe newval 'unsafep)
1855 (ses-cell-set-formula row col newval)
1858 (defun ses-read-cell (row col newval)
1859 "Self-insert for initial character of cell function."
1861 (let* ((initial (this-command-keys))
1862 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
1863 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
1864 (barf-if-buffer-read-only)
1867 (read-from-minibuffer
1868 (format "Cell %s: " ses--curcell)
1869 (cons (if (equal initial "\"") "\"\""
1870 (if (equal initial "(") "()" initial)) 2)
1872 t ;Convert to Lisp object
1873 'ses-read-cell-history
1874 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
1877 (when (ses-edit-cell row col newval)
1878 (ses-command-hook) ;Update cell widths before movement
1879 (dolist (x ses-after-entry-functions)
1882 (defun ses-read-symbol (row col symb)
1883 "Self-insert for a symbol as a cell formula. The set of all symbols that
1884 have been used as formulas in this spreadsheet is available for completions."
1886 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
1888 (barf-if-buffer-read-only)
1889 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
1890 ses--symbolic-formulas))
1893 (if (string= newval "")
1894 nil ;Don't create zero-length symbols!
1895 (list 'quote (intern newval))))))
1896 (when (ses-edit-cell row col symb)
1897 (ses-command-hook) ;Update cell widths before movement
1898 (dolist (x ses-after-entry-functions)
1901 (defun ses-clear-cell-forward (count)
1902 "Delete formula and printer for current cell and then move to next cell.
1903 With prefix, deletes several cells."
1906 (1value (ses-clear-cell-backward (- count)))
1911 (let ((rowcol (ses-sym-rowcol ses--curcell)))
1912 (or rowcol (signal 'end-of-buffer nil))
1913 (ses-clear-cell (car rowcol) (cdr rowcol)))
1916 (defun ses-clear-cell-backward (count)
1917 "Move to previous cell and then delete it. With prefix, deletes several
1921 (1value (ses-clear-cell-forward (- count)))
1922 (ses-check-curcell 'end)
1925 (backward-char 1) ;Will signal 'beginning-of-buffer if appropriate
1927 (let ((rowcol (ses-sym-rowcol ses--curcell)))
1928 (ses-clear-cell (car rowcol) (cdr rowcol))))))
1931 ;;----------------------------------------------------------------------------
1932 ;; Input of cell-printer functions
1933 ;;----------------------------------------------------------------------------
1935 (defun ses-read-printer (prompt default)
1936 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
1937 PROMPT should end with \": \". Result is t if operation was cancelled."
1938 (barf-if-buffer-read-only)
1941 (setq prompt (format "%s [currently %S]: "
1942 (substring prompt 0 -2)
1944 (let ((new (read-from-minibuffer prompt
1945 nil ;Initial contents
1947 t ;Evaluate the result
1948 'ses-read-printer-history
1949 (prin1-to-string default))))
1950 (if (equal new default)
1951 ;;User changed mind, decided not to change printer
1953 (ses-printer-validate new)
1956 (stringp (car-safe new))
1957 (ses-warn-unsafe new 'unsafep-function)
1961 (defun ses-read-cell-printer (newval)
1962 "Set the printer function for the current cell or range.
1964 A printer function is either a string (a format control-string with one
1965 %-sequence -- result from format will be right-justified), or a list of one
1966 string (result from format will be left-justified), or a lambda-expression of
1967 one argument, or a symbol that names a function of one argument. In the
1968 latter two cases, the function's result should be either a string (will be
1969 right-justified) or a list of one string (will be left-justified)."
1973 (ses-check-curcell 'range)
1974 ;;Default is none if not all cells in range have same printer
1975 (catch 'ses-read-cell-printer
1976 (ses-dorange ses--curcell
1977 (setq x (ses-cell-printer row col))
1978 (if (eq (car-safe x) 'ses-safe-printer)
1982 (unless (equal default x)
1983 ;;Range contains differing printer functions
1985 (throw 'ses-read-cell-printer t)))))
1986 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
1988 (unless (eq newval t)
1990 (ses-dorange ses--curcell
1991 (ses-set-cell row col 'printer newval)
1992 (ses-print-cell row col))))
1994 (defun ses-read-column-printer (col newval)
1995 "Set the printer function for the current column. See
1996 `ses-read-cell-printer' for input forms."
1998 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2000 (list col (ses-read-printer (format "Column %s printer: "
2001 (ses-column-letter col))
2002 (ses-col-printer col)))))
2004 (unless (eq newval t)
2006 (ses-set-parameter 'ses--col-printers newval col)
2008 (dotimes (row ses--numrows)
2009 (ses-print-cell row col)))))
2011 (defun ses-read-default-printer (newval)
2012 "Set the default printer function for cells that have no other. See
2013 `ses-read-cell-printer' for input forms."
2015 (list (ses-read-printer "Default printer: " ses--default-printer)))
2016 (unless (eq newval t)
2018 (ses-set-parameter 'ses--default-printer newval)
2019 (ses-reprint-all t)))
2022 ;;----------------------------------------------------------------------------
2023 ;; Spreadsheet size adjustments
2024 ;;----------------------------------------------------------------------------
2026 (defun ses-insert-row (count)
2027 "Insert a new row before the current one. With prefix, insert COUNT rows
2028 before current one."
2030 (ses-check-curcell 'end)
2031 (or (> count 0) (signal 'args-out-of-range nil))
2033 (let ((inhibit-quit t)
2034 (inhibit-read-only t)
2035 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2037 ;;Create a new set of cell-variables
2038 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2039 0 (1- ses--numcols))
2040 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2042 (ses-goto-print row 0)
2043 (dotimes-with-progress-reporter (x count) "Inserting row..."
2044 ;;Create a row of empty cells. The `symbol' fields will be set by
2045 ;;the call to ses-relocate-all.
2046 (setq newrow (make-vector ses--numcols nil))
2047 (dotimes (col ses--numcols)
2048 (aset newrow col (ses-make-cell)))
2049 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2050 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2051 (insert ses--blank-line))
2052 ;;Insert empty lines in cell data area (will be replaced by
2054 (ses-goto-data row 0)
2055 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2056 (ses-relocate-all row 0 count 0)
2057 ;;If any cell printers insert constant text, insert that text
2059 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2060 (global (ses-call-printer ses--default-printer)))
2061 (if (or (> (length cols) 0) (> (length global) 0))
2063 (dotimes (col ses--numcols)
2064 ;;These cells are always nil, only constant formatting printed
2065 (1value (ses-print-cell (+ x row) col))))))
2066 (when (> ses--header-row row)
2067 ;;Inserting before header
2068 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2069 (ses-reset-header-string)))
2070 ;;Reconstruct text attributes
2073 (push '(apply ses-widen) buffer-undo-list)
2074 ;;Return to current cell
2076 (ses-jump-safe ses--curcell)
2077 (ses-goto-print (1- ses--numrows) 0)))
2079 (defun ses-delete-row (count)
2080 "Delete the current row. With prefix, Deletes COUNT rows starting from the
2084 (or (> count 0) (signal 'args-out-of-range nil))
2085 (let ((inhibit-quit t)
2086 (inhibit-read-only t)
2087 (row (car (ses-sym-rowcol ses--curcell))))
2088 (setq count (min count (- ses--numrows row)))
2090 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2091 ;;Delete lines from print area
2092 (ses-goto-print row 0)
2093 (ses-delete-line count)
2094 ;;Delete lines from cell data area
2095 (ses-goto-data row 0)
2096 (ses-delete-line (* count (1+ ses--numcols)))
2097 ;;Relocate variables and formulas
2098 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2099 (ses-relocate-all row 0 (- count) 0)
2100 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2101 0 (1- ses--numcols))
2102 (when (> ses--header-row row)
2103 (if (<= ses--header-row (+ row count))
2104 ;;Deleting the header row
2105 (ses-set-parameter 'ses--header-row 0)
2106 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2107 (ses-reset-header-string)))
2108 ;;Reconstruct attributes
2111 (push '(apply ses-widen) buffer-undo-list)
2112 (ses-jump-safe ses--curcell))
2114 (defun ses-insert-column (count &optional col width printer)
2115 "Insert a new column before COL (default is the current one).
2116 With prefix, insert COUNT columns before current one.
2117 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2118 \(otherwise they're taken from the current column)."
2121 (or (> count 0) (signal 'args-out-of-range nil))
2123 (setq col (cdr (ses-sym-rowcol ses--curcell))
2124 width (ses-col-width col)
2125 printer (ses-col-printer col)))
2127 (let ((inhibit-quit t)
2128 (inhibit-read-only t)
2129 (widths ses--col-widths)
2130 (printers ses--col-printers)
2132 ;;Create a new set of cell-variables
2133 (ses-create-cell-variable-range 0 (1- ses--numrows)
2134 ses--numcols (+ ses--numcols count -1))
2135 ;;Insert each column.
2136 (dotimes-with-progress-reporter (x count) "Inserting column..."
2137 ;;Create a column of empty cells. The `symbol' fields will be set by
2138 ;;the call to ses-relocate-all.
2139 (ses-adjust-print-width col (1+ width))
2140 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2141 (dotimes (row ses--numrows)
2142 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2143 ;;Inserting in the middle of a spill-over
2145 (ses-aset-with-undo ses--cells row
2146 (ses-vector-insert (aref ses--cells row)
2147 col (ses-make-cell)))
2148 ;;Insert empty lines in cell data area (will be replaced by
2150 (ses-goto-data row col)
2152 ;;Insert column width and printer
2153 (setq widths (ses-vector-insert widths col width)
2154 printers (ses-vector-insert printers col printer)))
2155 (ses-set-parameter 'ses--col-widths widths)
2156 (ses-set-parameter 'ses--col-printers printers)
2157 (ses-reset-header-string)
2158 (ses-relocate-all 0 col 0 count)
2161 (when (or (> (length (ses-call-printer printer)) 0)
2162 (> (length (ses-call-printer ses--default-printer)) 0))
2163 ;;Either column printer or global printer inserts some constant text
2164 ;;Reprint the new columns to insert that text.
2165 (dotimes (x ses--numrows)
2167 ;Always nil here - this is a blank column
2168 (1value (ses-print-cell-new-width x (+ y col))))))
2170 (ses-jump-safe ses--curcell))
2172 (defun ses-delete-column (count)
2173 "Delete the current column. With prefix, Deletes COUNT columns starting
2174 from the current one."
2177 (or (> count 0) (signal 'args-out-of-range nil))
2178 (let ((inhibit-quit t)
2179 (inhibit-read-only t)
2180 (rowcol (ses-sym-rowcol ses--curcell))
2182 col origrow has-skip)
2183 (setq origrow (car rowcol)
2185 count (min count (- ses--numcols col)))
2186 (if (= count ses--numcols)
2187 (error "Can't delete all columns!"))
2188 ;;Determine width of column(s) being deleted
2190 (setq width (+ width (ses-col-width (+ col x)) 1)))
2192 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2193 (ses-adjust-print-width col (- width))
2194 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2195 ;;Delete lines from cell data area
2196 (ses-goto-data row col)
2197 (ses-delete-line count)
2198 ;;Delete cells. Check if deletion area begins or ends with a skip.
2199 (if (or (eq (ses-cell-value row col) '*skip*)
2200 (and (< col ses--numcols)
2201 (eq (ses-cell-value row (+ col count)) '*skip*)))
2203 (ses-aset-with-undo ses--cells row
2204 (ses-vector-delete (aref ses--cells row) col count)))
2206 (ses-set-parameter 'ses--col-widths
2207 (ses-vector-delete ses--col-widths col count))
2208 (ses-set-parameter 'ses--col-printers
2209 (ses-vector-delete ses--col-printers col count))
2210 (ses-reset-header-string)
2211 ;;Relocate variables and formulas
2212 (ses-relocate-all 0 col 0 (- count))
2213 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2214 ses--numcols (+ ses--numcols count -1))
2218 (if (>= col ses--numcols)
2219 (setq col (1- col)))
2220 (ses-goto-print origrow col)))
2222 (defun ses-forward-or-insert (&optional count)
2223 "Move to next cell in row, or inserts a new cell if already in last one, or
2224 inserts a new row if at bottom of print area. Repeat COUNT times."
2226 (ses-check-curcell 'end)
2227 (setq deactivate-mark t) ;Doesn't combine well with ranges
2230 (if (not ses--curcell)
2231 (progn ;At bottom of print area
2232 (barf-if-buffer-read-only)
2234 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2236 (char-before (next-single-property-change (point)
2238 ;;We're already in last nonskipped cell on line. Need to create a
2240 (barf-if-buffer-read-only)
2241 (ses-insert-column (- count x)
2244 (ses-col-printer col)))))
2247 (defun ses-append-row-jump-first-column ()
2248 "Insert a new row after current one and jumps to its first column."
2252 (beginning-of-line 2)
2256 (defun ses-set-column-width (col newwidth)
2257 "Set the width of the current column."
2259 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2260 (barf-if-buffer-read-only)
2262 (if current-prefix-arg
2263 (prefix-numeric-value current-prefix-arg)
2264 (read-from-minibuffer (format "Column %s width [currently %d]: "
2265 (ses-column-letter col)
2266 (ses-col-width col))
2267 nil ;No initial contents
2268 nil ;No override keymap
2269 t ;Convert to Lisp object
2272 (ses-col-width col))))))) ;Default value
2274 (error "Invalid column width"))
2276 (ses-reset-header-string)
2278 (let ((inhibit-quit t))
2279 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2280 (ses-set-parameter 'ses--col-widths newwidth col))
2281 (dotimes (row ses--numrows)
2282 (ses-print-cell-new-width row col))))
2285 ;;----------------------------------------------------------------------------
2286 ;; Cut and paste, import and export
2287 ;;----------------------------------------------------------------------------
2289 (defadvice copy-region-as-kill (around ses-copy-region-as-kill
2290 activate preactivate)
2291 "It doesn't make sense to copy read-only or intangible attributes into the
2292 kill ring. It probably doesn't make sense to copy keymap properties.
2293 We'll assume copying front-sticky properties doesn't make sense, either.
2295 This advice also includes some SES-specific code because otherwise it's too
2296 hard to override how mouse-1 works."
2301 (if (not (and (eq major-mode 'ses-mode)
2302 (eq (get-text-property beg 'read-only) 'ses)
2303 (eq (get-text-property (1- end) 'read-only) 'ses)))
2304 ad-do-it ;Normal copy-region-as-kill
2305 (kill-new (ses-copy-region beg end))
2306 (if transient-mark-mode
2307 (setq deactivate-mark t))
2310 (defun ses-copy-region (beg end)
2311 "Treat the region as rectangular. Convert the intangible attributes to
2312 SES attributes recording the contents of the cell as of the time of copying."
2313 (let* ((inhibit-point-motion-hooks t)
2314 (x (mapconcat 'ses-copy-region-helper
2315 (extract-rectangle beg (1- end)) "\n")))
2316 (remove-text-properties 0 (length x)
2324 (defun ses-copy-region-helper (line)
2325 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2326 external form by attaching to each print cell a 'ses attribute that records
2327 the corresponding data cell."
2328 (or (> (length line) 1)
2329 (error "Empty range"))
2330 (let ((inhibit-read-only t)
2332 mycell next sym rowcol)
2334 (setq sym (get-text-property pos 'intangible line)
2335 next (next-single-property-change pos 'intangible line)
2336 rowcol (ses-sym-rowcol sym)
2337 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2338 (put-text-property pos (or next (length line))
2340 (list (ses-cell-symbol mycell)
2341 (ses-cell-formula mycell)
2342 (ses-cell-printer mycell))
2347 (defun ses-kill-override (beg end)
2348 "Generic override for any commands that kill text. We clear the killed
2349 cells instead of deleting them."
2351 (ses-check-curcell 'needrange)
2352 ;;For some reason, the text-read-only error is not caught by
2353 ;;`delete-region', so we have to use subterfuge.
2354 (let ((buffer-read-only t))
2355 (1value (condition-case x
2356 (noreturn (funcall (lookup-key (current-global-map)
2357 (this-command-keys))
2359 (buffer-read-only nil)))) ;The expected error
2360 ;;Because the buffer was marked read-only, the kill command turned itself
2361 ;;into a copy. Now we clear the cells or signal the error. First we
2362 ;;check whether the buffer really is read-only.
2363 (barf-if-buffer-read-only)
2365 (ses-dorange ses--curcell
2366 (ses-clear-cell row col))
2367 (ses-jump (car ses--curcell)))
2369 (defadvice yank (around ses-yank activate preactivate)
2370 "In SES mode, the yanked text is inserted as cells.
2372 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2373 SES buffer), the formulas and print functions are restored for the cells. If
2374 the text contains tabs, this is an insertion of tab-separated formulas.
2375 Otherwise the text is inserted as the formula for the current cell.
2377 When inserting cells, the formulas are usually relocated to keep the same
2378 relative references to neighboring cells. This is best if the formulas
2379 generally refer to other cells within the yanked text. You can use the C-u
2380 prefix to specify insertion without relocation, which is best when the
2381 formulas refer to cells outsite the yanked text.
2383 When inserting formulas, the text is treated as a string constant if it doesn't
2384 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2385 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2387 (if (not (and (eq major-mode 'ses-mode)
2388 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2389 ad-do-it ;Normal non-SES yank
2390 (ses-check-curcell 'end)
2392 (let ((text (current-kill (cond
2396 (or (ses-yank-cells text arg)
2397 (ses-yank-tsf text arg)
2398 (ses-yank-one (ses-yank-resize 1 1)
2401 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2402 ;;Just one cell - delete final tab or newline
2406 (exchange-point-and-mark))))
2408 (defun ses-yank-pop (arg)
2409 "Replace just-yanked stretch of killed text with a different stretch.
2410 This command is allowed only immediately after a `yank' or a `yank-pop', when
2411 the region contains a stretch of reinserted previously-killed text. We
2412 replace it with a different stretch of killed text.
2413 Unlike standard `yank-pop', this function uses `undo' to delete the
2414 previous insertion."
2416 (or (eq last-command 'yank)
2417 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2419 (noreturn (error "Previous command was not a yank")))
2422 (yank (1+ (or arg 1)))
2423 (setq this-command 'yank))
2425 (defun ses-yank-cells (text arg)
2426 "If the TEXT has a proper set of 'ses attributes, inserts the text as
2427 cells, else return nil. The cells are reprinted--the supplied text is
2428 ignored because the column widths, default printer, etc. at yank time might
2429 be different from those at kill-time. ARG is a list to indicate that
2430 formulas are to be inserted without relocation."
2431 (let ((first (get-text-property 0 'ses text))
2432 (last (get-text-property (1- (length text)) 'ses text)))
2433 (when (and first last) ;;Otherwise not proper set of attributes
2434 (setq first (ses-sym-rowcol (car first))
2435 last (ses-sym-rowcol (car last)))
2436 (let* ((needrows (- (car last) (car first) -1))
2437 (needcols (- (cdr last) (cdr first) -1))
2438 (rowcol (ses-yank-resize needrows needcols))
2439 (rowincr (- (car rowcol) (car first)))
2440 (colincr (- (cdr rowcol) (cdr first)))
2443 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2444 (setq myrow (+ row (car rowcol)))
2445 (dotimes (col needcols)
2446 (setq mycol (+ col (cdr rowcol))
2447 last (get-text-property pos 'ses text)
2448 pos (next-single-property-change pos 'ses text)
2449 x (ses-sym-rowcol (car last)))
2451 ;;Newline - all remaining cells on row are skipped
2452 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2453 last (list nil nil nil)
2455 (if (/= (car x) (- myrow rowincr))
2456 (error "Cell row error"))
2457 (if (< (- mycol colincr) (cdr x))
2458 ;;Some columns were skipped
2459 (let ((oldcol mycol))
2460 (while (< (- mycol colincr) (cdr x))
2461 (ses-clear-cell myrow mycol)
2464 (ses-print-cell myrow (1- oldcol)))) ;;This inserts *skip*
2465 (when (car last) ;Skip this for *skip* cells
2466 (setq x (nth 2 last))
2467 (unless (equal x (ses-cell-printer myrow mycol))
2470 (eq (car-safe x) 'ses-safe-printer)
2471 (setq x `(ses-safe-printer ,x)))
2472 (ses-set-cell myrow mycol 'printer x))
2473 (setq x (cadr last))
2475 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2477 (eq (car-safe x) 'ses-safe-formula)
2478 (setq x `(ses-safe-formula ,x)))
2479 (ses-cell-set-formula myrow mycol x)))
2481 (if (get-text-property pos 'ses text)
2482 (error "Missing newline between rows"))
2483 (setq pos (next-single-property-change pos 'ses text))))
2486 (defun ses-yank-one (rowcol text from to arg)
2487 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2488 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2489 (let ((val (condition-case nil
2490 (read-from-string text from to)
2491 (error (cons nil from)))))
2493 ((< (cdr val) (or to (length text)))
2494 ;;Invalid sexp - leave it as a string
2495 (setq val (substring text from to)))
2496 ((and (car val) (symbolp (car val)))
2498 (setq val (list 'quote (car val))) ;Keep symbol
2499 (setq val (substring text from to)))) ;Treat symbol as text
2501 (setq val (car val))))
2502 (let ((row (car rowcol))
2505 (setq val `(ses-safe-formula ,val)))
2506 (ses-cell-set-formula row col val))))
2508 (defun ses-yank-tsf (text arg)
2509 "If TEXT contains tabs and/or newlines, treats the tabs as
2510 column-separators and the newlines as row-separators and inserts the text as
2511 cell formulas--else return nil. Treat plain symbols as strings unless ARG
2512 is a list. Ignore a final newline."
2513 (if (or (not (string-match "[\t\n]" text))
2514 (= (match-end 0) (length text)))
2517 (if (/= (aref text (1- (length text))) ?\n)
2518 (setq text (concat text "\n")))
2524 ;;Find all the tabs and newlines
2525 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
2527 (setq cols (1+ cols))
2528 (when (eq (aref text pos) ?\n)
2530 (setq needcols cols)
2531 (or (= needcols cols)
2532 (error "Inconsistent row lengths")))
2534 needrows (1+ needrows))))
2535 ;;Insert the formulas
2536 (setq rowcol (ses-yank-resize needrows needcols))
2537 (dotimes (row needrows)
2538 (dotimes (col needcols)
2539 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
2540 (+ (cdr rowcol) needcols (- col) -1))
2541 text (1+ (cadr spots)) (car spots) arg)
2542 (setq spots (cdr spots))))
2543 (ses-goto-print (+ (car rowcol) needrows -1)
2544 (+ (cdr rowcol) needcols -1))
2547 (defun ses-yank-resize (needrows needcols)
2548 "If this yank will require inserting rows and/or columns, asks for
2549 confirmation and then inserts them. Result is (row,col) for top left of yank
2550 spot, or error signal if user requests cancel."
2552 (let ((rowcol (if ses--curcell
2553 (ses-sym-rowcol ses--curcell)
2554 (cons ses--numrows 0)))
2556 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
2557 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
2558 rowbool (> needrows 0)
2559 colbool (> needcols 0))
2560 (when (or rowbool colbool)
2561 ;;Need to insert. Get confirm
2562 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
2563 (if rowbool (format "%d rows" needrows) "")
2564 (if (and rowbool colbool) " and " "")
2565 (if colbool (format "%d columns" needcols) "")))
2566 (error "Cancelled"))
2570 (ses-goto-print ses--numrows 0)
2571 (ses-insert-row needrows))))
2573 (ses-insert-column needcols
2575 (ses-col-width (1- ses--numcols))
2576 (ses-col-printer (1- ses--numcols)))))
2579 (defun ses-export-tsv (beg end)
2580 "Export values from the current range, with tabs between columns and
2581 newlines between rows. Result is placed in kill ring."
2583 (ses-export-tab nil))
2585 (defun ses-export-tsf (beg end)
2586 "Export formulas from the current range, with tabs between columns and
2587 newlines between rows. Result is placed in kill ring."
2591 (defun ses-export-tab (want-formulas)
2592 "Export the current range with tabs between columns and newlines between
2593 rows. Result is placed in kill ring. The export is values unless
2594 WANT-FORMULAS is non-nil. Newlines and tabs in the export text are escaped."
2595 (ses-check-curcell 'needrange)
2596 (let ((print-escape-newlines t)
2598 (ses-dorange ses--curcell
2599 (setq item (if want-formulas
2600 (ses-cell-formula row col)
2601 (ses-cell-value row col)))
2602 (if (eq (car-safe item) 'ses-safe-formula)
2603 ;;Hide our deferred safety-check marker
2604 (setq item (cadr item)))
2605 (if (or (not item) (eq item '*skip*))
2607 (when (eq (car-safe item) 'quote)
2609 (setq item (cadr item)))
2610 (setq item (prin1-to-string item t))
2611 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
2617 (push "\n" result))))
2618 (setq result (apply 'concat (nreverse result)))
2622 ;;----------------------------------------------------------------------------
2623 ;; Other user commands
2624 ;;----------------------------------------------------------------------------
2626 (defun ses-unset-header-row ()
2627 "Select the default header row."
2629 (ses-set-header-row 0))
2631 (defun ses-set-header-row (row)
2632 "Set the ROW to display in the header-line.
2633 With a numerical prefix arg, use that row.
2634 With no prefix arg, use the current row.
2635 With a \\[universal-argument] prefix arg, prompt the user.
2636 The top row is row 1. Selecting row 0 displays the default header row."
2638 (list (if (numberp current-prefix-arg) current-prefix-arg
2639 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
2640 (if current-prefix-arg
2641 (read-number "Header row: " currow)
2643 (if (or (< row 0) (> row ses--numrows))
2644 (error "Invalid header-row"))
2646 (let ((oldval ses--header-row))
2647 (let (buffer-undo-list)
2648 (ses-set-parameter 'ses--header-row row))
2649 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
2650 (ses-reset-header-string))
2652 (defun ses-mark-row ()
2653 "Marks the entirety of current row as a range."
2655 (ses-check-curcell 'range)
2656 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
2658 (ses-goto-print (1+ row) 0)
2659 (push-mark (point) nil t)
2660 (ses-goto-print row 0)))
2662 (defun ses-mark-column ()
2663 "Marks the entirety of current column as a range."
2665 (ses-check-curcell 'range)
2666 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
2669 (ses-goto-print (1- ses--numrows) col)
2671 (push-mark (point) nil t)
2672 (while (eq '*skip* (ses-cell-value row col))
2673 ;;Skip over initial cells in column that can't be selected
2674 (setq row (1+ row)))
2675 (ses-goto-print row col)))
2677 (defun ses-end-of-line ()
2678 "Move point to last cell on line."
2680 (ses-check-curcell 'end 'range)
2681 (when ses--curcell ;Otherwise we're at the bottom row, which is empty anyway
2682 (let ((col (1- ses--numcols))
2684 (if (symbolp ses--curcell)
2686 (setq row (car (ses-sym-rowcol ses--curcell)))
2687 ;;Range - use whichever end of the range the point is at
2688 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
2690 (cdr ses--curcell))))
2691 ;;If range already includes the last cell in a row, point is actually
2692 ;;in the following row
2693 (if (<= (cdr rowcol) (1- col))
2694 (setq row (car rowcol))
2695 (setq row (1+ (car rowcol)))
2696 (if (= row ses--numrows)
2697 ;;Already at end - can't go anywhere
2699 (when (< row ses--numrows) ;Otherwise it's a range that includes last cell
2700 (while (eq (ses-cell-value row col) '*skip*)
2701 ;;Back to beginning of multi-column cell
2702 (setq col (1- col)))
2703 (ses-goto-print row col)))))
2705 (defun ses-renarrow-buffer ()
2706 "Narrow the buffer so only the print area is visible. Use after \\[widen]."
2708 (setq ses--deferred-narrow t))
2710 (defun ses-sort-column (sorter &optional reverse)
2711 "Sorts the range by a specified column. With prefix, sorts in
2713 (interactive "*sSort column: \nP")
2714 (ses-check-curcell 'needrange)
2715 (let ((min (ses-sym-rowcol (car ses--curcell)))
2716 (max (ses-sym-rowcol (cdr ses--curcell))))
2717 (let ((minrow (car min))
2722 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
2723 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
2724 (error "Invalid sort column"))
2725 ;;Get key columns and sort them
2726 (dotimes (x (- maxrow minrow -1))
2727 (ses-goto-print (+ minrow x) sorter)
2728 (setq end (next-single-property-change (point) 'intangible))
2729 (push (cons (buffer-substring-no-properties (point) end)
2732 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
2733 ;;Extract the lines in reverse sorted order
2735 (setq keys (nreverse keys)))
2737 (ses-goto-print (cdr x) (1+ maxcol))
2739 (ses-goto-print (cdr x) mincol)
2740 (push (ses-copy-region (point) end) extracts))
2742 ;;Paste the lines sequentially
2743 (dotimes (x (- maxrow minrow -1))
2744 (ses-goto-print (+ minrow x) mincol)
2746 (ses-yank-cells (pop extracts) nil)))))
2748 (defun ses-sort-column-click (event reverse)
2749 "Mouse version of `ses-sort-column'."
2750 (interactive "*e\nP")
2751 (setq event (event-end event))
2752 (select-window (posn-window event))
2753 (setq event (car (posn-col-row event))) ;Click column
2755 (while (and (< col ses--numcols) (> event (ses-col-width col)))
2756 (setq event (- event (ses-col-width col) 1)
2758 (if (>= col ses--numcols)
2760 (ses-sort-column (ses-column-letter col) reverse))))
2762 (defun ses-insert-range ()
2763 "Inserts into minibuffer the list of cells currently highlighted in the
2767 (with-current-buffer (window-buffer minibuffer-scroll-window)
2768 (ses-command-hook) ;For ses-coverage
2769 (ses-check-curcell 'needrange)
2770 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
2771 ,(cdr ses--curcell))))))
2772 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
2774 (defun ses-insert-ses-range ()
2775 "Inserts \"(ses-range x y)\" in the minibuffer to represent the currently
2776 highlighted range in the spreadsheet."
2779 (with-current-buffer (window-buffer minibuffer-scroll-window)
2780 (ses-command-hook) ;For ses-coverage
2781 (ses-check-curcell 'needrange)
2782 (setq x (format "(ses-range %S %S)"
2784 (cdr ses--curcell))))
2787 (defun ses-insert-range-click (event)
2788 "Mouse version of `ses-insert-range'."
2790 (mouse-set-point event)
2793 (defun ses-insert-ses-range-click (event)
2794 "Mouse version of `ses-insert-ses-range'."
2796 (mouse-set-point event)
2797 (ses-insert-ses-range))
2800 ;;----------------------------------------------------------------------------
2801 ;; Checking formulas for safety
2802 ;;----------------------------------------------------------------------------
2804 (defun ses-safe-printer (printer)
2805 "Returns PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
2806 (if (or (stringp printer)
2807 (stringp (car-safe printer))
2809 (ses-warn-unsafe printer 'unsafep-function))
2813 (defun ses-safe-formula (formula)
2814 "Returns FORMULA if safe, or the substitute formula *unsafe* otherwise."
2815 (if (ses-warn-unsafe formula 'unsafep)
2817 `(ses-unsafe ',formula)))
2819 (defun ses-warn-unsafe (formula checker)
2820 "Applies CHECKER to FORMULA. If result is non-nil, asks user for
2821 confirmation about FORMULA, which might be unsafe. Returns t if formula
2822 is safe or user allows execution anyway. Always returns t if
2823 `safe-functions' is t."
2824 (if (eq safe-functions t)
2826 (setq checker (funcall checker formula))
2829 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
2830 formula checker)))))
2833 ;;----------------------------------------------------------------------------
2834 ;; Standard formulas
2835 ;;----------------------------------------------------------------------------
2837 (defmacro ses-range (from to)
2838 "Expands to a list of cell-symbols for the range. The range automatically
2839 expands to include any new row or column inserted into its middle. The SES
2840 library code specifically looks for the symbol `ses-range', so don't create an
2841 alias for this macro!"
2843 (ses-dorange (cons from to)
2844 (push (ses-cell-symbol row col) result))
2845 (cons 'list result)))
2847 (defun ses-delete-blanks (&rest args)
2848 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
2851 (unless (memq cur '(nil *skip*))
2855 (defun ses+ (&rest args)
2856 "Compute the sum of the arguments, ignoring blanks."
2857 (apply '+ (apply 'ses-delete-blanks args)))
2859 (defun ses-average (list)
2860 "Computes the sum of the numbers in LIST, divided by their length. Blanks
2861 are ignored. Result is always floating-point, even if all args are integers."
2862 (setq list (apply 'ses-delete-blanks list))
2863 (/ (float (apply '+ list)) (length list)))
2865 (defmacro ses-select (fromrange test torange)
2866 "Select cells in FROMRANGE that are `equal' to TEST. For each match, return
2867 the corresponding cell from TORANGE. The ranges are macroexpanded but not
2868 evaluated so they should be either (ses-range BEG END) or (list ...). The
2870 (setq fromrange (cdr (macroexpand fromrange))
2871 torange (cdr (macroexpand torange))
2873 (or (= (length fromrange) (length torange))
2874 (error "ses-select: Ranges not same length"))
2876 (dolist (x fromrange)
2877 (if (equal test (symbol-value x))
2878 (push (car torange) result))
2879 (setq torange (cdr torange)))
2880 (cons 'list result)))
2882 ;;All standard formulas are safe
2883 (dolist (x '(ses-range ses-delete-blanks ses+ ses-average ses-select))
2884 (put x 'side-effect-free t))
2887 ;;----------------------------------------------------------------------------
2888 ;; Standard print functions
2889 ;;----------------------------------------------------------------------------
2891 ;;These functions use the variables 'row' and 'col' that are
2892 ;;dynamically bound by ses-print-cell. We define these varables at
2893 ;;compile-time to make the compiler happy.
2895 (dolist (x '(row col))
2896 (make-local-variable x)
2899 (defun ses-center (value &optional span fill)
2900 "Print VALUE, centered within column. FILL is the fill character for
2901 centering (default = space). SPAN indicates how many additional rightward
2902 columns to include in width (default = 0)."
2903 (let ((printer (or (ses-col-printer col) ses--default-printer))
2904 (width (ses-col-width col))
2906 (or fill (setq fill ?\s))
2907 (or span (setq span 0))
2908 (setq value (ses-call-printer printer value))
2910 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
2911 (setq width (- width (length value)))
2913 value ;Too large for field, anyway
2914 (setq half (make-string (/ width 2) fill))
2915 (concat half value half
2916 (if (> (% width 2) 0) (char-to-string fill))))))
2918 (defun ses-center-span (value &optional fill)
2919 "Print VALUE, centered within the span that starts in the current column
2920 and continues until the next nonblank column. FILL specifies the fill
2921 character (default = space)."
2922 (let ((end (1+ col)))
2923 (while (and (< end ses--numcols)
2924 (memq (ses-cell-value row end) '(nil *skip*)))
2925 (setq end (1+ end)))
2926 (ses-center value (- end col 1) fill)))
2928 (defun ses-dashfill (value &optional span)
2929 "Print VALUE centered using dashes. SPAN indicates how many rightward
2930 columns to include in width (default = 0)."
2931 (ses-center value span ?-))
2933 (defun ses-dashfill-span (value)
2934 "Print VALUE, centered using dashes within the span that starts in the
2935 current column and continues until the next nonblank column."
2936 (ses-center-span value ?-))
2938 (defun ses-tildefill-span (value)
2939 "Print VALUE, centered using tildes within the span that starts in the
2940 current column and continues until the next nonblank column."
2941 (ses-center-span value ?~))
2943 (defun ses-unsafe (value)
2944 "Substitute for an unsafe formula or printer"
2945 (error "Unsafe formula or printer"))
2947 ;;All standard printers are safe, including ses-unsafe!
2948 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
2949 (put x 'side-effect-free t))
2953 ;; arch-tag: 88c1ccf0-4293-4824-8c5d-0757b52217f3
2954 ;;; ses.el ends here