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) (< 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)))
943 (defun ses-goto-data (def &optional col)
944 "Move point to data area for (DEF,COL). If DEF is a row
945 number, COL is the column number for a data cell -- otherwise DEF
946 is one of the symbols ses--col-widths, ses--col-printers,
947 ses--default-printer, ses--numrows, or ses--numcols."
949 (setq ses--deferred-narrow t))
951 (let ((inhibit-point-motion-hooks t)) ;In case intangible attrs are wrong
952 (goto-char (point-min))
955 (forward-line (+ ses--numrows 2 (* def (1+ ses--numcols)) col))
956 ;;Convert def-symbol to offset
957 (setq def (plist-get ses-paramlines-plist def))
958 (or def (signal 'args-out-of-range nil))
959 (forward-line (+ (* ses--numrows (+ ses--numcols 2)) def)))))
961 (defun ses-set-parameter (def value &optional elem)
962 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
963 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
964 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
966 ;;We call ses-goto-data early, using the old values of numrows and
967 ;;numcols in case one of them is being changed.
970 (ses-aset-with-undo (symbol-value def) elem value)
971 (ses-set-with-undo def value))
972 (let ((inhibit-read-only t)
973 (fmt (plist-get '(ses--col-widths "(ses-column-widths %S)"
974 ses--col-printers "(ses-column-printers %S)"
975 ses--default-printer "(ses-default-printer %S)"
976 ses--header-row "(ses-header-row %S)"
977 ses--file-format " %S ;SES file-format"
978 ses--numrows " %S ;numrows"
979 ses--numcols " %S ;numcols")
981 (delete-region (point) (line-end-position))
982 (insert (format fmt (symbol-value def))))))
984 (defun ses-write-cells ()
985 "Write cells in `ses--deferred-write' from local variables to data area.
986 Newlines in the data are escaped."
987 (let* ((inhibit-read-only t)
988 (print-escape-newlines t)
989 rowcol row col cell sym formula printer text)
990 (setq ses-start-time (float-time))
991 (with-temp-message " "
993 (while ses--deferred-write
994 (ses-time-check "Writing... (%d cells left)"
995 '(length ses--deferred-write))
996 (setq rowcol (pop ses--deferred-write)
999 cell (ses-get-cell row col)
1000 sym (ses-cell-symbol cell)
1001 formula (ses-cell-formula cell)
1002 printer (ses-cell-printer cell))
1003 (if (eq (car-safe formula) 'ses-safe-formula)
1004 (setq formula (cadr formula)))
1005 (if (eq (car-safe printer) 'ses-safe-printer)
1006 (setq printer (cadr printer)))
1007 ;;This is noticably faster than (format "%S %S %S %S %S")
1008 (setq text (concat "(ses-cell "
1011 (prin1-to-string (symbol-value sym))
1013 (prin1-to-string formula)
1015 (prin1-to-string printer)
1017 (if (atom (ses-cell-references cell))
1020 (mapconcat 'symbol-name
1021 (ses-cell-references cell)
1025 (ses-goto-data row col)
1026 (delete-region (point) (line-end-position))
1031 ;;----------------------------------------------------------------------------
1032 ;; Formula relocation
1033 ;;----------------------------------------------------------------------------
1035 (defun ses-formula-references (formula &optional result-so-far)
1036 "Produce a list of symbols for cells that this formula's value
1037 refers to. For recursive calls, RESULT-SO-FAR is the list being constructed,
1038 or t to get a wrong-type-argument error when the first reference is found."
1040 (if (ses-sym-rowcol formula)
1041 ;;Entire formula is one symbol
1042 (add-to-list 'result-so-far formula)
1043 ) ;;Ignore other atoms
1044 (dolist (cur formula)
1046 ((ses-sym-rowcol cur)
1047 ;;Save this reference
1048 (add-to-list 'result-so-far cur))
1049 ((eq (car-safe cur) 'ses-range)
1050 ;;All symbols in range are referenced
1051 (dolist (x (cdr (macroexpand cur)))
1052 (add-to-list 'result-so-far x)))
1053 ((and (consp cur) (not (eq (car cur) 'quote)))
1054 ;;Recursive call for subformulas
1055 (setq result-so-far (ses-formula-references cur result-so-far)))
1057 ;;Ignore other stuff
1061 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1062 "Produce a copy of FORMULA where all symbols that refer to cells in row
1063 STARTROW or above and col STARTCOL or above are altered by adding ROWINCR
1064 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1065 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1067 If ROWINCR or COLINCR is negative, references to cells being deleted are
1069 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1071 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1072 (let (rowcol result)
1073 (if (or (atom formula) (eq (car formula) 'quote))
1074 (if (setq rowcol (ses-sym-rowcol formula))
1075 (ses-relocate-symbol formula rowcol
1076 startrow startcol rowincr colincr)
1077 formula) ;Pass through as-is
1078 (dolist (cur formula)
1079 (setq rowcol (ses-sym-rowcol cur))
1082 (setq cur (ses-relocate-symbol cur rowcol
1083 startrow startcol rowincr colincr))
1086 ;;Reference to a deleted cell. Set a flag in ses-relocate-return.
1087 ;;don't change the flag if it's already 'range, since range
1089 (unless ses-relocate-return
1090 (setq ses-relocate-return 'delete))))
1091 ((eq (car-safe cur) 'ses-range)
1092 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1095 ((or (atom cur) (eq (car cur) 'quote))
1096 ;;Constants pass through unchanged
1099 ;;Recursively copy and alter subformulas
1100 (push (ses-relocate-formula cur startrow startcol
1103 (nreverse result))))
1105 (defun ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1106 "Relocate one symbol SYM, whichs corresponds to ROWCOL (a cons of ROW and
1107 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1108 by (ROWINCR,COLINCR)."
1109 (let ((row (car rowcol))
1111 (if (or (< row startrow) (< col startcol))
1113 (setq row (+ row rowincr)
1114 col (+ col colincr))
1115 (if (and (>= row startrow) (>= col startcol)
1116 (< row ses--numrows) (< col ses--numcols))
1117 ;;Relocate this variable
1118 (ses-create-cell-symbol row col)
1119 ;;Delete reference to a deleted cell
1122 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1123 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1124 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1125 new range, or nil if the entire range is deleted. If new rows are being added
1126 just beyond the end of a row range, or new columns just beyond a column range,
1127 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1128 if the range was altered."
1129 (let* ((minorig (cadr range))
1130 (minrowcol (ses-sym-rowcol minorig))
1131 (min (ses-relocate-symbol minorig minrowcol
1134 (maxorig (nth 2 range))
1135 (maxrowcol (ses-sym-rowcol maxorig))
1136 (max (ses-relocate-symbol maxorig maxrowcol
1141 ((and (not min) (not max))
1142 (setq range nil)) ;;The entire range is deleted
1144 ;;Inserting or deleting rows
1147 ;;Chopped off beginning of range
1148 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1149 ses-relocate-return 'range))
1152 ;;Trying to insert a nonexistent row
1153 (setq max (ses-create-cell-symbol (1- ses--numrows)
1155 ;;End of range is being deleted
1156 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1157 ses-relocate-return 'range))
1159 (= (car maxrowcol) (1- startrow))
1160 (= (cdr minrowcol) (cdr maxrowcol))
1161 ;;Insert after ending row of vertical range - include it
1162 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1163 (cdr maxrowcol))))))
1165 ;;Inserting or deleting columns
1168 ;;Chopped off beginning of range
1169 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1170 ses-relocate-return 'range))
1173 ;;Trying to insert a nonexistent column
1174 (setq max (ses-create-cell-symbol (car maxrowcol)
1176 ;;End of range is being deleted
1177 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1178 ses-relocate-return 'range))
1180 (= (cdr maxrowcol) (1- startcol))
1181 (= (car minrowcol) (car maxrowcol))
1182 ;;Insert after ending column of horizontal range - include it
1183 (setq max (ses-create-cell-symbol (car maxrowcol)
1184 (+ startcol colincr -1)))))))
1186 (if (/= (- (funcall field maxrowcol)
1187 (funcall field minrowcol))
1188 (- (funcall field (ses-sym-rowcol max))
1189 (funcall field (ses-sym-rowcol min))))
1190 ;;This range has changed size
1191 (setq ses-relocate-return 'range))
1192 (list 'ses-range min max))))
1194 (defun ses-relocate-all (minrow mincol rowincr colincr)
1195 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1196 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1199 (let (mycell newval)
1200 (dotimes-with-progress-reporter
1201 (row ses--numrows) "Relocating formulas..."
1202 (dotimes (col ses--numcols)
1203 (setq ses-relocate-return nil
1204 mycell (ses-get-cell row col)
1205 newval (ses-relocate-formula (ses-cell-formula mycell)
1206 minrow mincol rowincr colincr))
1207 (ses-set-cell row col 'formula newval)
1208 (if (eq ses-relocate-return 'range)
1209 ;;This cell contains a (ses-range X Y) where a cell has been
1210 ;;inserted or deleted in the middle of the range.
1211 (push (cons row col) reform))
1212 (if ses-relocate-return
1213 ;;This cell referred to a cell that's been deleted or is no
1214 ;;longer part of the range. We can't fix that now because
1215 ;;reference lists cells have been partially updated.
1216 (add-to-list 'ses--deferred-recalc
1217 (ses-create-cell-symbol row col)))
1218 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1219 minrow mincol rowincr colincr))
1220 (ses-set-cell row col 'references newval)
1221 (and (>= row minrow) (>= col mincol)
1222 (ses-set-cell row col 'symbol
1223 (ses-create-cell-symbol row col))))))
1224 ;;Relocate the cell values
1225 (let (oldval myrow mycol xrow xcol)
1227 ((and (<= rowincr 0) (<= colincr 0))
1228 ;;Deletion of rows and/or columns
1229 (dotimes-with-progress-reporter
1230 (row (- ses--numrows minrow)) "Relocating variables..."
1231 (setq myrow (+ row minrow))
1232 (dotimes (col (- ses--numcols mincol))
1233 (setq mycol (+ col mincol)
1234 xrow (- myrow rowincr)
1235 xcol (- mycol colincr))
1236 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1237 (setq oldval (ses-cell-value xrow xcol))
1238 ;;Cell is off the end of the array
1239 (setq oldval (symbol-value (ses-create-cell-symbol xrow xcol))))
1240 (ses-set-cell myrow mycol 'value oldval))))
1241 ((and (wholenump rowincr) (wholenump colincr))
1242 ;;Insertion of rows and/or columns. Run the loop backwards.
1243 (let ((disty (1- ses--numrows))
1244 (distx (1- ses--numcols))
1246 (dotimes-with-progress-reporter
1247 (row (- ses--numrows minrow)) "Relocating variables..."
1248 (setq myrow (- disty row))
1249 (dotimes (col (- ses--numcols mincol))
1250 (setq mycol (- distx col)
1251 xrow (- myrow rowincr)
1252 xcol (- mycol colincr))
1253 (if (or (< xrow minrow) (< xcol mincol))
1254 ;;Newly-inserted value
1256 ;;Transfer old value
1257 (setq oldval (ses-cell-value xrow xcol)))
1258 (ses-set-cell myrow mycol 'value oldval)))
1259 t)) ;Make testcover happy by returning non-nil here
1261 (error "ROWINCR and COLINCR must have the same sign"))))
1262 ;;Reconstruct reference lists for cells that contain ses-ranges that
1263 ;;have changed size.
1265 (message "Fixing ses-ranges...")
1267 (setq ses-start-time (float-time))
1269 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1270 (setq row (caar reform)
1272 reform (cdr reform))
1273 (ses-cell-set-formula row col (ses-cell-formula row col))))
1277 ;;----------------------------------------------------------------------------
1279 ;;----------------------------------------------------------------------------
1281 ;; This should be unnecessary, because the feature is now built in.
1283 (defadvice undo-more (around ses-undo-more activate preactivate)
1284 "For SES mode, allow undo outside of narrowed buffer range."
1285 (if (not (eq major-mode 'ses-mode))
1287 ;;Here is some extra code for SES mode.
1288 (setq ses--deferred-narrow
1289 (or ses--deferred-narrow (ses-narrowed-p)))
1294 ;;Restore narrow if appropriate
1296 (signal (car x) (cdr x))))))
1298 (defun ses-begin-change ()
1299 "For undo, remember point before we start changing hidden stuff."
1300 (let ((inhibit-read-only t))
1301 (insert-and-inherit "X")
1302 (delete-region (1- (point)) (point))))
1304 (defun ses-set-with-undo (sym newval)
1305 "Like set, but undoable. Result is t if value has changed."
1306 ;;We avoid adding redundant entries to the undo list, but this is
1307 ;;unavoidable for strings because equal ignores text properties and there's
1308 ;;no easy way to get the whole property list to see if it's different!
1309 (unless (and (boundp sym)
1310 (equal (symbol-value sym) newval)
1311 (not (stringp newval)))
1312 (push (if (boundp sym)
1313 `(apply ses-set-with-undo ,sym ,(symbol-value sym))
1314 `(apply ses-unset-with-undo ,sym))
1319 (defun ses-unset-with-undo (sym)
1320 "Set SYM to be unbound. This is undoable."
1321 (when (1value (boundp sym)) ;;Always bound, except after a programming error
1322 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
1325 (defun ses-aset-with-undo (array idx newval)
1326 "Like aset, but undoable. Result is t if element has changed"
1327 (unless (equal (aref array idx) newval)
1328 (push `(apply ses-aset-with-undo ,array ,idx ,(aref array idx)) buffer-undo-list)
1329 (aset array idx newval)
1333 ;;----------------------------------------------------------------------------
1334 ;; Startup for major mode
1335 ;;----------------------------------------------------------------------------
1338 "Parse the current buffer and sets up buffer-local variables. Does not
1339 execute cell formulas or print functions."
1341 ;;Read our global parameters, which should be a 3-element list
1342 (goto-char (point-max))
1343 (search-backward ";; Local Variables:\n" nil t)
1345 (let ((params (condition-case nil (read (current-buffer)) (error nil))))
1346 (or (and (= (safe-length params) 3)
1347 (numberp (car params))
1348 (numberp (cadr params))
1350 (numberp (nth 2 params))
1351 (> (nth 2 params) 0))
1352 (error "Invalid SES file"))
1353 (setq ses--file-format (car params)
1354 ses--numrows (cadr params)
1355 ses--numcols (nth 2 params))
1356 (when (= ses--file-format 1)
1357 (let (buffer-undo-list) ;This is not undoable
1358 (ses-goto-data 'ses--header-row)
1359 (insert "(ses-header-row 0)\n")
1360 (ses-set-parameter 'ses--file-format 2)
1361 (message "Upgrading from SES-1 file format")))
1362 (or (= ses--file-format 2)
1363 (error "This file needs a newer version of the SES library code"))
1364 (ses-create-cell-variable-range 0 (1- ses--numrows) 0 (1- ses--numcols))
1365 ;;Initialize cell array
1366 (setq ses--cells (make-vector ses--numrows nil))
1367 (dotimes (row ses--numrows)
1368 (aset ses--cells row (make-vector ses--numcols nil))))
1369 ;;Skip over print area, which we assume is correct
1370 (goto-char (point-min))
1371 (forward-line ses--numrows)
1372 (or (looking-at ses-print-data-boundary)
1373 (error "Missing marker between print and data areas"))
1374 (forward-char (length ses-print-data-boundary))
1375 ;;Initialize printer and symbol lists
1376 (mapc 'ses-printer-record ses-standard-printer-functions)
1377 (setq ses--symbolic-formulas nil)
1378 ;;Load cell definitions
1379 (dotimes (row ses--numrows)
1380 (dotimes (col ses--numcols)
1381 (let* ((x (read (current-buffer)))
1382 (rowcol (ses-sym-rowcol (car-safe (cdr-safe x)))))
1383 (or (and (looking-at "\n")
1384 (eq (car-safe x) 'ses-cell)
1385 (eq row (car rowcol))
1386 (eq col (cdr rowcol)))
1387 (error "Cell-def error"))
1389 (or (looking-at "\n\n")
1390 (error "Missing blank line between rows")))
1391 ;;Load global parameters
1392 (let ((widths (read (current-buffer)))
1393 (n1 (char-after (point)))
1394 (printers (read (current-buffer)))
1395 (n2 (char-after (point)))
1396 (def-printer (read (current-buffer)))
1397 (n3 (char-after (point)))
1398 (head-row (read (current-buffer)))
1399 (n4 (char-after (point))))
1400 (or (and (eq (car-safe widths) 'ses-column-widths)
1402 (eq (car-safe printers) 'ses-column-printers)
1404 (eq (car-safe def-printer) 'ses-default-printer)
1406 (eq (car-safe head-row) 'ses-header-row)
1408 (error "Invalid SES global parameters"))
1409 (1value (eval widths))
1410 (1value (eval def-printer))
1411 (1value (eval printers))
1412 (1value (eval head-row)))
1413 ;;Should be back at global-params
1415 (or (looking-at (replace-regexp-in-string "1" "[0-9]+"
1416 ses-initial-global-parameters))
1417 (error "Problem with column-defs or global-params"))
1418 ;;Check for overall newline count in definitions area
1420 (let ((start (point)))
1421 (ses-goto-data 'ses--numrows)
1422 (or (= (point) start)
1423 (error "Extraneous newlines someplace?"))))
1426 "Set up for display of only the printed cell values.
1428 Narrows the buffer to show only the print area. Gives it `read-only' and
1429 `intangible' properties. Sets up highlighting for current cell."
1431 (let ((end (point-min))
1432 (inhibit-read-only t)
1433 (was-modified (buffer-modified-p))
1435 (ses-goto-data 0 0) ;;Include marker between print-area and data-area
1436 (set-text-properties (point) (point-max) nil) ;Delete garbage props
1437 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1438 ;;The print area is read-only (except for our special commands) and uses a
1440 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1441 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1442 ;;For the beginning of the buffer, we want the read-only and keymap
1443 ;;attributes to be inherited from the first character
1444 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1445 ;;Create intangible properties, which also indicate which cell the text
1447 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1448 (dotimes (col ses--numcols)
1450 sym (ses-cell-symbol row col))
1451 ;;Include skipped cells following this one
1452 (while (and (< col (1- ses--numcols))
1453 (eq (ses-cell-value row (1+ col)) '*skip*))
1454 (setq end (+ end (ses-col-width col) 1)
1456 (setq end (+ end (ses-col-width col) 1))
1457 (put-text-property pos end 'intangible sym)))
1458 ;;Adding these properties did not actually alter the text
1459 (unless was-modified
1460 (restore-buffer-modified-p nil)
1461 (buffer-disable-undo)
1462 (buffer-enable-undo)))
1463 ;;Create the underlining overlay. It's impossible for (point) to be 2,
1464 ;;because column A must be at least 1 column wide.
1465 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1466 (overlay-put ses--curcell-overlay 'face 'underline))
1468 (defun ses-cleanup ()
1469 "Cleanup when changing a buffer from SES mode to something else. Delete
1470 overlay, remove special text properties."
1472 (let ((inhibit-read-only t)
1473 (was-modified (buffer-modified-p)))
1474 ;;Delete read-only, keymap, and intangible properties
1475 (set-text-properties (point-min) (point-max) nil)
1477 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1478 (unless was-modified
1479 (set-buffer-modified-p nil))))
1483 "Major mode for Simple Emacs Spreadsheet.
1484 See \"ses-example.ses\" (in the etc data directory) for more info.
1488 These key definitions are active only in the print area (the visible part):
1489 \\{ses-mode-print-map}
1490 These are active only in the minibuffer, when entering or editing a formula:
1491 \\{ses-mode-edit-map}"
1493 (unless (and (boundp 'ses--deferred-narrow)
1494 (eq ses--deferred-narrow 'ses-mode))
1495 (kill-all-local-variables)
1496 (mapc 'make-local-variable ses-localvars)
1497 (setq major-mode 'ses-mode
1499 next-line-add-newlines nil
1501 ;;SES deliberately puts lots of trailing whitespace in its buffer
1502 show-trailing-whitespace nil
1503 ;;Cell ranges do not work reasonably without this
1504 transient-mark-mode t)
1505 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1506 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1507 (setq ses--curcell nil
1508 ses--deferred-recalc nil
1509 ses--deferred-write nil
1510 ses--header-hscroll -1 ;Flag for "initial recalc needed"
1511 header-line-format '(:eval (progn
1512 (when (/= (window-hscroll)
1513 ses--header-hscroll)
1514 ;;Reset ses--header-hscroll first, to
1515 ;;avoid recursion problems when
1516 ;;debugging ses-create-header-string
1517 (setq ses--header-hscroll
1519 (ses-create-header-string))
1520 ses--header-string)))
1521 (let ((was-empty (zerop (buffer-size)))
1522 (was-modified (buffer-modified-p)))
1525 ;;Initialize buffer to contain one cell, for now
1526 (insert ses-initial-file-contents))
1530 (unless (equal ses-initial-default-printer (1value ses--default-printer))
1531 (1value (ses-read-default-printer ses-initial-default-printer)))
1532 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1533 (1value (ses-set-column-width 0 ses-initial-column-width)))
1535 (if (> (car ses-initial-size) (1value ses--numrows))
1536 (1value (ses-insert-row (1- (car ses-initial-size)))))
1537 (if (> (cdr ses-initial-size) (1value ses--numcols))
1538 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1540 (restore-buffer-modified-p was-modified)
1541 (buffer-disable-undo)
1542 (buffer-enable-undo)
1543 (goto-char (point-min))))
1544 (use-local-map ses-mode-map)
1545 ;;Set the deferred narrowing flag (we can't narrow until after
1546 ;;after-find-file completes). If .ses is on the auto-load alist and the
1547 ;;file has "mode: ses", our ses-mode function will be called twice! Use
1548 ;;a special flag to detect this (will be reset by ses-command-hook).
1549 ;;For find-alternate-file, post-command-hook doesn't get run for some
1550 ;;reason, so use an idle timer to make sure.
1551 (setq ses--deferred-narrow 'ses-mode)
1552 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1553 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1554 (run-mode-hooks 'ses-mode-hook)))
1556 (put 'ses-mode 'mode-class 'special)
1558 (defun ses-command-hook ()
1559 "Invoked from `post-command-hook'. If point has moved to a different cell,
1560 moves the underlining overlay. Performs any recalculations or cell-data
1561 writes that have been deferred. If buffer-narrowing has been deferred,
1562 narrows the buffer now."
1564 (when (eq major-mode 'ses-mode) ;Otherwise, not our buffer anymore
1565 (when ses--deferred-recalc
1566 ;;We reset the deferred list before starting on the recalc -- in case
1567 ;;of error, we don't want to retry the recalc after every keystroke!
1568 (let ((old ses--deferred-recalc))
1569 (setq ses--deferred-recalc nil)
1570 (ses-update-cells old)))
1571 (if ses--deferred-write
1572 ;;We don't reset the deferred list before starting -- the most
1573 ;;likely error is keyboard-quit, and we do want to keep trying
1574 ;;these writes after a quit.
1576 (when ses--deferred-narrow
1577 ;;We're not allowed to narrow the buffer until after-find-file has
1578 ;;read the local variables at the end of the file. Now it's safe to
1581 (goto-char (point-min))
1582 (forward-line ses--numrows)
1583 (narrow-to-region (point-min) (point)))
1584 (setq ses--deferred-narrow nil))
1585 ;;Update the modeline
1586 (let ((oldcell ses--curcell))
1588 (unless (eq ses--curcell oldcell)
1591 (setq mode-line-process nil))
1592 ((atom ses--curcell)
1593 (setq mode-line-process (list " cell "
1594 (symbol-name ses--curcell))))
1596 (setq mode-line-process (list " range "
1597 (symbol-name (car ses--curcell))
1599 (symbol-name (cdr ses--curcell))))))
1600 (force-mode-line-update)))
1601 ;;Use underline overlay for single-cells only, turn off otherwise
1602 (if (listp ses--curcell)
1603 (move-overlay ses--curcell-overlay 2 2)
1604 (let ((next (next-single-property-change (point) 'intangible)))
1605 (move-overlay ses--curcell-overlay (point) (1- next))))
1606 (when (not (pos-visible-in-window-p))
1607 ;;Scrolling will happen later
1608 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1609 (setq ses--curcell t)))
1610 ;;Prevent errors in this post-command-hook from silently erasing the hook!
1612 (unless executing-kbd-macro
1614 (message "%s" (error-message-string err))))
1615 nil) ;Make coverage-tester happy
1617 (defun ses-create-header-string ()
1618 "Set up `ses--header-string' as the buffer's header line.
1619 Based on the current set of columns and `window-hscroll' position."
1620 (let ((totwidth (- (window-hscroll)))
1622 ;;Leave room for the left-side fringe and scrollbar
1623 (push (propertize " " 'display '((space :align-to 0))) result)
1624 (dotimes (col ses--numcols)
1625 (setq width (ses-col-width col)
1626 totwidth (+ totwidth width 1))
1628 ;;Scrolled so intercolumn space is leftmost
1630 (when (> totwidth 1)
1631 (if (> ses--header-row 0)
1633 (ses-goto-print (1- ses--header-row) col)
1634 (setq x (buffer-substring-no-properties (point)
1636 ;; Strip trailing space.
1637 (if (string-match "[ \t]+\\'" x)
1638 (setq x (substring x 0 (match-beginning 0))))
1639 ;; Cut off excess text.
1640 (if (>= (length x) totwidth)
1641 (setq x (substring x 0 (- totwidth -1)))))
1642 (setq x (ses-column-letter col)))
1643 (push (propertize x 'face ses-box-prop) result)
1644 (push (propertize "."
1645 'display `((space :align-to ,(1- totwidth)))
1648 ;;Allow the following space to be squished to make room for the 3-D box
1649 ;;Coverage test ignores properties, thinks this is always a space!
1650 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
1652 (if (> ses--header-row 0)
1653 (push (propertize (format " [row %d]" ses--header-row)
1654 'display '((height (- 1))))
1656 (setq ses--header-string (apply 'concat (nreverse result)))))
1659 ;;----------------------------------------------------------------------------
1660 ;; Redisplay and recalculation
1661 ;;----------------------------------------------------------------------------
1663 (defun ses-jump (sym)
1664 "Move point to cell SYM."
1665 (interactive "SJump to cell: ")
1666 (let ((rowcol (ses-sym-rowcol sym)))
1667 (or rowcol (error "Invalid cell name"))
1668 (if (eq (symbol-value sym) '*skip*)
1669 (error "Cell is covered by preceding cell"))
1670 (ses-goto-print (car rowcol) (cdr rowcol))))
1672 (defun ses-jump-safe (cell)
1673 "Like `ses-jump', but no error if invalid cell."
1678 (defun ses-reprint-all (&optional nonarrow)
1679 "Recreate the display area. Calls all printer functions. Narrows to
1680 print area if NONARROW is nil."
1684 (setq ses--deferred-narrow t))
1685 (let ((startcell (get-text-property (point) 'intangible))
1686 (inhibit-read-only t))
1688 (goto-char (point-min))
1689 (search-forward ses-print-data-boundary)
1690 (backward-char (length ses-print-data-boundary))
1691 (delete-region (point-min) (point))
1692 ;;Insert all blank lines before printing anything, so ses-print-cell can
1693 ;;find the data area when inserting or deleting *skip* values for cells
1694 (dotimes (row ses--numrows)
1695 (insert-and-inherit ses--blank-line))
1696 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
1697 (if (eq (ses-cell-value row 0) '*skip*)
1698 ;;Column deletion left a dangling skip
1699 (ses-set-cell row 0 'value nil))
1700 (dotimes (col ses--numcols)
1701 (ses-print-cell row col))
1702 (beginning-of-line 2))
1703 (ses-jump-safe startcell)))
1705 (defun ses-recalculate-cell ()
1706 "Recalculate and reprint the current cell or range.
1708 For an individual cell, shows the error if the formula or printer
1709 signals one, or otherwise shows the cell's complete value. For a range, the
1710 cells are recalculated in \"natural\" order, so cells that other cells refer
1711 to are recalculated first."
1713 (ses-check-curcell 'range)
1716 (setq ses-start-time (float-time))
1717 (if (atom ses--curcell)
1718 (setq sig (ses-sym-rowcol ses--curcell)
1719 sig (ses-calculate-cell (car sig) (cdr sig) t))
1720 ;;First, recalculate all cells that don't refer to other cells and
1721 ;;produce a list of cells with references.
1722 (ses-dorange ses--curcell
1723 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
1726 ;;The t causes an error if the cell has references.
1727 ;;If no references, the t will be the result value.
1728 (1value (ses-formula-references (ses-cell-formula row col) t))
1729 (setq sig (ses-calculate-cell row col t)))
1730 (wrong-type-argument
1731 ;;The formula contains a reference
1732 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
1733 ;;Do the update now, so we can force recalculation
1734 (let ((x ses--deferred-recalc))
1735 (setq ses--deferred-recalc nil)
1736 (condition-case hold
1737 (ses-update-cells x t)
1738 (error (setq sig hold))))
1741 (message "%s" (error-message-string sig)))
1742 ((consp ses--curcell)
1745 (princ (symbol-value ses--curcell))))))
1747 (defun ses-recalculate-all ()
1748 "Recalculate and reprint all cells."
1750 (let ((startcell (get-text-property (point) 'intangible))
1751 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
1752 (1- ses--numcols)))))
1753 (ses-recalculate-cell)
1754 (ses-jump-safe startcell)))
1756 (defun ses-truncate-cell ()
1757 "Reprint current cell, but without spillover into any following blank
1761 (let* ((rowcol (ses-sym-rowcol ses--curcell))
1764 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
1765 (eq (ses-cell-value row (1+ col)) '*skip*))
1766 ;;This cell has spill-over. We'll momentarily pretend the following
1767 ;;cell has a `t' in it.
1768 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
1769 (ses-print-cell row col)))
1770 ;;Now remove the *skip*. ses-print-cell is always nil here
1771 (ses-set-cell row (1+ col) 'value nil)
1772 (1value (ses-print-cell row (1+ col))))))
1774 (defun ses-reconstruct-all ()
1775 "Reconstruct buffer based on cell data stored in Emacs variables."
1778 ;;Reconstruct reference lists.
1780 ;;Delete old reference lists
1781 (dotimes-with-progress-reporter
1782 (row ses--numrows) "Deleting references..."
1783 (dotimes (col ses--numcols)
1784 (ses-set-cell row col 'references nil)))
1785 ;;Create new reference lists
1786 (dotimes-with-progress-reporter
1787 (row ses--numrows) "Computing references..."
1788 (dotimes (col ses--numcols)
1789 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
1790 (setq x (ses-sym-rowcol ref)
1793 (ses-set-cell yrow ycol 'references
1794 (cons (ses-cell-symbol row col)
1795 (ses-cell-references yrow ycol)))))))
1796 ;;Delete everything and reconstruct basic data area
1797 (if (ses-narrowed-p)
1798 (setq ses--deferred-narrow t))
1800 (let ((inhibit-read-only t))
1801 (goto-char (point-max))
1802 (if (search-backward ";; Local Variables:\n" nil t)
1803 (delete-region (point-min) (point))
1804 ;;Buffer is quite screwed up - can't even save the user-specified locals
1805 (delete-region (point-min) (point-max))
1806 (insert ses-initial-file-trailer)
1807 (goto-char (point-min)))
1808 ;;Create a blank display area
1809 (dotimes (row ses--numrows)
1810 (insert ses--blank-line))
1811 (insert ses-print-data-boundary)
1812 ;;Placeholders for cell data
1813 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
1814 ;;Placeholders for col-widths, col-printers, default-printer, header-row
1816 (insert ses-initial-global-parameters))
1817 (ses-set-parameter 'ses--col-widths ses--col-widths)
1818 (ses-set-parameter 'ses--col-printers ses--col-printers)
1819 (ses-set-parameter 'ses--default-printer ses--default-printer)
1820 (ses-set-parameter 'ses--header-row ses--header-row)
1821 (ses-set-parameter 'ses--numrows ses--numrows)
1822 (ses-set-parameter 'ses--numcols ses--numcols)
1823 ;;Keep our old narrowing
1825 (ses-recalculate-all)
1826 (goto-char (point-min)))
1829 ;;----------------------------------------------------------------------------
1830 ;; Input of cell formulas
1831 ;;----------------------------------------------------------------------------
1833 (defun ses-edit-cell (row col newval)
1834 "Display current cell contents in minibuffer, for editing. Returns nil if
1835 cell formula was unsafe and user declined confirmation."
1838 (barf-if-buffer-read-only)
1840 (let* ((rowcol (ses-sym-rowcol ses--curcell))
1843 (formula (ses-cell-formula row col))
1845 (if (eq (car-safe formula) 'ses-safe-formula)
1846 (setq formula (cadr formula)))
1847 (if (eq (car-safe formula) 'quote)
1848 (setq initial (format "'%S" (cadr formula)))
1849 (setq initial (prin1-to-string formula)))
1850 (if (stringp formula)
1851 ;;Position cursor inside close-quote
1852 (setq initial (cons initial (length initial))))
1854 (read-from-minibuffer (format "Cell %s: " ses--curcell)
1857 t ;Convert to Lisp object
1858 'ses-read-cell-history)))))
1859 (when (ses-warn-unsafe newval 'unsafep)
1861 (ses-cell-set-formula row col newval)
1864 (defun ses-read-cell (row col newval)
1865 "Self-insert for initial character of cell function."
1867 (let* ((initial (this-command-keys))
1868 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
1869 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
1870 (barf-if-buffer-read-only)
1873 (read-from-minibuffer
1874 (format "Cell %s: " ses--curcell)
1875 (cons (if (equal initial "\"") "\"\""
1876 (if (equal initial "(") "()" initial)) 2)
1878 t ;Convert to Lisp object
1879 'ses-read-cell-history
1880 (prin1-to-string curval)))))
1881 (when (ses-edit-cell row col newval)
1882 (ses-command-hook) ;Update cell widths before movement
1883 (dolist (x ses-after-entry-functions)
1886 (defun ses-read-symbol (row col symb)
1887 "Self-insert for a symbol as a cell formula. The set of all symbols that
1888 have been used as formulas in this spreadsheet is available for completions."
1890 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
1892 (barf-if-buffer-read-only)
1893 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
1894 ses--symbolic-formulas))
1897 (if (string= newval "")
1898 nil ;Don't create zero-length symbols!
1899 (list 'quote (intern newval))))))
1900 (when (ses-edit-cell row col symb)
1901 (ses-command-hook) ;Update cell widths before movement
1902 (dolist (x ses-after-entry-functions)
1905 (defun ses-clear-cell-forward (count)
1906 "Delete formula and printer for current cell and then move to next cell.
1907 With prefix, deletes several cells."
1910 (1value (ses-clear-cell-backward (- count)))
1915 (let ((rowcol (ses-sym-rowcol ses--curcell)))
1916 (or rowcol (signal 'end-of-buffer nil))
1917 (ses-clear-cell (car rowcol) (cdr rowcol)))
1920 (defun ses-clear-cell-backward (count)
1921 "Move to previous cell and then delete it. With prefix, deletes several
1925 (1value (ses-clear-cell-forward (- count)))
1926 (ses-check-curcell 'end)
1929 (backward-char 1) ;Will signal 'beginning-of-buffer if appropriate
1931 (let ((rowcol (ses-sym-rowcol ses--curcell)))
1932 (ses-clear-cell (car rowcol) (cdr rowcol))))))
1935 ;;----------------------------------------------------------------------------
1936 ;; Input of cell-printer functions
1937 ;;----------------------------------------------------------------------------
1939 (defun ses-read-printer (prompt default)
1940 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
1941 PROMPT should end with \": \". Result is t if operation was cancelled."
1942 (barf-if-buffer-read-only)
1945 (setq prompt (format "%s [currently %S]: "
1946 (substring prompt 0 -2)
1948 (let ((new (read-from-minibuffer prompt
1949 nil ;Initial contents
1951 t ;Evaluate the result
1952 'ses-read-printer-history
1953 (prin1-to-string default))))
1954 (if (equal new default)
1955 ;;User changed mind, decided not to change printer
1957 (ses-printer-validate new)
1960 (stringp (car-safe new))
1961 (ses-warn-unsafe new 'unsafep-function)
1965 (defun ses-read-cell-printer (newval)
1966 "Set the printer function for the current cell or range.
1968 A printer function is either a string (a format control-string with one
1969 %-sequence -- result from format will be right-justified), or a list of one
1970 string (result from format will be left-justified), or a lambda-expression of
1971 one argument, or a symbol that names a function of one argument. In the
1972 latter two cases, the function's result should be either a string (will be
1973 right-justified) or a list of one string (will be left-justified)."
1977 (ses-check-curcell 'range)
1978 ;;Default is none if not all cells in range have same printer
1979 (catch 'ses-read-cell-printer
1980 (ses-dorange ses--curcell
1981 (setq x (ses-cell-printer row col))
1982 (if (eq (car-safe x) 'ses-safe-printer)
1986 (unless (equal default x)
1987 ;;Range contains differing printer functions
1989 (throw 'ses-read-cell-printer t)))))
1990 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
1992 (unless (eq newval t)
1994 (ses-dorange ses--curcell
1995 (ses-set-cell row col 'printer newval)
1996 (ses-print-cell row col))))
1998 (defun ses-read-column-printer (col newval)
1999 "Set the printer function for the current column. See
2000 `ses-read-cell-printer' for input forms."
2002 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2004 (list col (ses-read-printer (format "Column %s printer: "
2005 (ses-column-letter col))
2006 (ses-col-printer col)))))
2008 (unless (eq newval t)
2010 (ses-set-parameter 'ses--col-printers newval col)
2012 (dotimes (row ses--numrows)
2013 (ses-print-cell row col)))))
2015 (defun ses-read-default-printer (newval)
2016 "Set the default printer function for cells that have no other. See
2017 `ses-read-cell-printer' for input forms."
2019 (list (ses-read-printer "Default printer: " ses--default-printer)))
2020 (unless (eq newval t)
2022 (ses-set-parameter 'ses--default-printer newval)
2023 (ses-reprint-all t)))
2026 ;;----------------------------------------------------------------------------
2027 ;; Spreadsheet size adjustments
2028 ;;----------------------------------------------------------------------------
2030 (defun ses-insert-row (count)
2031 "Insert a new row before the current one. With prefix, insert COUNT rows
2032 before current one."
2034 (ses-check-curcell 'end)
2035 (or (> count 0) (signal 'args-out-of-range nil))
2037 (let ((inhibit-quit t)
2038 (inhibit-read-only t)
2039 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2041 ;;Create a new set of cell-variables
2042 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2043 0 (1- ses--numcols))
2044 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2046 (ses-goto-print row 0)
2047 (dotimes-with-progress-reporter (x count) "Inserting row..."
2048 ;;Create a row of empty cells. The `symbol' fields will be set by
2049 ;;the call to ses-relocate-all.
2050 (setq newrow (make-vector ses--numcols nil))
2051 (dotimes (col ses--numcols)
2052 (aset newrow col (ses-make-cell)))
2053 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2054 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2055 (insert ses--blank-line))
2056 ;;Insert empty lines in cell data area (will be replaced by
2058 (ses-goto-data row 0)
2059 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2060 (ses-relocate-all row 0 count 0)
2061 ;;If any cell printers insert constant text, insert that text
2063 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2064 (global (ses-call-printer ses--default-printer)))
2065 (if (or (> (length cols) 0) (> (length global) 0))
2067 (dotimes (col ses--numcols)
2068 ;;These cells are always nil, only constant formatting printed
2069 (1value (ses-print-cell (+ x row) col))))))
2070 (when (> ses--header-row row)
2071 ;;Inserting before header
2072 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2073 (ses-reset-header-string)))
2074 ;;Reconstruct text attributes
2076 ;;Return to current cell
2078 (ses-jump-safe ses--curcell)
2079 (ses-goto-print (1- ses--numrows) 0)))
2081 (defun ses-delete-row (count)
2082 "Delete the current row. With prefix, Deletes COUNT rows starting from the
2086 (or (> count 0) (signal 'args-out-of-range nil))
2087 (let ((inhibit-quit t)
2088 (inhibit-read-only t)
2089 (row (car (ses-sym-rowcol ses--curcell))))
2090 (setq count (min count (- ses--numrows row)))
2092 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2093 ;;Delete lines from print area
2094 (ses-goto-print row 0)
2095 (ses-delete-line count)
2096 ;;Delete lines from cell data area
2097 (ses-goto-data row 0)
2098 (ses-delete-line (* count (1+ ses--numcols)))
2099 ;;Relocate variables and formulas
2100 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2101 (ses-relocate-all row 0 (- count) 0)
2102 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2103 0 (1- ses--numcols))
2104 (when (> ses--header-row row)
2105 (if (<= ses--header-row (+ row count))
2106 ;;Deleting the header row
2107 (ses-set-parameter 'ses--header-row 0)
2108 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2109 (ses-reset-header-string)))
2110 ;;Reconstruct attributes
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 (ses-set-parameter 'ses--header-row row)
2647 (ses-reset-header-string))
2649 (defun ses-mark-row ()
2650 "Marks the entirety of current row as a range."
2652 (ses-check-curcell 'range)
2653 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
2655 (ses-goto-print (1+ row) 0)
2656 (push-mark (point) nil t)
2657 (ses-goto-print row 0)))
2659 (defun ses-mark-column ()
2660 "Marks the entirety of current column as a range."
2662 (ses-check-curcell 'range)
2663 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
2666 (ses-goto-print (1- ses--numrows) col)
2668 (push-mark (point) nil t)
2669 (while (eq '*skip* (ses-cell-value row col))
2670 ;;Skip over initial cells in column that can't be selected
2671 (setq row (1+ row)))
2672 (ses-goto-print row col)))
2674 (defun ses-end-of-line ()
2675 "Move point to last cell on line."
2677 (ses-check-curcell 'end 'range)
2678 (when ses--curcell ;Otherwise we're at the bottom row, which is empty anyway
2679 (let ((col (1- ses--numcols))
2681 (if (symbolp ses--curcell)
2683 (setq row (car (ses-sym-rowcol ses--curcell)))
2684 ;;Range - use whichever end of the range the point is at
2685 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
2687 (cdr ses--curcell))))
2688 ;;If range already includes the last cell in a row, point is actually
2689 ;;in the following row
2690 (if (<= (cdr rowcol) (1- col))
2691 (setq row (car rowcol))
2692 (setq row (1+ (car rowcol)))
2693 (if (= row ses--numrows)
2694 ;;Already at end - can't go anywhere
2696 (when (< row ses--numrows) ;Otherwise it's a range that includes last cell
2697 (while (eq (ses-cell-value row col) '*skip*)
2698 ;;Back to beginning of multi-column cell
2699 (setq col (1- col)))
2700 (ses-goto-print row col)))))
2702 (defun ses-renarrow-buffer ()
2703 "Narrow the buffer so only the print area is visible. Use after \\[widen]."
2705 (setq ses--deferred-narrow t))
2707 (defun ses-sort-column (sorter &optional reverse)
2708 "Sorts the range by a specified column. With prefix, sorts in
2710 (interactive "*sSort column: \nP")
2711 (ses-check-curcell 'needrange)
2712 (let ((min (ses-sym-rowcol (car ses--curcell)))
2713 (max (ses-sym-rowcol (cdr ses--curcell))))
2714 (let ((minrow (car min))
2719 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
2720 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
2721 (error "Invalid sort column"))
2722 ;;Get key columns and sort them
2723 (dotimes (x (- maxrow minrow -1))
2724 (ses-goto-print (+ minrow x) sorter)
2725 (setq end (next-single-property-change (point) 'intangible))
2726 (push (cons (buffer-substring-no-properties (point) end)
2729 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
2730 ;;Extract the lines in reverse sorted order
2732 (setq keys (nreverse keys)))
2734 (ses-goto-print (cdr x) (1+ maxcol))
2736 (ses-goto-print (cdr x) mincol)
2737 (push (ses-copy-region (point) end) extracts))
2739 ;;Paste the lines sequentially
2740 (dotimes (x (- maxrow minrow -1))
2741 (ses-goto-print (+ minrow x) mincol)
2743 (ses-yank-cells (pop extracts) nil)))))
2745 (defun ses-sort-column-click (event reverse)
2746 "Mouse version of `ses-sort-column'."
2747 (interactive "*e\nP")
2748 (setq event (event-end event))
2749 (select-window (posn-window event))
2750 (setq event (car (posn-col-row event))) ;Click column
2752 (while (and (< col ses--numcols) (> event (ses-col-width col)))
2753 (setq event (- event (ses-col-width col) 1)
2755 (if (>= col ses--numcols)
2757 (ses-sort-column (ses-column-letter col) reverse))))
2759 (defun ses-insert-range ()
2760 "Inserts into minibuffer the list of cells currently highlighted in the
2764 (with-current-buffer (window-buffer minibuffer-scroll-window)
2765 (ses-command-hook) ;For ses-coverage
2766 (ses-check-curcell 'needrange)
2767 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
2768 ,(cdr ses--curcell))))))
2769 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
2771 (defun ses-insert-ses-range ()
2772 "Inserts \"(ses-range x y)\" in the minibuffer to represent the currently
2773 highlighted range in the spreadsheet."
2776 (with-current-buffer (window-buffer minibuffer-scroll-window)
2777 (ses-command-hook) ;For ses-coverage
2778 (ses-check-curcell 'needrange)
2779 (setq x (format "(ses-range %S %S)"
2781 (cdr ses--curcell))))
2784 (defun ses-insert-range-click (event)
2785 "Mouse version of `ses-insert-range'."
2787 (mouse-set-point event)
2790 (defun ses-insert-ses-range-click (event)
2791 "Mouse version of `ses-insert-ses-range'."
2793 (mouse-set-point event)
2794 (ses-insert-ses-range))
2797 ;;----------------------------------------------------------------------------
2798 ;; Checking formulas for safety
2799 ;;----------------------------------------------------------------------------
2801 (defun ses-safe-printer (printer)
2802 "Returns PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
2803 (if (or (stringp printer)
2804 (stringp (car-safe printer))
2806 (ses-warn-unsafe printer 'unsafep-function))
2810 (defun ses-safe-formula (formula)
2811 "Returns FORMULA if safe, or the substitute formula *unsafe* otherwise."
2812 (if (ses-warn-unsafe formula 'unsafep)
2814 `(ses-unsafe ',formula)))
2816 (defun ses-warn-unsafe (formula checker)
2817 "Applies CHECKER to FORMULA. If result is non-nil, asks user for
2818 confirmation about FORMULA, which might be unsafe. Returns t if formula
2819 is safe or user allows execution anyway. Always returns t if
2820 `safe-functions' is t."
2821 (if (eq safe-functions t)
2823 (setq checker (funcall checker formula))
2826 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
2827 formula checker)))))
2830 ;;----------------------------------------------------------------------------
2831 ;; Standard formulas
2832 ;;----------------------------------------------------------------------------
2834 (defmacro ses-range (from to)
2835 "Expands to a list of cell-symbols for the range. The range automatically
2836 expands to include any new row or column inserted into its middle. The SES
2837 library code specifically looks for the symbol `ses-range', so don't create an
2838 alias for this macro!"
2840 (ses-dorange (cons from to)
2841 (push (ses-cell-symbol row col) result))
2842 (cons 'list result)))
2844 (defun ses-delete-blanks (&rest args)
2845 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
2848 (unless (memq cur '(nil *skip*))
2852 (defun ses+ (&rest args)
2853 "Compute the sum of the arguments, ignoring blanks."
2854 (apply '+ (apply 'ses-delete-blanks args)))
2856 (defun ses-average (list)
2857 "Computes the sum of the numbers in LIST, divided by their length. Blanks
2858 are ignored. Result is always floating-point, even if all args are integers."
2859 (setq list (apply 'ses-delete-blanks list))
2860 (/ (float (apply '+ list)) (length list)))
2862 (defmacro ses-select (fromrange test torange)
2863 "Select cells in FROMRANGE that are `equal' to TEST. For each match, return
2864 the corresponding cell from TORANGE. The ranges are macroexpanded but not
2865 evaluated so they should be either (ses-range BEG END) or (list ...). The
2867 (setq fromrange (cdr (macroexpand fromrange))
2868 torange (cdr (macroexpand torange))
2870 (or (= (length fromrange) (length torange))
2871 (error "ses-select: Ranges not same length"))
2873 (dolist (x fromrange)
2874 (if (equal test (symbol-value x))
2875 (push (car torange) result))
2876 (setq torange (cdr torange)))
2877 (cons 'list result)))
2879 ;;All standard formulas are safe
2880 (dolist (x '(ses-range ses-delete-blanks ses+ ses-average ses-select))
2881 (put x 'side-effect-free t))
2884 ;;----------------------------------------------------------------------------
2885 ;; Standard print functions
2886 ;;----------------------------------------------------------------------------
2888 ;;These functions use the variables 'row' and 'col' that are
2889 ;;dynamically bound by ses-print-cell. We define these varables at
2890 ;;compile-time to make the compiler happy.
2892 (dolist (x '(row col))
2893 (make-local-variable x)
2896 (defun ses-center (value &optional span fill)
2897 "Print VALUE, centered within column. FILL is the fill character for
2898 centering (default = space). SPAN indicates how many additional rightward
2899 columns to include in width (default = 0)."
2900 (let ((printer (or (ses-col-printer col) ses--default-printer))
2901 (width (ses-col-width col))
2903 (or fill (setq fill ?\s))
2904 (or span (setq span 0))
2905 (setq value (ses-call-printer printer value))
2907 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
2908 (setq width (- width (length value)))
2910 value ;Too large for field, anyway
2911 (setq half (make-string (/ width 2) fill))
2912 (concat half value half
2913 (if (> (% width 2) 0) (char-to-string fill))))))
2915 (defun ses-center-span (value &optional fill)
2916 "Print VALUE, centered within the span that starts in the current column
2917 and continues until the next nonblank column. FILL specifies the fill
2918 character (default = space)."
2919 (let ((end (1+ col)))
2920 (while (and (< end ses--numcols)
2921 (memq (ses-cell-value row end) '(nil *skip*)))
2922 (setq end (1+ end)))
2923 (ses-center value (- end col 1) fill)))
2925 (defun ses-dashfill (value &optional span)
2926 "Print VALUE centered using dashes. SPAN indicates how many rightward
2927 columns to include in width (default = 0)."
2928 (ses-center value span ?-))
2930 (defun ses-dashfill-span (value)
2931 "Print VALUE, centered using dashes within the span that starts in the
2932 current column and continues until the next nonblank column."
2933 (ses-center-span value ?-))
2935 (defun ses-tildefill-span (value)
2936 "Print VALUE, centered using tildes within the span that starts in the
2937 current column and continues until the next nonblank column."
2938 (ses-center-span value ?~))
2940 (defun ses-unsafe (value)
2941 "Substitute for an unsafe formula or printer"
2942 (error "Unsafe formula or printer"))
2944 ;;All standard printers are safe, including ses-unsafe!
2945 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
2946 (put x 'side-effect-free t))
2950 ;; arch-tag: 88c1ccf0-4293-4824-8c5d-0757b52217f3
2951 ;;; ses.el ends here