1 ;;; ses.el -- Simple Emacs Spreadsheet -*- coding: utf-8 -*-
3 ;; Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Author: Jonathan Yavner <jyavner@member.fsf.org>
7 ;; Maintainer: Jonathan Yavner <jyavner@member.fsf.org>
8 ;; Keywords: spreadsheet
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; * Use $ or … for truncated fields
30 ;; * Add command to make a range of columns be temporarily invisible.
31 ;; * Allow paste of one cell to a range of cells -- copy formula to each.
32 ;; * Do something about control characters & octal codes in cell print
33 ;; areas. Use string-width?
34 ;; * Input validation functions. How specified?
35 ;; * Faces (colors & styles) in print cells.
36 ;; * Move a column by dragging its letter in the header line.
37 ;; * Left-margin column for row number.
38 ;; * Move a row by dragging its number in the left-margin.
46 ;;----------------------------------------------------------------------------
47 ;; User-customizable variables
48 ;;----------------------------------------------------------------------------
51 "Simple Emacs Spreadsheet."
56 (defcustom ses-initial-size
'(1 .
1)
57 "Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
59 :type
'(cons (integer :tag
"numrows") (integer :tag
"numcols")))
61 (defcustom ses-initial-column-width
7
62 "Initial width of columns in a new spreadsheet."
64 :type
'(integer :match
(lambda (widget value
) (> value
0))))
66 (defcustom ses-initial-default-printer
"%.7g"
67 "Initial default printer for a new spreadsheet."
70 (list :tag
"Parenthesized string" string
)
73 (defcustom ses-after-entry-functions
'(forward-char)
74 "Things to do after entering a value into a cell.
75 An abnormal hook that usually runs a cursor-movement function.
76 Each function is called with ARG=1."
79 :options
'(forward-char backward-char next-line previous-line
))
81 (defcustom ses-mode-hook nil
82 "Hook functions to be run upon entering SES mode."
87 ;;----------------------------------------------------------------------------
88 ;; Global variables and constants
89 ;;----------------------------------------------------------------------------
91 (defvar ses-read-cell-history nil
92 "List of formulas that have been typed in.")
94 (defvar ses-read-printer-history nil
95 "List of printer functions that have been typed in.")
97 (easy-menu-define ses-header-line-menu nil
98 "Context menu when mouse-3 is used on the header-line in an SES buffer."
100 ["Set current row" ses-set-header-row t
]
101 ["Unset row" ses-unset-header-row
(> ses--header-row
0)]))
103 (defconst ses-mode-map
104 (let ((keys `("\C-c\M-\C-l" ses-reconstruct-all
105 "\C-c\C-l" ses-recalculate-all
106 "\C-c\C-n" ses-renarrow-buffer
107 "\C-c\C-c" ses-recalculate-cell
108 "\C-c\M-\C-s" ses-sort-column
109 "\C-c\M-\C-h" ses-set-header-row
110 "\C-c\C-t" ses-truncate-cell
112 "\C-c\C-p" ses-read-default-printer
113 "\M-\C-l" ses-reprint-all
114 [?\S-\C-l
] ses-reprint-all
115 [header-line down-mouse-3
] ,ses-header-line-menu
116 [header-line mouse-2
] ses-sort-column-click
))
117 (newmap (make-sparse-keymap)))
119 (define-key (1value newmap
) (car keys
) (cadr keys
))
120 (setq keys
(cddr keys
)))
122 "Local keymap for Simple Emacs Spreadsheet.")
124 (easy-menu-define ses-menu ses-mode-map
125 "Menu bar menu for SES."
127 ["Insert row" ses-insert-row
(ses-in-print-area)]
128 ["Delete row" ses-delete-row
(ses-in-print-area)]
129 ["Insert column" ses-insert-column
(ses-in-print-area)]
130 ["Delete column" ses-delete-column
(ses-in-print-area)]
131 ["Set column printer" ses-read-column-printer t
]
132 ["Set column width" ses-set-column-width t
]
133 ["Set default printer" ses-read-default-printer t
]
134 ["Jump to cell" ses-jump t
]
135 ["Set cell printer" ses-read-cell-printer t
]
136 ["Recalculate cell" ses-recalculate-cell t
]
137 ["Truncate cell display" ses-truncate-cell t
]
138 ["Export values" ses-export-tsv t
]
139 ["Export formulas" ses-export-tsf t
]))
141 (defconst ses-mode-edit-map
142 (let ((keys '("\C-c\C-r" ses-insert-range
143 "\C-c\C-s" ses-insert-ses-range
144 [S-mouse-3
] ses-insert-range-click
145 [C-S-mouse-3
] ses-insert-ses-range-click
146 "\M-\C-i" lisp-complete-symbol
))
147 (newmap (make-sparse-keymap)))
148 (set-keymap-parent newmap minibuffer-local-map
)
150 (define-key newmap
(pop keys
) (pop keys
)))
152 "Local keymap for SES minibuffer cell-editing.")
154 ;Local keymap for SES print area
155 (defalias 'ses-mode-print-map
156 (let ((keys '([backtab] backward-char
157 [tab] ses-forward-or-insert
158 "\C-i" ses-forward-or-insert ;Needed for ses-coverage.el?
159 "\M-o" ses-insert-column
160 "\C-o" ses-insert-row
162 "\M-k" ses-delete-column
164 "\C-k" ses-delete-row
165 "\C-j" ses-append-row-jump-first-column
167 "\M-H" ses-mark-column
168 "\C-d" ses-clear-cell-forward
169 "\C-?" ses-clear-cell-backward
174 "c" ses-recalculate-cell
176 "p" ses-read-cell-printer
177 "t" ses-truncate-cell
178 "w" ses-set-column-width
179 "x" ses-export-keymap
180 "\M-p" ses-read-column-printer))
181 (repl '(;;We'll replace these wherever they appear in the keymap
182 clipboard-kill-region ses-kill-override
183 end-of-line ses-end-of-line
184 kill-line ses-delete-row
185 kill-region ses-kill-override
186 open-line ses-insert-row))
187 (numeric "0123456789.-")
188 (newmap (make-keymap)))
189 ;;Get rid of printables
190 (suppress-keymap newmap t)
191 ;;These keys insert themselves as the beginning of a numeric value
192 (dotimes (x (length numeric))
193 (define-key newmap (substring numeric x (1+ x)) 'ses-read-cell))
194 ;;Override these global functions wherever they're bound
196 (substitute-key-definition (car repl) (cadr repl) newmap
197 (current-global-map))
198 (setq repl (cddr repl)))
199 ;;Apparently substitute-key-definition doesn't catch this?
200 (define-key newmap [(menu-bar) edit cut] 'ses-kill-override)
201 ;;Define our other local keys
203 (define-key newmap (car keys) (cadr keys))
204 (setq keys (cddr keys)))
207 ;;Helptext for ses-mode wants keymap as variable, not function
208 (defconst ses-mode-print-map (symbol-function 'ses-mode-print-map))
210 ;;Key map used for 'x' key.
211 (defalias 'ses-export-keymap
212 (let ((map (make-sparse-keymap "SES export")))
213 (define-key map "T" (cons " tab-formulas" 'ses-export-tsf))
214 (define-key map "t" (cons " tab-values" 'ses-export-tsv))
217 (defconst ses-print-data-boundary "\n\014\n"
218 "Marker string denoting the boundary between print area and data area.")
220 (defconst ses-initial-global-parameters
221 "\n( ;Global parameters (these are read first)\n 2 ;SES file-format\n 1 ;numrows\n 1 ;numcols\n)\n\n"
222 "Initial contents for the three-element list at the bottom of the data area.")
224 (defconst ses-initial-file-trailer
225 ";; Local Variables:\n;; mode: ses\n;; End:\n"
226 "Initial contents for the file-trailer area at the bottom of the file.")
228 (defconst ses-initial-file-contents
229 (concat " \n" ;One blank cell in print area
230 ses-print-data-boundary
231 "(ses-cell A1 nil nil nil nil)\n" ;One blank cell in data area
232 "\n" ;End-of-row terminator for the one row in data area
233 "(ses-column-widths [7])\n"
234 "(ses-column-printers [nil])\n"
235 "(ses-default-printer \"%.7g\")\n"
236 "(ses-header-row 0)\n"
237 ses-initial-global-parameters
238 ses-initial-file-trailer)
239 "The initial contents of an empty spreadsheet.")
241 (defconst ses-box-prop '(:box (:line-width 2 :style released-button))
242 "Display properties to create a raised box for cells in the header line.")
244 (defconst ses-standard-printer-functions
245 '(ses-center ses-center-span ses-dashfill ses-dashfill-span
247 "List of print functions to be included in initial history of printer
248 functions. None of these standard-printer functions is suitable for use as a
249 column printer or a global-default printer because they invoke the column or
250 default printer and then modify its output.")
253 ;;----------------------------------------------------------------------------
254 ;; Local variables and constants
255 ;;----------------------------------------------------------------------------
258 (defconst ses-localvars
259 '(ses--blank-line ses--cells ses--col-printers ses--col-widths ses--curcell
260 ses--curcell-overlay ses--default-printer ses--deferred-narrow
261 ses--deferred-recalc ses--deferred-write ses--file-format
262 ses--header-hscroll ses--header-row ses--header-string ses--linewidth
263 ses--numcols ses--numrows ses--symbolic-formulas ses--data-marker
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)
275 ;;;This variable is documented as being permitted in file-locals:
276 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
278 (defconst ses-paramlines-plist
279 '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
280 ses--header-row -2 ses--file-format 1 ses--numrows 2
282 "Offsets from 'Global parameters' line to various parameter lines in the
283 data area of a spreadsheet.")
287 ;; "Side-effect variables". They are set in one function, altered in
288 ;; another as a side effect, then read back by the first, as a way of
289 ;; passing back more than one value. These declarations are just to make
290 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
291 ;; think the make-local-variable trick above is cleaner).
294 (defvar ses-relocate-return nil
295 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
296 `ses-relocate-all'. Set to 'delete if a cell-reference was deleted from a
297 formula--so the formula needs recalculation. Set to 'range if the size of a
298 `ses-range' was changed--so both the formula's value and list of dependents
299 need to be recalculated.")
301 (defvar ses-call-printer-return nil
302 "Set to t if last cell printer invoked by `ses-call-printer' requested
303 left-justification of the result. Set to error-signal if ses-call-printer
304 encountered an error during printing. Otherwise nil.")
306 (defvar ses-start-time nil
307 "Time when current operation started. Used by `ses-time-check' to decide
308 when to emit a progress message.")
311 ;;----------------------------------------------------------------------------
313 ;;----------------------------------------------------------------------------
315 (defmacro ses-get-cell (row col)
316 "Return the cell structure that stores information about cell (ROW,COL)."
317 `(aref (aref ses--cells ,row) ,col))
319 ;; We might want to use defstruct here, but cells are explicitly used as
320 ;; arrays in ses-set-cell, so we'd need to fix this first. --Stef
321 (defsubst ses-make-cell (&optional symbol formula printer references)
322 (vector symbol formula printer references))
324 (defmacro ses-cell-symbol (row &optional col)
325 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
326 `(aref ,(if col `(ses-get-cell ,row ,col) row) 0))
328 (defmacro ses-cell-formula (row &optional col)
329 "From a CELL or a pair (ROW,COL), get the function that computes its value."
330 `(aref ,(if col `(ses-get-cell ,row ,col) row) 1))
332 (defmacro ses-cell-printer (row &optional col)
333 "From a CELL or a pair (ROW,COL), get the function that prints its value."
334 `(aref ,(if col `(ses-get-cell ,row ,col) row) 2))
336 (defmacro ses-cell-references (row &optional col)
337 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
338 functions refer to its value."
339 `(aref ,(if col `(ses-get-cell ,row ,col) row) 3))
341 (defmacro ses-cell-value (row &optional col)
342 "From a CELL or a pair (ROW,COL), get the current value for that cell."
343 `(symbol-value (ses-cell-symbol ,row ,col)))
345 (defmacro ses-col-width (col)
346 "Return the width for column COL."
347 `(aref ses--col-widths ,col))
349 (defmacro ses-col-printer (col)
350 "Return the default printer for column COL."
351 `(aref ses--col-printers ,col))
353 (defmacro ses-sym-rowcol (sym)
354 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0). Result
355 is nil if SYM is not a symbol that names a cell."
356 `(and (symbolp ,sym) (get ,sym 'ses-cell)))
358 (defmacro ses-cell (sym value formula printer references)
359 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
360 FORMULA, does not reprint using PRINTER, does not check REFERENCES. This is a
361 macro to prevent propagate-on-load viruses. Safety-checking for FORMULA and
362 PRINTER are deferred until first use."
363 (let ((rowcol (ses-sym-rowcol sym)))
364 (ses-formula-record formula)
365 (ses-printer-record printer)
367 (eq safe-functions t)
368 (setq formula `(ses-safe-formula ,formula)))
371 (eq safe-functions t)
372 (setq printer `(ses-safe-printer ,printer)))
373 (aset (aref ses--cells (car rowcol))
375 (ses-make-cell sym formula printer references)))
379 (defmacro ses-column-widths (widths)
380 "Load the vector of column widths from the spreadsheet file. This is a
381 macro to prevent propagate-on-load viruses."
382 (or (and (vectorp widths) (= (length widths) ses--numcols))
383 (error "Bad column-width vector"))
384 ;;To save time later, we also calculate the total width of each line in the
385 ;;print area (excluding the terminating newline)
386 (setq ses--col-widths widths
387 ses--linewidth (apply '+ -1 (mapcar '1+ widths))
388 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
391 (defmacro ses-column-printers (printers)
392 "Load the vector of column printers from the spreadsheet file and checks
393 them for safety. This is a macro to prevent propagate-on-load viruses."
394 (or (and (vectorp printers) (= (length printers) ses--numcols))
395 (error "Bad column-printers vector"))
396 (dotimes (x ses--numcols)
397 (aset printers x (ses-safe-printer (aref printers x))))
398 (setq ses--col-printers printers)
399 (mapc 'ses-printer-record printers)
402 (defmacro ses-default-printer (def)
403 "Load the global default printer from the spreadsheet file and checks it
404 for safety. This is a macro to prevent propagate-on-load viruses."
405 (setq ses--default-printer (ses-safe-printer def))
406 (ses-printer-record def)
409 (defmacro ses-header-row (row)
410 "Load the header row from the spreadsheet file and checks it
411 for safety. This is a macro to prevent propagate-on-load viruses."
412 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
413 (error "Bad header-row"))
414 (setq ses--header-row row)
417 (defmacro ses-dorange (curcell &rest body)
418 "Execute BODY repeatedly, with the variables `row' and `col' set to each
419 cell in the range specified by CURCELL. The range is available in the
420 variables `minrow', `maxrow', `mincol', and `maxcol'."
421 (declare (indent defun) (debug (form body)))
422 (let ((cur (make-symbol "cur"))
423 (min (make-symbol "min"))
424 (max (make-symbol "max"))
425 (r (make-symbol "r"))
426 (c (make-symbol "c")))
427 `(let* ((,cur ,curcell)
428 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
429 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
430 (let ((minrow (car ,min))
435 (if (or (> minrow maxrow) (> mincol maxcol))
436 (error "Empty range"))
437 (dotimes (,r (- maxrow minrow -1))
438 (setq row (+ ,r minrow))
439 (dotimes (,c (- maxcol mincol -1))
440 (setq col (+ ,c mincol))
443 ;;Support for coverage testing.
444 (defmacro 1value (form)
445 "For code-coverage testing, indicate that FORM is expected to always have
448 (defmacro noreturn (form)
449 "For code-coverage testing, indicate that FORM will always signal an error."
453 ;;----------------------------------------------------------------------------
455 ;;----------------------------------------------------------------------------
457 (defun ses-vector-insert (array idx new)
458 "Create a new vector which is one larger than ARRAY and has NEW inserted
460 (let* ((len (length array))
461 (result (make-vector (1+ len) new)))
464 (if (< x idx) x (1+ x))
468 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
469 (defun ses-vector-delete (array idx count)
470 "Create a new vector which is a copy of ARRAY with COUNT objects removed
471 starting at element IDX. ARRAY is either a vector or a symbol whose value
472 is a vector--if a symbol, the new vector is assigned as the symbol's value."
473 (let* ((a (if (arrayp array) array (symbol-value array)))
474 (len (- (length a) count))
475 (result (make-vector len nil)))
477 (aset result x (aref a (if (< x idx) x (+ x count)))))
482 (defun ses-delete-line (count)
483 "Like `kill-line', but no kill ring."
486 (delete-region pos (point))))
488 (defun ses-printer-validate (printer)
489 "Signals an error if PRINTER is not a valid SES cell printer."
493 (and (stringp (car-safe printer)) (not (cdr printer)))
494 (error "Invalid printer function"))
497 (defun ses-printer-record (printer)
498 "Add PRINTER to `ses-read-printer-history' if not already there, after first
499 checking that it is a valid printer function."
500 (ses-printer-validate printer)
501 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
503 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
505 (defun ses-formula-record (formula)
506 "If FORMULA is of the form 'symbol, adds it to the list of symbolic formulas
507 for this spreadsheet."
508 (when (and (eq (car-safe formula) 'quote)
509 (symbolp (cadr formula)))
510 (add-to-list 'ses--symbolic-formulas
511 (list (symbol-name (cadr formula))))))
513 (defun ses-column-letter (col)
514 "Return the alphabetic name of column number COL.
515 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
516 (let ((units (char-to-string (+ ?A (% col 26)))))
519 (concat (ses-column-letter (1- (/ col 26))) units))))
521 (defun ses-create-cell-symbol (row col)
522 "Produce a symbol that names the cell (ROW,COL). (0,0) => 'A1."
523 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
525 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
526 "Create buffer-local variables for cells. This is undoable."
527 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
530 (dotimes (row (1+ (- maxrow minrow)))
531 (dotimes (col (1+ (- maxcol mincol)))
532 (setq xrow (+ row minrow)
534 sym (ses-create-cell-symbol xrow xcol))
535 (put sym 'ses-cell (cons xrow xcol))
536 (make-local-variable sym)))))
538 ;;We do not delete the ses-cell properties for the cell-variables, in case a
539 ;;formula that refers to this cell is in the kill-ring and is later pasted
541 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
542 "Destroy buffer-local variables for cells. This is undoable."
544 (dotimes (row (1+ (- maxrow minrow)))
545 (dotimes (col (1+ (- maxcol mincol)))
546 (setq sym (ses-create-cell-symbol (+ row minrow) (+ col mincol)))
548 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
550 (kill-local-variable sym))))
551 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
554 (defun ses-reset-header-string ()
555 "Flags the header string for update. Upon undo, the header string will be
557 (push '(apply ses-reset-header-string) buffer-undo-list)
558 (setq ses--header-hscroll -1))
560 ;;Split this code off into a function to avoid coverage-testing difficulties
561 (defun ses-time-check (format arg)
562 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
563 and (eval ARG) and reset `ses-start-time' to the current time."
564 (when (> (- (float-time) ses-start-time) 1.0)
565 (message format (eval arg))
566 (setq ses-start-time (float-time)))
570 ;;----------------------------------------------------------------------------
572 ;;----------------------------------------------------------------------------
574 (defun ses-set-cell (row col field val)
575 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
576 cell (ROW,COL). This is undoable. The cell's data will be updated through
577 `post-command-hook'."
578 (let ((cell (ses-get-cell row col))
579 (elt (plist-get '(value t symbol 0 formula 1 printer 2 references 3)
582 (or elt (signal 'args-out-of-range nil))
583 (setq change (if (eq elt t)
584 (ses-set-with-undo (ses-cell-symbol cell) val)
585 (ses-aset-with-undo cell elt val)))
587 (add-to-list 'ses--deferred-write (cons row col))))
588 nil) ;Make coverage-tester happy
590 (defun ses-cell-set-formula (row col formula)
591 "Store a new formula for (ROW . COL) and enqueues the cell for
592 recalculation via `post-command-hook'. Updates the reference lists for the
593 cells that this cell refers to. Does not update cell value or reprint the
594 cell. To avoid inconsistencies, this function is not interruptible, which
595 means Emacs will crash if FORMULA contains a circular list."
596 (let* ((cell (ses-get-cell row col))
597 (old (ses-cell-formula cell)))
598 (let ((sym (ses-cell-symbol cell))
599 (oldref (ses-formula-references old))
600 (newref (ses-formula-references formula))
603 (add-to-list 'ses--deferred-recalc sym)
604 ;;Delete old references from this cell. Skip the ones that are also
607 (unless (memq ref newref)
608 (setq x (ses-sym-rowcol ref)
611 (ses-set-cell xrow xcol 'references
612 (delq sym (ses-cell-references xrow xcol)))))
613 ;;Add new ones. Skip ones left over from old list
615 (setq x (ses-sym-rowcol ref)
618 x (ses-cell-references xrow xcol))
620 (ses-set-cell xrow xcol 'references (cons sym x))))
621 (ses-formula-record formula)
622 (ses-set-cell row col 'formula formula))))
624 (defun ses-calculate-cell (row col force)
625 "Calculate and print the value for cell (ROW,COL) using the cell's formula
626 function and print functions, if any. Result is nil for normal operation, or
627 the error signal if the formula or print function failed. The old value is
628 left unchanged if it was *skip* and the new value is nil.
629 Any cells that depend on this cell are queued for update after the end of
630 processing for the current keystroke, unless the new value is the same as
631 the old and FORCE is nil."
632 (let ((cell (ses-get-cell row col))
633 formula-error printer-error)
634 (let ((oldval (ses-cell-value cell))
635 (formula (ses-cell-formula cell))
637 (when (eq (car-safe formula) 'ses-safe-formula)
638 (setq formula (ses-safe-formula (cadr formula)))
639 (ses-set-cell row col 'formula formula))
641 (setq newval (eval formula))
643 (setq formula-error sig
645 (if (and (not newval) (eq oldval '*skip*))
646 ;;Don't lose the *skip* - previous field spans this one
647 (setq newval '*skip*))
648 (when (or force (not (eq newval oldval)))
649 (add-to-list 'ses--deferred-write (cons row col)) ;In case force=t
650 (ses-set-cell row col 'value newval)
651 (dolist (ref (ses-cell-references cell))
652 (add-to-list 'ses--deferred-recalc ref))))
653 (setq printer-error (ses-print-cell row col))
654 (or formula-error printer-error)))
656 (defun ses-clear-cell (row col)
657 "Delete formula and printer for cell (ROW,COL)."
658 (ses-set-cell row col 'printer nil)
659 (ses-cell-set-formula row col nil))
661 (defun ses-update-cells (list &optional force)
662 "Recalculate cells in LIST, checking for dependency loops. Prints
663 progress messages every second. Dependent cells are not recalculated
664 if the cell's value is unchanged and FORCE is nil."
665 (let ((ses--deferred-recalc list)
668 curlist prevlist rowcol formula)
669 (with-temp-message " "
670 (while (and ses--deferred-recalc (not (equal nextlist prevlist)))
671 ;;In each loop, recalculate cells that refer only to other cells that
672 ;;have already been recalculated or aren't in the recalculation
673 ;;region. Repeat until all cells have been processed or until the
674 ;;set of cells being worked on stops changing.
676 (message "Recalculating... (%d cells left)"
677 (length ses--deferred-recalc)))
678 (setq curlist ses--deferred-recalc
679 ses--deferred-recalc nil
682 (setq rowcol (ses-sym-rowcol (car curlist))
683 formula (ses-cell-formula (car rowcol) (cdr rowcol)))
685 (dolist (ref (ses-formula-references formula))
686 (when (or (memq ref curlist)
687 (memq ref ses--deferred-recalc))
688 ;;This cell refers to another that isn't done yet
689 (add-to-list 'ses--deferred-recalc (car curlist))
691 ;;ses-update-cells is called from post-command-hook, so
692 ;;inhibit-quit is implicitly bound to t.
694 ;;Abort the recalculation. User will probably undo now.
696 (ses-calculate-cell (car rowcol) (cdr rowcol) force))
697 (setq curlist (cdr curlist)))
698 (dolist (ref ses--deferred-recalc)
699 (add-to-list 'nextlist ref))
700 (setq nextlist (sort (copy-sequence nextlist) 'string<))
701 (if (equal nextlist prevlist)
702 ;;We'll go around the loop one more time.
703 (add-to-list 'nextlist t)))
704 (when ses--deferred-recalc
705 ;;Just couldn't finish these
706 (dolist (x ses--deferred-recalc)
707 (let ((rowcol (ses-sym-rowcol x)))
708 (ses-set-cell (car rowcol) (cdr rowcol) 'value '*error*)
709 (1value (ses-print-cell (car rowcol) (cdr rowcol)))))
710 (error "Circular references: %s" ses--deferred-recalc))
712 ;;Can't use save-excursion here: if the cell under point is
713 ;;updated, save-excusion's marker will move past the cell.
717 ;;----------------------------------------------------------------------------
719 ;;----------------------------------------------------------------------------
721 (defun ses-in-print-area ()
722 "Returns t if point is in print area of spreadsheet."
723 (<= (point) ses--data-marker))
725 ;;We turn off point-motion-hooks and explicitly position the cursor, in case
726 ;;the intangible properties have gotten screwed up (e.g., when
727 ;;ses-goto-print is called during a recursive ses-print-cell).
728 (defun ses-goto-print (row col)
729 "Move point to print area for cell (ROW,COL)."
730 (let ((inhibit-point-motion-hooks t)
732 (goto-char (point-min))
734 ;; calculate column position
736 (setq n (+ n (ses-col-width c) 1)))
737 ;; move to the position
738 (and (> n (move-to-column n))
740 ;; move point to the bol of next line (for TAB at the last cell)
743 (defun ses-set-curcell ()
744 "Sets `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
745 region, or nil if cursor is not at a cell."
746 (if (or (not mark-active)
748 (= (region-beginning) (region-end)))
750 (setq ses--curcell (get-text-property (point) 'intangible))
752 (let ((bcell (get-text-property (region-beginning) 'intangible))
753 (ecell (get-text-property (1- (region-end)) 'intangible)))
754 (when (= (region-end) ses--data-marker)
755 ;;Correct for overflow
756 (setq ecell (get-text-property (- (region-end) 2) 'intangible)))
757 (setq ses--curcell (if (and bcell ecell)
762 (defun ses-check-curcell (&rest args)
763 "Signal an error if ses--curcell is inappropriate. The end marker is
764 appropriate if some argument is 'end. A range is appropriate if some
765 argument is 'range. A single cell is appropriate unless some argument is
767 (if (eq ses--curcell t)
768 ;;curcell recalculation was postponed, but user typed ahead
773 (error "Not at cell")))
774 ((consp ses--curcell)
775 (or (memq 'range args)
776 (memq 'needrange args)
777 (error "Can't use a range")))
778 ((memq 'needrange args)
779 (error "Need a range"))))
781 (defun ses-print-cell (row col)
782 "Format and print the value of cell (ROW,COL) to the print area.
783 Use the cell's printer function. If the cell's new print form is too wide,
784 it will spill over into the following cell, but will not run off the end of the
785 row or overwrite the next non-nil field. Result is nil for normal operation,
786 or the error signal if the printer function failed and the cell was formatted
787 with \"%s\". If the cell's value is *skip*, nothing is printed because the
788 preceding cell has spilled over."
789 (catch 'ses-print-cell
790 (let* ((cell (ses-get-cell row col))
791 (value (ses-cell-value cell))
792 (printer (ses-cell-printer cell))
795 ;;Create the string to print
798 ;;Don't print anything
799 (throw 'ses-print-cell nil))
801 (setq text (make-string (ses-col-width col) ?#)))
803 ;;Deferred safety-check on printer
804 (if (eq (car-safe printer) 'ses-safe-printer)
805 (ses-set-cell row col 'printer
806 (setq printer (ses-safe-printer (cadr printer)))))
808 (setq text (ses-call-printer (or printer
809 (ses-col-printer col)
810 ses--default-printer)
812 (if (consp ses-call-printer-return)
813 ;;Printer returned an error
814 (setq sig ses-call-printer-return))))
815 ;;Adjust print width to match column width
816 (let ((width (ses-col-width col))
817 (len (string-width text)))
820 ;;Fill field to length with spaces
821 (setq len (make-string (- width len) ?\s)
822 text (if (eq ses-call-printer-return t)
826 ;;Spill over into following cells, if possible
827 (let ((maxwidth width))
828 (while (and (> len maxwidth)
829 (< maxcol ses--numcols)
830 (or (not (setq x (ses-cell-value row maxcol)))
833 ;;Set this cell to '*skip* so it won't overwrite our spillover
834 (ses-set-cell row maxcol 'value '*skip*))
835 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
837 (if (<= len maxwidth)
838 ;;Fill to complete width of all the fields spanned
839 (setq text (concat text (make-string (- maxwidth len) ?\s)))
840 ;;Not enough room to end of line or next non-nil field. Truncate
841 ;;if string or decimal; otherwise fill with error indicator
842 (setq sig `(error "Too wide" ,text))
845 (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
846 ((and (numberp value)
847 (string-match "\\.[0-9]+" text)
850 (- (match-end 0) (match-beginning 0))))))
851 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
852 (setq text (concat (substring text
854 (- (match-beginning 0) width))
855 (substring text (match-end 0)))))
857 (setq text (make-string maxwidth ?#)))))))))
858 ;;Substitute question marks for tabs and newlines. Newlines are
859 ;;used as row-separators; tabs could confuse the reimport logic.
860 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
861 (ses-goto-print row col)
862 (setq startpos (point))
863 ;;Install the printed result. This is not interruptible.
864 (let ((inhibit-read-only t)
866 (let ((inhibit-point-motion-hooks t))
867 (delete-region (point) (progn
868 (move-to-column (+ (current-column)
869 (string-width text)))
871 ;;We use concat instead of inserting separate strings in order to
872 ;;reduce the number of cells in the undo list.
873 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
874 ;;We use set-text-properties to prevent a wacky print function
875 ;;from inserting rogue properties, and to ensure that the keymap
876 ;;property is inherited (is it a bug that only unpropertied strings
877 ;;actually inherit from surrounding text?)
878 (set-text-properties 0 (length x) nil x)
879 (insert-and-inherit x)
880 (put-text-property startpos (point) 'intangible
881 (ses-cell-symbol cell))
882 (when (and (zerop row) (zerop col))
883 ;;Reconstruct special beginning-of-buffer attributes
884 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
885 (put-text-property (point-min) (point) 'read-only 'ses)
886 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)))
887 (if (= row (1- ses--header-row))
888 ;;This line is part of the header - force recalc
889 (ses-reset-header-string))
890 ;;If this cell (or a preceding one on the line) previously spilled over
891 ;;and has gotten shorter, redraw following cells on line recursively.
892 (when (and (< maxcol ses--numcols)
893 (eq (ses-cell-value row maxcol) '*skip*))
894 (ses-set-cell row maxcol 'value nil)
895 (ses-print-cell row maxcol))
896 ;;Return to start of cell
900 (defun ses-call-printer (printer &optional value)
901 "Invokes PRINTER (a string or parenthesized string or function-symbol or
902 lambda of one argument) on VALUE. Result is the printed cell as a string.
903 The variable `ses-call-printer-return' is set to t if the printer used
904 parenthesis to request left-justification, or the error-signal if the
905 printer signaled one (and \"%s\" is used as the default printer), else nil."
906 (setq ses-call-printer-return nil)
909 (condition-case signal
912 (format printer value))
913 ((stringp (car-safe printer))
914 (setq ses-call-printer-return t)
915 (format (car printer) value))
917 (setq value (funcall printer value))
920 (or (stringp (car-safe value))
921 (error "Printer should return \"string\" or (\"string\")"))
922 (setq ses-call-printer-return t)
925 (setq ses-call-printer-return signal)
926 (prin1-to-string value t))))
928 (defun ses-adjust-print-width (col change)
929 "Insert CHANGE spaces in front of column COL, or at end of line if
930 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
932 (let ((inhibit-read-only t)
933 (blank (if (> change 0) (make-string change ?\s)))
934 (at-end (= col ses--numcols)))
935 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
936 ;;ses-set-with-undo always returns t for strings.
937 (1value (ses-set-with-undo 'ses--blank-line
938 (concat (make-string ses--linewidth ?\s) "\n")))
939 (dotimes (row ses--numrows)
940 (ses-goto-print row col)
942 ;;Insert new columns before newline
943 (let ((inhibit-point-motion-hooks t))
947 (delete-char (- change))))))
949 (defun ses-print-cell-new-width (row col)
950 "Same as ses-print-cell, except if the cell's value is *skip*, the preceding
951 nonskipped cell is reprinted. This function is used when the width of
952 cell (ROW,COL) has changed."
953 (if (not (eq (ses-cell-value row col) '*skip*))
954 (ses-print-cell row col)
955 ;;Cell was skipped over - reprint previous
956 (ses-goto-print row col)
958 (let ((rowcol (ses-sym-rowcol (get-text-property (point) 'intangible))))
959 (ses-print-cell (car rowcol) (cdr rowcol)))))
962 ;;----------------------------------------------------------------------------
964 ;;----------------------------------------------------------------------------
966 (defun ses-narrowed-p () (/= (- (point-max) (point-min)) (buffer-size)))
969 "Turn off narrowing, to be reenabled at end of command loop."
971 (setq ses--deferred-narrow t))
974 (defun ses-goto-data (def &optional col)
975 "Move point to data area for (DEF,COL). If DEF is a row
976 number, COL is the column number for a data cell -- otherwise DEF
977 is one of the symbols ses--col-widths, ses--col-printers,
978 ses--default-printer, ses--numrows, or ses--numcols."
980 (let ((inhibit-point-motion-hooks t)) ;In case intangible attrs are wrong
984 (goto-char ses--data-marker)
985 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
986 ;;Convert def-symbol to offset
987 (setq def (plist-get ses-paramlines-plist def))
988 (or def (signal 'args-out-of-range nil))
989 (goto-char ses--params-marker)
990 (forward-line def))))
992 (defun ses-set-parameter (def value &optional elem)
993 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
994 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
995 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
997 ;;We call ses-goto-data early, using the old values of numrows and
998 ;;numcols in case one of them is being changed.
1000 (let ((inhibit-read-only t)
1001 (fmt (plist-get '(ses--col-widths "(ses-column-widths %S)"
1002 ses--col-printers "(ses-column-printers %S)"
1003 ses--default-printer "(ses-default-printer %S)"
1004 ses--header-row "(ses-header-row %S)"
1005 ses--file-format " %S ;SES file-format"
1006 ses--numrows " %S ;numrows"
1007 ses--numcols " %S ;numcols")
1012 (setq oldval (aref (symbol-value def) elem))
1013 (aset (symbol-value def) elem value))
1014 (setq oldval (symbol-value def))
1016 ;;Special undo since it's outside the narrowed buffer
1017 (let (buffer-undo-list)
1018 (delete-region (point) (line-end-position))
1019 (insert (format fmt (symbol-value def))))
1020 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1023 (defun ses-write-cells ()
1024 "Write cells in `ses--deferred-write' from local variables to data area.
1025 Newlines in the data are escaped."
1026 (let* ((inhibit-read-only t)
1027 (print-escape-newlines t)
1028 rowcol row col cell sym formula printer text)
1029 (setq ses-start-time (float-time))
1030 (with-temp-message " "
1032 (while ses--deferred-write
1033 (ses-time-check "Writing... (%d cells left)"
1034 '(length ses--deferred-write))
1035 (setq rowcol (pop ses--deferred-write)
1038 cell (ses-get-cell row col)
1039 sym (ses-cell-symbol cell)
1040 formula (ses-cell-formula cell)
1041 printer (ses-cell-printer cell))
1042 (if (eq (car-safe formula) 'ses-safe-formula)
1043 (setq formula (cadr formula)))
1044 (if (eq (car-safe printer) 'ses-safe-printer)
1045 (setq printer (cadr printer)))
1046 ;;This is noticably faster than (format "%S %S %S %S %S")
1047 (setq text (concat "(ses-cell "
1050 (prin1-to-string (symbol-value sym))
1052 (prin1-to-string formula)
1054 (prin1-to-string printer)
1056 (if (atom (ses-cell-references cell))
1059 (mapconcat 'symbol-name
1060 (ses-cell-references cell)
1064 (ses-goto-data row col)
1065 (delete-region (point) (line-end-position))
1070 ;;----------------------------------------------------------------------------
1071 ;; Formula relocation
1072 ;;----------------------------------------------------------------------------
1074 (defun ses-formula-references (formula &optional result-so-far)
1075 "Produce a list of symbols for cells that this formula's value
1076 refers to. For recursive calls, RESULT-SO-FAR is the list being constructed,
1077 or t to get a wrong-type-argument error when the first reference is found."
1079 (if (ses-sym-rowcol formula)
1080 ;;Entire formula is one symbol
1081 (add-to-list 'result-so-far formula)
1082 ) ;;Ignore other atoms
1083 (dolist (cur formula)
1085 ((ses-sym-rowcol cur)
1086 ;;Save this reference
1087 (add-to-list 'result-so-far cur))
1088 ((eq (car-safe cur) 'ses-range)
1089 ;;All symbols in range are referenced
1090 (dolist (x (cdr (macroexpand cur)))
1091 (add-to-list 'result-so-far x)))
1092 ((and (consp cur) (not (eq (car cur) 'quote)))
1093 ;;Recursive call for subformulas
1094 (setq result-so-far (ses-formula-references cur result-so-far)))
1096 ;;Ignore other stuff
1100 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1101 "Relocate one symbol SYM, whichs corresponds to ROWCOL (a cons of ROW and
1102 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1103 by (ROWINCR,COLINCR)."
1104 (let ((row (car rowcol))
1106 (if (or (< row startrow) (< col startcol))
1108 (setq row (+ row rowincr)
1109 col (+ col colincr))
1110 (if (and (>= row startrow) (>= col startcol)
1111 (< row ses--numrows) (< col ses--numcols))
1112 ;;Relocate this variable
1113 (ses-create-cell-symbol row col)
1114 ;;Delete reference to a deleted cell
1117 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1118 "Produce a copy of FORMULA where all symbols that refer to cells in row
1119 STARTROW or above and col STARTCOL or above are altered by adding ROWINCR
1120 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1121 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1123 If ROWINCR or COLINCR is negative, references to cells being deleted are
1125 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1127 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1128 (let (rowcol result)
1129 (if (or (atom formula) (eq (car formula) 'quote))
1130 (if (setq rowcol (ses-sym-rowcol formula))
1131 (ses-relocate-symbol formula rowcol
1132 startrow startcol rowincr colincr)
1133 formula) ;Pass through as-is
1134 (dolist (cur formula)
1135 (setq rowcol (ses-sym-rowcol cur))
1138 (setq cur (ses-relocate-symbol cur rowcol
1139 startrow startcol rowincr colincr))
1142 ;;Reference to a deleted cell. Set a flag in ses-relocate-return.
1143 ;;don't change the flag if it's already 'range, since range
1145 (unless ses-relocate-return
1146 (setq ses-relocate-return 'delete))))
1147 ((eq (car-safe cur) 'ses-range)
1148 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1151 ((or (atom cur) (eq (car cur) 'quote))
1152 ;;Constants pass through unchanged
1155 ;;Recursively copy and alter subformulas
1156 (push (ses-relocate-formula cur startrow startcol
1159 (nreverse result))))
1161 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1162 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1163 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1164 new range, or nil if the entire range is deleted. If new rows are being added
1165 just beyond the end of a row range, or new columns just beyond a column range,
1166 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1167 if the range was altered."
1168 (let* ((minorig (cadr range))
1169 (minrowcol (ses-sym-rowcol minorig))
1170 (min (ses-relocate-symbol minorig minrowcol
1173 (maxorig (nth 2 range))
1174 (maxrowcol (ses-sym-rowcol maxorig))
1175 (max (ses-relocate-symbol maxorig maxrowcol
1180 ((and (not min) (not max))
1181 (setq range nil)) ;;The entire range is deleted
1183 ;;Inserting or deleting rows
1186 ;;Chopped off beginning of range
1187 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1188 ses-relocate-return 'range))
1191 ;;Trying to insert a nonexistent row
1192 (setq max (ses-create-cell-symbol (1- ses--numrows)
1194 ;;End of range is being deleted
1195 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1196 ses-relocate-return 'range))
1198 (= (car maxrowcol) (1- startrow))
1199 (= (cdr minrowcol) (cdr maxrowcol))
1200 ;;Insert after ending row of vertical range - include it
1201 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1202 (cdr maxrowcol))))))
1204 ;;Inserting or deleting columns
1207 ;;Chopped off beginning of range
1208 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1209 ses-relocate-return 'range))
1212 ;;Trying to insert a nonexistent column
1213 (setq max (ses-create-cell-symbol (car maxrowcol)
1215 ;;End of range is being deleted
1216 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1217 ses-relocate-return 'range))
1219 (= (cdr maxrowcol) (1- startcol))
1220 (= (car minrowcol) (car maxrowcol))
1221 ;;Insert after ending column of horizontal range - include it
1222 (setq max (ses-create-cell-symbol (car maxrowcol)
1223 (+ startcol colincr -1)))))))
1225 (if (/= (- (funcall field maxrowcol)
1226 (funcall field minrowcol))
1227 (- (funcall field (ses-sym-rowcol max))
1228 (funcall field (ses-sym-rowcol min))))
1229 ;;This range has changed size
1230 (setq ses-relocate-return 'range))
1231 (list 'ses-range min max))))
1233 (defun ses-relocate-all (minrow mincol rowincr colincr)
1234 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1235 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1238 (let (mycell newval)
1239 (dotimes-with-progress-reporter
1240 (row ses--numrows) "Relocating formulas..."
1241 (dotimes (col ses--numcols)
1242 (setq ses-relocate-return nil
1243 mycell (ses-get-cell row col)
1244 newval (ses-relocate-formula (ses-cell-formula mycell)
1245 minrow mincol rowincr colincr))
1246 (ses-set-cell row col 'formula newval)
1247 (if (eq ses-relocate-return 'range)
1248 ;;This cell contains a (ses-range X Y) where a cell has been
1249 ;;inserted or deleted in the middle of the range.
1250 (push (cons row col) reform))
1251 (if ses-relocate-return
1252 ;;This cell referred to a cell that's been deleted or is no
1253 ;;longer part of the range. We can't fix that now because
1254 ;;reference lists cells have been partially updated.
1255 (add-to-list 'ses--deferred-recalc
1256 (ses-create-cell-symbol row col)))
1257 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1258 minrow mincol rowincr colincr))
1259 (ses-set-cell row col 'references newval)
1260 (and (>= row minrow) (>= col mincol)
1261 (ses-set-cell row col 'symbol
1262 (ses-create-cell-symbol row col))))))
1263 ;;Relocate the cell values
1264 (let (oldval myrow mycol xrow xcol)
1266 ((and (<= rowincr 0) (<= colincr 0))
1267 ;;Deletion of rows and/or columns
1268 (dotimes-with-progress-reporter
1269 (row (- ses--numrows minrow)) "Relocating variables..."
1270 (setq myrow (+ row minrow))
1271 (dotimes (col (- ses--numcols mincol))
1272 (setq mycol (+ col mincol)
1273 xrow (- myrow rowincr)
1274 xcol (- mycol colincr))
1275 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1276 (setq oldval (ses-cell-value xrow xcol))
1277 ;;Cell is off the end of the array
1278 (setq oldval (symbol-value (ses-create-cell-symbol xrow xcol))))
1279 (ses-set-cell myrow mycol 'value oldval))))
1280 ((and (wholenump rowincr) (wholenump colincr))
1281 ;;Insertion of rows and/or columns. Run the loop backwards.
1282 (let ((disty (1- ses--numrows))
1283 (distx (1- ses--numcols))
1285 (dotimes-with-progress-reporter
1286 (row (- ses--numrows minrow)) "Relocating variables..."
1287 (setq myrow (- disty row))
1288 (dotimes (col (- ses--numcols mincol))
1289 (setq mycol (- distx col)
1290 xrow (- myrow rowincr)
1291 xcol (- mycol colincr))
1292 (if (or (< xrow minrow) (< xcol mincol))
1293 ;;Newly-inserted value
1295 ;;Transfer old value
1296 (setq oldval (ses-cell-value xrow xcol)))
1297 (ses-set-cell myrow mycol 'value oldval)))
1298 t)) ;Make testcover happy by returning non-nil here
1300 (error "ROWINCR and COLINCR must have the same sign"))))
1301 ;;Reconstruct reference lists for cells that contain ses-ranges that
1302 ;;have changed size.
1304 (message "Fixing ses-ranges...")
1306 (setq ses-start-time (float-time))
1308 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1309 (setq row (caar reform)
1311 reform (cdr reform))
1312 (ses-cell-set-formula row col (ses-cell-formula row col))))
1316 ;;----------------------------------------------------------------------------
1318 ;;----------------------------------------------------------------------------
1320 (defun ses-begin-change ()
1321 "For undo, remember point before we start changing hidden stuff."
1322 (let ((inhibit-read-only t))
1323 (insert-and-inherit "X")
1324 (delete-region (1- (point)) (point))))
1326 (defun ses-set-with-undo (sym newval)
1327 "Like set, but undoable. Result is t if value has changed."
1328 ;;We try to avoid adding redundant entries to the undo list, but this is
1329 ;;unavoidable for strings because equal ignores text properties and there's
1330 ;;no easy way to get the whole property list to see if it's different!
1331 (unless (and (boundp sym)
1332 (equal (symbol-value sym) newval)
1333 (not (stringp newval)))
1334 (push (if (boundp sym)
1335 `(apply ses-set-with-undo ,sym ,(symbol-value sym))
1336 `(apply ses-unset-with-undo ,sym))
1341 (defun ses-unset-with-undo (sym)
1342 "Set SYM to be unbound. This is undoable."
1343 (when (1value (boundp sym)) ;;Always bound, except after a programming error
1344 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
1347 (defun ses-aset-with-undo (array idx newval)
1348 "Like aset, but undoable. Result is t if element has changed"
1349 (unless (equal (aref array idx) newval)
1350 (push `(apply ses-aset-with-undo ,array ,idx ,(aref array idx)) buffer-undo-list)
1351 (aset array idx newval)
1355 ;;----------------------------------------------------------------------------
1356 ;; Startup for major mode
1357 ;;----------------------------------------------------------------------------
1360 "Parse the current buffer and sets up buffer-local variables. Does not
1361 execute cell formulas or print functions."
1363 ;;Read our global parameters, which should be a 3-element list
1364 (goto-char (point-max))
1365 (search-backward ";; Local Variables:\n" nil t)
1367 (setq ses--params-marker (point-marker))
1368 (let ((params (condition-case nil (read (current-buffer)) (error nil))))
1369 (or (and (= (safe-length params) 3)
1370 (numberp (car params))
1371 (numberp (cadr params))
1372 (>= (cadr params) 0)
1373 (numberp (nth 2 params))
1374 (> (nth 2 params) 0))
1375 (error "Invalid SES file"))
1376 (setq ses--file-format (car params)
1377 ses--numrows (cadr params)
1378 ses--numcols (nth 2 params))
1379 (when (= ses--file-format 1)
1380 (let (buffer-undo-list) ;This is not undoable
1381 (ses-goto-data 'ses--header-row)
1382 (insert "(ses-header-row 0)\n")
1383 (ses-set-parameter 'ses--file-format 2)
1384 (message "Upgrading from SES-1 file format")))
1385 (or (= ses--file-format 2)
1386 (error "This file needs a newer version of the SES library code"))
1387 (ses-create-cell-variable-range 0 (1- ses--numrows) 0 (1- ses--numcols))
1388 ;;Initialize cell array
1389 (setq ses--cells (make-vector ses--numrows nil))
1390 (dotimes (row ses--numrows)
1391 (aset ses--cells row (make-vector ses--numcols nil))))
1392 ;;Skip over print area, which we assume is correct
1393 (goto-char (point-min))
1394 (forward-line ses--numrows)
1395 (or (looking-at ses-print-data-boundary)
1396 (error "Missing marker between print and data areas"))
1398 (setq ses--data-marker (point-marker))
1399 (forward-char (1- (length ses-print-data-boundary)))
1400 ;;Initialize printer and symbol lists
1401 (mapc 'ses-printer-record ses-standard-printer-functions)
1402 (setq ses--symbolic-formulas nil)
1403 ;;Load cell definitions
1404 (dotimes (row ses--numrows)
1405 (dotimes (col ses--numcols)
1406 (let* ((x (read (current-buffer)))
1407 (rowcol (ses-sym-rowcol (car-safe (cdr-safe x)))))
1408 (or (and (looking-at "\n")
1409 (eq (car-safe x) 'ses-cell)
1410 (eq row (car rowcol))
1411 (eq col (cdr rowcol)))
1412 (error "Cell-def error"))
1414 (or (looking-at "\n\n")
1415 (error "Missing blank line between rows")))
1416 ;;Load global parameters
1417 (let ((widths (read (current-buffer)))
1418 (n1 (char-after (point)))
1419 (printers (read (current-buffer)))
1420 (n2 (char-after (point)))
1421 (def-printer (read (current-buffer)))
1422 (n3 (char-after (point)))
1423 (head-row (read (current-buffer)))
1424 (n4 (char-after (point))))
1425 (or (and (eq (car-safe widths) 'ses-column-widths)
1427 (eq (car-safe printers) 'ses-column-printers)
1429 (eq (car-safe def-printer) 'ses-default-printer)
1431 (eq (car-safe head-row) 'ses-header-row)
1433 (error "Invalid SES global parameters"))
1434 (1value (eval widths))
1435 (1value (eval def-printer))
1436 (1value (eval printers))
1437 (1value (eval head-row)))
1438 ;;Should be back at global-params
1440 (or (looking-at (replace-regexp-in-string "1" "[0-9]+"
1441 ses-initial-global-parameters))
1442 (error "Problem with column-defs or global-params"))
1443 ;;Check for overall newline count in definitions area
1445 (let ((start (point)))
1446 (ses-goto-data 'ses--numrows)
1447 (or (= (point) start)
1448 (error "Extraneous newlines someplace?"))))
1451 "Set up for display of only the printed cell values.
1453 Narrows the buffer to show only the print area. Gives it `read-only' and
1454 `intangible' properties. Sets up highlighting for current cell."
1456 (let ((end (point-min))
1457 (inhibit-read-only t)
1458 (inhibit-point-motion-hooks t)
1459 (was-modified (buffer-modified-p))
1461 (ses-goto-data 0 0) ;;Include marker between print-area and data-area
1462 (set-text-properties (point) (point-max) nil) ;Delete garbage props
1463 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1464 ;;The print area is read-only (except for our special commands) and uses a
1466 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1467 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1468 ;;For the beginning of the buffer, we want the read-only and keymap
1469 ;;attributes to be inherited from the first character
1470 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1471 ;;Create intangible properties, which also indicate which cell the text
1473 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1474 (dotimes (col ses--numcols)
1476 sym (ses-cell-symbol row col))
1477 ;;Include skipped cells following this one
1478 (while (and (< col (1- ses--numcols))
1479 (eq (ses-cell-value row (1+ col)) '*skip*))
1480 (setq end (+ end (ses-col-width col) 1)
1482 (setq end (save-excursion
1484 (move-to-column (+ (current-column) (- end pos)
1485 (ses-col-width col)))
1487 (+ end (ses-col-width col) 1)
1490 (put-text-property pos end 'intangible sym)))
1491 ;;Adding these properties did not actually alter the text
1492 (unless was-modified
1493 (restore-buffer-modified-p nil)
1494 (buffer-disable-undo)
1495 (buffer-enable-undo)))
1496 ;;Create the underlining overlay. It's impossible for (point) to be 2,
1497 ;;because column A must be at least 1 column wide.
1498 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1499 (overlay-put ses--curcell-overlay 'face 'underline))
1501 (defun ses-cleanup ()
1502 "Cleanup when changing a buffer from SES mode to something else.
1503 Delete overlays, remove special text properties."
1505 (let ((inhibit-read-only t)
1506 ;; When reverting, hide the buffer name, otherwise Emacs will ask
1507 ;; the user "the file is modified, do you really want to make
1508 ;; modifications to this buffer", where the "modifications" refer to
1509 ;; the irrelevant set-text-properties below.
1510 (buffer-file-name nil)
1511 (was-modified (buffer-modified-p)))
1512 ;;Delete read-only, keymap, and intangible properties
1513 (set-text-properties (point-min) (point-max) nil)
1515 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1516 (unless was-modified
1517 (restore-buffer-modified-p nil))))
1521 "Major mode for Simple Emacs Spreadsheet.
1522 See \"ses-example.ses\" (in `data-directory') for more info.
1526 These key definitions are active only in the print area (the visible part):
1527 \\{ses-mode-print-map}
1528 These are active only in the minibuffer, when entering or editing a formula:
1529 \\{ses-mode-edit-map}"
1531 (unless (and (boundp 'ses--deferred-narrow)
1532 (eq ses--deferred-narrow 'ses-mode))
1533 (kill-all-local-variables)
1534 (mapc 'make-local-variable ses-localvars)
1535 (setq major-mode 'ses-mode
1537 next-line-add-newlines nil
1539 ;;SES deliberately puts lots of trailing whitespace in its buffer
1540 show-trailing-whitespace nil
1541 ;;Cell ranges do not work reasonably without this
1542 transient-mark-mode t
1543 ;;not to use tab characters for safe
1544 ;;(tabs may do bad for column calculation)
1545 indent-tabs-mode nil)
1546 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1547 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1548 (setq ses--curcell nil
1549 ses--deferred-recalc nil
1550 ses--deferred-write nil
1551 ses--header-hscroll -1 ;Flag for "initial recalc needed"
1552 header-line-format '(:eval (progn
1553 (when (/= (window-hscroll)
1554 ses--header-hscroll)
1555 ;;Reset ses--header-hscroll first, to
1556 ;;avoid recursion problems when
1557 ;;debugging ses-create-header-string
1558 (setq ses--header-hscroll
1560 (ses-create-header-string))
1561 ses--header-string)))
1562 (let ((was-empty (zerop (buffer-size)))
1563 (was-modified (buffer-modified-p)))
1566 ;;Initialize buffer to contain one cell, for now
1567 (insert ses-initial-file-contents))
1571 (unless (equal ses-initial-default-printer (1value ses--default-printer))
1572 (1value (ses-read-default-printer ses-initial-default-printer)))
1573 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1574 (1value (ses-set-column-width 0 ses-initial-column-width)))
1576 (if (> (car ses-initial-size) (1value ses--numrows))
1577 (1value (ses-insert-row (1- (car ses-initial-size)))))
1578 (if (> (cdr ses-initial-size) (1value ses--numcols))
1579 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1581 (restore-buffer-modified-p was-modified)
1582 (buffer-disable-undo)
1583 (buffer-enable-undo)
1584 (goto-char (point-min))))
1585 (use-local-map ses-mode-map)
1586 ;;Set the deferred narrowing flag (we can't narrow until after
1587 ;;after-find-file completes). If .ses is on the auto-load alist and the
1588 ;;file has "mode: ses", our ses-mode function will be called twice! Use
1589 ;;a special flag to detect this (will be reset by ses-command-hook).
1590 ;;For find-alternate-file, post-command-hook doesn't get run for some
1591 ;;reason, so use an idle timer to make sure.
1592 (setq ses--deferred-narrow 'ses-mode)
1593 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1594 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1595 (run-mode-hooks 'ses-mode-hook)))
1597 (put 'ses-mode 'mode-class 'special)
1599 (defun ses-command-hook ()
1600 "Invoked from `post-command-hook'. If point has moved to a different cell,
1601 moves the underlining overlay. Performs any recalculations or cell-data
1602 writes that have been deferred. If buffer-narrowing has been deferred,
1603 narrows the buffer now."
1605 (when (eq major-mode 'ses-mode) ;Otherwise, not our buffer anymore
1606 (when ses--deferred-recalc
1607 ;;We reset the deferred list before starting on the recalc -- in case
1608 ;;of error, we don't want to retry the recalc after every keystroke!
1609 (let ((old ses--deferred-recalc))
1610 (setq ses--deferred-recalc nil)
1611 (ses-update-cells old)))
1612 (when ses--deferred-write
1613 ;;We don't reset the deferred list before starting -- the most
1614 ;;likely error is keyboard-quit, and we do want to keep trying
1615 ;;these writes after a quit.
1617 (push '(apply ses-widen) buffer-undo-list))
1618 (when ses--deferred-narrow
1619 ;;We're not allowed to narrow the buffer until after-find-file has
1620 ;;read the local variables at the end of the file. Now it's safe to
1622 (narrow-to-region (point-min) ses--data-marker)
1623 (setq ses--deferred-narrow nil))
1624 ;;Update the modeline
1625 (let ((oldcell ses--curcell))
1627 (unless (eq ses--curcell oldcell)
1630 (setq mode-line-process nil))
1631 ((atom ses--curcell)
1632 (setq mode-line-process (list " cell "
1633 (symbol-name ses--curcell))))
1635 (setq mode-line-process (list " range "
1636 (symbol-name (car ses--curcell))
1638 (symbol-name (cdr ses--curcell))))))
1639 (force-mode-line-update)))
1640 ;;Use underline overlay for single-cells only, turn off otherwise
1641 (if (listp ses--curcell)
1642 (move-overlay ses--curcell-overlay 2 2)
1643 (let ((next (next-single-property-change (point) 'intangible)))
1644 (move-overlay ses--curcell-overlay (point) (1- next))))
1645 (when (not (pos-visible-in-window-p))
1646 ;;Scrolling will happen later
1647 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1648 (setq ses--curcell t)))
1649 ;;Prevent errors in this post-command-hook from silently erasing the hook!
1651 (unless executing-kbd-macro
1653 (message "%s" (error-message-string err))))
1654 nil) ;Make coverage-tester happy
1656 (defun ses-create-header-string ()
1657 "Set up `ses--header-string' as the buffer's header line.
1658 Based on the current set of columns and `window-hscroll' position."
1659 (let ((totwidth (- (window-hscroll)))
1661 ;;Leave room for the left-side fringe and scrollbar
1662 (push (propertize " " 'display '((space :align-to 0))) result)
1663 (dotimes (col ses--numcols)
1664 (setq width (ses-col-width col)
1665 totwidth (+ totwidth width 1))
1667 ;;Scrolled so intercolumn space is leftmost
1669 (when (> totwidth 1)
1670 (if (> ses--header-row 0)
1672 (ses-goto-print (1- ses--header-row) col)
1673 (setq x (buffer-substring-no-properties (point)
1675 ;; Strip trailing space.
1676 (if (string-match "[ \t]+\\'" x)
1677 (setq x (substring x 0 (match-beginning 0))))
1678 ;; Cut off excess text.
1679 (if (>= (length x) totwidth)
1680 (setq x (substring x 0 (- totwidth -1)))))
1681 (setq x (ses-column-letter col)))
1682 (push (propertize x 'face ses-box-prop) result)
1683 (push (propertize "."
1684 'display `((space :align-to ,(1- totwidth)))
1687 ;;Allow the following space to be squished to make room for the 3-D box
1688 ;;Coverage test ignores properties, thinks this is always a space!
1689 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
1691 (if (> ses--header-row 0)
1692 (push (propertize (format " [row %d]" ses--header-row)
1693 'display '((height (- 1))))
1695 (setq ses--header-string (apply 'concat (nreverse result)))))
1698 ;;----------------------------------------------------------------------------
1699 ;; Redisplay and recalculation
1700 ;;----------------------------------------------------------------------------
1702 (defun ses-jump (sym)
1703 "Move point to cell SYM."
1704 (interactive "SJump to cell: ")
1705 (let ((rowcol (ses-sym-rowcol sym)))
1706 (or rowcol (error "Invalid cell name"))
1707 (if (eq (symbol-value sym) '*skip*)
1708 (error "Cell is covered by preceding cell"))
1709 (ses-goto-print (car rowcol) (cdr rowcol))))
1711 (defun ses-jump-safe (cell)
1712 "Like `ses-jump', but no error if invalid cell."
1717 (defun ses-reprint-all (&optional nonarrow)
1718 "Recreate the display area. Calls all printer functions. Narrows to
1719 print area if NONARROW is nil."
1723 (setq ses--deferred-narrow t))
1724 (let ((startcell (get-text-property (point) 'intangible))
1725 (inhibit-read-only t))
1727 (goto-char (point-min))
1728 (search-forward ses-print-data-boundary)
1729 (backward-char (length ses-print-data-boundary))
1730 (delete-region (point-min) (point))
1731 ;;Insert all blank lines before printing anything, so ses-print-cell can
1732 ;;find the data area when inserting or deleting *skip* values for cells
1733 (dotimes (row ses--numrows)
1734 (insert-and-inherit ses--blank-line))
1735 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
1736 (if (eq (ses-cell-value row 0) '*skip*)
1737 ;;Column deletion left a dangling skip
1738 (ses-set-cell row 0 'value nil))
1739 (dotimes (col ses--numcols)
1740 (ses-print-cell row col))
1741 (beginning-of-line 2))
1742 (ses-jump-safe startcell)))
1744 (defun ses-recalculate-cell ()
1745 "Recalculate and reprint the current cell or range.
1747 For an individual cell, shows the error if the formula or printer
1748 signals one, or otherwise shows the cell's complete value. For a range, the
1749 cells are recalculated in \"natural\" order, so cells that other cells refer
1750 to are recalculated first."
1752 (ses-check-curcell 'range)
1755 (setq ses-start-time (float-time))
1756 (if (atom ses--curcell)
1757 (setq sig (ses-sym-rowcol ses--curcell)
1758 sig (ses-calculate-cell (car sig) (cdr sig) t))
1759 ;;First, recalculate all cells that don't refer to other cells and
1760 ;;produce a list of cells with references.
1761 (ses-dorange ses--curcell
1762 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
1765 ;;The t causes an error if the cell has references.
1766 ;;If no references, the t will be the result value.
1767 (1value (ses-formula-references (ses-cell-formula row col) t))
1768 (setq sig (ses-calculate-cell row col t)))
1769 (wrong-type-argument
1770 ;;The formula contains a reference
1771 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
1772 ;;Do the update now, so we can force recalculation
1773 (let ((x ses--deferred-recalc))
1774 (setq ses--deferred-recalc nil)
1775 (condition-case hold
1776 (ses-update-cells x t)
1777 (error (setq sig hold))))
1780 (message "%s" (error-message-string sig)))
1781 ((consp ses--curcell)
1784 (princ (symbol-value ses--curcell))))))
1786 (defun ses-recalculate-all ()
1787 "Recalculate and reprint all cells."
1789 (let ((startcell (get-text-property (point) 'intangible))
1790 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
1791 (1- ses--numcols)))))
1792 (ses-recalculate-cell)
1793 (ses-jump-safe startcell)))
1795 (defun ses-truncate-cell ()
1796 "Reprint current cell, but without spillover into any following blank
1800 (let* ((rowcol (ses-sym-rowcol ses--curcell))
1803 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
1804 (eq (ses-cell-value row (1+ col)) '*skip*))
1805 ;;This cell has spill-over. We'll momentarily pretend the following
1806 ;;cell has a `t' in it.
1807 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
1808 (ses-print-cell row col)))
1809 ;;Now remove the *skip*. ses-print-cell is always nil here
1810 (ses-set-cell row (1+ col) 'value nil)
1811 (1value (ses-print-cell row (1+ col))))))
1813 (defun ses-reconstruct-all ()
1814 "Reconstruct buffer based on cell data stored in Emacs variables."
1817 ;;Reconstruct reference lists.
1819 ;;Delete old reference lists
1820 (dotimes-with-progress-reporter
1821 (row ses--numrows) "Deleting references..."
1822 (dotimes (col ses--numcols)
1823 (ses-set-cell row col 'references nil)))
1824 ;;Create new reference lists
1825 (dotimes-with-progress-reporter
1826 (row ses--numrows) "Computing references..."
1827 (dotimes (col ses--numcols)
1828 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
1829 (setq x (ses-sym-rowcol ref)
1832 (ses-set-cell yrow ycol 'references
1833 (cons (ses-cell-symbol row col)
1834 (ses-cell-references yrow ycol)))))))
1835 ;;Delete everything and reconstruct basic data area
1837 (let ((inhibit-read-only t))
1838 (goto-char (point-max))
1839 (if (search-backward ";; Local Variables:\n" nil t)
1840 (delete-region (point-min) (point))
1841 ;;Buffer is quite screwed up - can't even save the user-specified locals
1842 (delete-region (point-min) (point-max))
1843 (insert ses-initial-file-trailer)
1844 (goto-char (point-min)))
1845 ;;Create a blank display area
1846 (dotimes (row ses--numrows)
1847 (insert ses--blank-line))
1848 (insert ses-print-data-boundary)
1849 (backward-char (1- (length ses-print-data-boundary)))
1850 (setq ses--data-marker (point-marker))
1851 (forward-char (1- (length ses-print-data-boundary)))
1852 ;;Placeholders for cell data
1853 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
1854 ;;Placeholders for col-widths, col-printers, default-printer, header-row
1856 (insert ses-initial-global-parameters)
1857 (backward-char (1- (length ses-initial-global-parameters)))
1858 (setq ses--params-marker (point-marker))
1859 (forward-char (1- (length ses-initial-global-parameters))))
1860 (ses-set-parameter 'ses--col-widths ses--col-widths)
1861 (ses-set-parameter 'ses--col-printers ses--col-printers)
1862 (ses-set-parameter 'ses--default-printer ses--default-printer)
1863 (ses-set-parameter 'ses--header-row ses--header-row)
1864 (ses-set-parameter 'ses--numrows ses--numrows)
1865 (ses-set-parameter 'ses--numcols ses--numcols)
1866 ;;Keep our old narrowing
1868 (ses-recalculate-all)
1869 (goto-char (point-min)))
1872 ;;----------------------------------------------------------------------------
1873 ;; Input of cell formulas
1874 ;;----------------------------------------------------------------------------
1876 (defun ses-edit-cell (row col newval)
1877 "Display current cell contents in minibuffer, for editing. Returns nil if
1878 cell formula was unsafe and user declined confirmation."
1881 (barf-if-buffer-read-only)
1883 (let* ((rowcol (ses-sym-rowcol ses--curcell))
1886 (formula (ses-cell-formula row col))
1888 (if (eq (car-safe formula) 'ses-safe-formula)
1889 (setq formula (cadr formula)))
1890 (if (eq (car-safe formula) 'quote)
1891 (setq initial (format "'%S" (cadr formula)))
1892 (setq initial (prin1-to-string formula)))
1893 (if (stringp formula)
1894 ;;Position cursor inside close-quote
1895 (setq initial (cons initial (length initial))))
1897 (read-from-minibuffer (format "Cell %s: " ses--curcell)
1900 t ;Convert to Lisp object
1901 'ses-read-cell-history)))))
1902 (when (ses-warn-unsafe newval 'unsafep)
1904 (ses-cell-set-formula row col newval)
1907 (defun ses-read-cell (row col newval)
1908 "Self-insert for initial character of cell function."
1910 (let* ((initial (this-command-keys))
1911 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
1912 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
1913 (barf-if-buffer-read-only)
1916 (read-from-minibuffer
1917 (format "Cell %s: " ses--curcell)
1918 (cons (if (equal initial "\"") "\"\""
1919 (if (equal initial "(") "()" initial)) 2)
1921 t ;Convert to Lisp object
1922 'ses-read-cell-history
1923 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
1926 (when (ses-edit-cell row col newval)
1927 (ses-command-hook) ;Update cell widths before movement
1928 (dolist (x ses-after-entry-functions)
1931 (defun ses-read-symbol (row col symb)
1932 "Self-insert for a symbol as a cell formula. The set of all symbols that
1933 have been used as formulas in this spreadsheet is available for completions."
1935 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
1937 (barf-if-buffer-read-only)
1938 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
1939 ses--symbolic-formulas))
1942 (if (string= newval "")
1943 nil ;Don't create zero-length symbols!
1944 (list 'quote (intern newval))))))
1945 (when (ses-edit-cell row col symb)
1946 (ses-command-hook) ;Update cell widths before movement
1947 (dolist (x ses-after-entry-functions)
1950 (defun ses-clear-cell-forward (count)
1951 "Delete formula and printer for current cell and then move to next cell.
1952 With prefix, deletes several cells."
1955 (1value (ses-clear-cell-backward (- count)))
1960 (let ((rowcol (ses-sym-rowcol ses--curcell)))
1961 (or rowcol (signal 'end-of-buffer nil))
1962 (ses-clear-cell (car rowcol) (cdr rowcol)))
1965 (defun ses-clear-cell-backward (count)
1966 "Move to previous cell and then delete it. With prefix, deletes several
1970 (1value (ses-clear-cell-forward (- count)))
1971 (ses-check-curcell 'end)
1974 (backward-char 1) ;Will signal 'beginning-of-buffer if appropriate
1976 (let ((rowcol (ses-sym-rowcol ses--curcell)))
1977 (ses-clear-cell (car rowcol) (cdr rowcol))))))
1980 ;;----------------------------------------------------------------------------
1981 ;; Input of cell-printer functions
1982 ;;----------------------------------------------------------------------------
1984 (defun ses-read-printer (prompt default)
1985 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
1986 PROMPT should end with \": \". Result is t if operation was cancelled."
1987 (barf-if-buffer-read-only)
1990 (setq prompt (format "%s [currently %S]: "
1991 (substring prompt 0 -2)
1993 (let ((new (read-from-minibuffer prompt
1994 nil ;Initial contents
1996 t ;Evaluate the result
1997 'ses-read-printer-history
1998 (prin1-to-string default))))
1999 (if (equal new default)
2000 ;;User changed mind, decided not to change printer
2002 (ses-printer-validate new)
2005 (stringp (car-safe new))
2006 (ses-warn-unsafe new 'unsafep-function)
2010 (defun ses-read-cell-printer (newval)
2011 "Set the printer function for the current cell or range.
2013 A printer function is either a string (a format control-string with one
2014 %-sequence -- result from format will be right-justified), or a list of one
2015 string (result from format will be left-justified), or a lambda-expression of
2016 one argument, or a symbol that names a function of one argument. In the
2017 latter two cases, the function's result should be either a string (will be
2018 right-justified) or a list of one string (will be left-justified)."
2022 (ses-check-curcell 'range)
2023 ;;Default is none if not all cells in range have same printer
2024 (catch 'ses-read-cell-printer
2025 (ses-dorange ses--curcell
2026 (setq x (ses-cell-printer row col))
2027 (if (eq (car-safe x) 'ses-safe-printer)
2031 (unless (equal default x)
2032 ;;Range contains differing printer functions
2034 (throw 'ses-read-cell-printer t)))))
2035 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2037 (unless (eq newval t)
2039 (ses-dorange ses--curcell
2040 (ses-set-cell row col 'printer newval)
2041 (ses-print-cell row col))))
2043 (defun ses-read-column-printer (col newval)
2044 "Set the printer function for the current column. See
2045 `ses-read-cell-printer' for input forms."
2047 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2049 (list col (ses-read-printer (format "Column %s printer: "
2050 (ses-column-letter col))
2051 (ses-col-printer col)))))
2053 (unless (eq newval t)
2055 (ses-set-parameter 'ses--col-printers newval col)
2057 (dotimes (row ses--numrows)
2058 (ses-print-cell row col)))))
2060 (defun ses-read-default-printer (newval)
2061 "Set the default printer function for cells that have no other. See
2062 `ses-read-cell-printer' for input forms."
2064 (list (ses-read-printer "Default printer: " ses--default-printer)))
2065 (unless (eq newval t)
2067 (ses-set-parameter 'ses--default-printer newval)
2068 (ses-reprint-all t)))
2071 ;;----------------------------------------------------------------------------
2072 ;; Spreadsheet size adjustments
2073 ;;----------------------------------------------------------------------------
2075 (defun ses-insert-row (count)
2076 "Insert a new row before the current one. With prefix, insert COUNT rows
2077 before current one."
2079 (ses-check-curcell 'end)
2080 (or (> count 0) (signal 'args-out-of-range nil))
2082 (let ((inhibit-quit t)
2083 (inhibit-read-only t)
2084 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2086 ;;Create a new set of cell-variables
2087 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2088 0 (1- ses--numcols))
2089 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2091 (ses-goto-print row 0)
2092 (dotimes-with-progress-reporter (x count) "Inserting row..."
2093 ;;Create a row of empty cells. The `symbol' fields will be set by
2094 ;;the call to ses-relocate-all.
2095 (setq newrow (make-vector ses--numcols nil))
2096 (dotimes (col ses--numcols)
2097 (aset newrow col (ses-make-cell)))
2098 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2099 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2100 (insert ses--blank-line))
2101 ;;Insert empty lines in cell data area (will be replaced by
2103 (ses-goto-data row 0)
2104 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2105 (ses-relocate-all row 0 count 0)
2106 ;;If any cell printers insert constant text, insert that text
2108 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2109 (global (ses-call-printer ses--default-printer)))
2110 (if (or (> (length cols) 0) (> (length global) 0))
2112 (dotimes (col ses--numcols)
2113 ;;These cells are always nil, only constant formatting printed
2114 (1value (ses-print-cell (+ x row) col))))))
2115 (when (> ses--header-row row)
2116 ;;Inserting before header
2117 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2118 (ses-reset-header-string)))
2119 ;;Reconstruct text attributes
2122 (push '(apply ses-widen) buffer-undo-list)
2123 ;;Return to current cell
2125 (ses-jump-safe ses--curcell)
2126 (ses-goto-print (1- ses--numrows) 0)))
2128 (defun ses-delete-row (count)
2129 "Delete the current row. With prefix, Deletes COUNT rows starting from the
2133 (or (> count 0) (signal 'args-out-of-range nil))
2134 (let ((inhibit-quit t)
2135 (inhibit-read-only t)
2136 (row (car (ses-sym-rowcol ses--curcell))))
2137 (setq count (min count (- ses--numrows row)))
2139 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2140 ;;Delete lines from print area
2141 (ses-goto-print row 0)
2142 (ses-delete-line count)
2143 ;;Delete lines from cell data area
2144 (ses-goto-data row 0)
2145 (ses-delete-line (* count (1+ ses--numcols)))
2146 ;;Relocate variables and formulas
2147 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2148 (ses-relocate-all row 0 (- count) 0)
2149 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2150 0 (1- ses--numcols))
2151 (when (> ses--header-row row)
2152 (if (<= ses--header-row (+ row count))
2153 ;;Deleting the header row
2154 (ses-set-parameter 'ses--header-row 0)
2155 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2156 (ses-reset-header-string)))
2157 ;;Reconstruct attributes
2160 (push '(apply ses-widen) buffer-undo-list)
2161 (ses-jump-safe ses--curcell))
2163 (defun ses-insert-column (count &optional col width printer)
2164 "Insert a new column before COL (default is the current one).
2165 With prefix, insert COUNT columns before current one.
2166 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2167 \(otherwise they're taken from the current column)."
2170 (or (> count 0) (signal 'args-out-of-range nil))
2172 (setq col (cdr (ses-sym-rowcol ses--curcell))
2173 width (ses-col-width col)
2174 printer (ses-col-printer col)))
2176 (let ((inhibit-quit t)
2177 (inhibit-read-only t)
2178 (widths ses--col-widths)
2179 (printers ses--col-printers)
2181 ;;Create a new set of cell-variables
2182 (ses-create-cell-variable-range 0 (1- ses--numrows)
2183 ses--numcols (+ ses--numcols count -1))
2184 ;;Insert each column.
2185 (dotimes-with-progress-reporter (x count) "Inserting column..."
2186 ;;Create a column of empty cells. The `symbol' fields will be set by
2187 ;;the call to ses-relocate-all.
2188 (ses-adjust-print-width col (1+ width))
2189 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2190 (dotimes (row ses--numrows)
2191 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2192 ;;Inserting in the middle of a spill-over
2194 (ses-aset-with-undo ses--cells row
2195 (ses-vector-insert (aref ses--cells row)
2196 col (ses-make-cell)))
2197 ;;Insert empty lines in cell data area (will be replaced by
2199 (ses-goto-data row col)
2201 ;;Insert column width and printer
2202 (setq widths (ses-vector-insert widths col width)
2203 printers (ses-vector-insert printers col printer)))
2204 (ses-set-parameter 'ses--col-widths widths)
2205 (ses-set-parameter 'ses--col-printers printers)
2206 (ses-reset-header-string)
2207 (ses-relocate-all 0 col 0 count)
2210 (when (or (> (length (ses-call-printer printer)) 0)
2211 (> (length (ses-call-printer ses--default-printer)) 0))
2212 ;;Either column printer or global printer inserts some constant text
2213 ;;Reprint the new columns to insert that text.
2214 (dotimes (x ses--numrows)
2216 ;Always nil here - this is a blank column
2217 (1value (ses-print-cell-new-width x (+ y col))))))
2219 (ses-jump-safe ses--curcell))
2221 (defun ses-delete-column (count)
2222 "Delete the current column. With prefix, Deletes COUNT columns starting
2223 from the current one."
2226 (or (> count 0) (signal 'args-out-of-range nil))
2227 (let ((inhibit-quit t)
2228 (inhibit-read-only t)
2229 (rowcol (ses-sym-rowcol ses--curcell))
2231 col origrow has-skip)
2232 (setq origrow (car rowcol)
2234 count (min count (- ses--numcols col)))
2235 (if (= count ses--numcols)
2236 (error "Can't delete all columns!"))
2237 ;;Determine width of column(s) being deleted
2239 (setq width (+ width (ses-col-width (+ col x)) 1)))
2241 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2242 (ses-adjust-print-width col (- width))
2243 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2244 ;;Delete lines from cell data area
2245 (ses-goto-data row col)
2246 (ses-delete-line count)
2247 ;;Delete cells. Check if deletion area begins or ends with a skip.
2248 (if (or (eq (ses-cell-value row col) '*skip*)
2249 (and (< col ses--numcols)
2250 (eq (ses-cell-value row (+ col count)) '*skip*)))
2252 (ses-aset-with-undo ses--cells row
2253 (ses-vector-delete (aref ses--cells row) col count)))
2255 (ses-set-parameter 'ses--col-widths
2256 (ses-vector-delete ses--col-widths col count))
2257 (ses-set-parameter 'ses--col-printers
2258 (ses-vector-delete ses--col-printers col count))
2259 (ses-reset-header-string)
2260 ;;Relocate variables and formulas
2261 (ses-relocate-all 0 col 0 (- count))
2262 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2263 ses--numcols (+ ses--numcols count -1))
2267 (if (>= col ses--numcols)
2268 (setq col (1- col)))
2269 (ses-goto-print origrow col)))
2271 (defun ses-forward-or-insert (&optional count)
2272 "Move to next cell in row, or inserts a new cell if already in last one, or
2273 inserts a new row if at bottom of print area. Repeat COUNT times."
2275 (ses-check-curcell 'end)
2276 (setq deactivate-mark t) ;Doesn't combine well with ranges
2279 (if (not ses--curcell)
2280 (progn ;At bottom of print area
2281 (barf-if-buffer-read-only)
2283 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2285 (char-before (next-single-property-change (point)
2287 ;;We're already in last nonskipped cell on line. Need to create a
2289 (barf-if-buffer-read-only)
2290 (ses-insert-column (- count x)
2293 (ses-col-printer col)))))
2296 (defun ses-append-row-jump-first-column ()
2297 "Insert a new row after current one and jumps to its first column."
2301 (beginning-of-line 2)
2305 (defun ses-set-column-width (col newwidth)
2306 "Set the width of the current column."
2308 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2309 (barf-if-buffer-read-only)
2311 (if current-prefix-arg
2312 (prefix-numeric-value current-prefix-arg)
2313 (read-from-minibuffer (format "Column %s width [currently %d]: "
2314 (ses-column-letter col)
2315 (ses-col-width col))
2316 nil ;No initial contents
2317 nil ;No override keymap
2318 t ;Convert to Lisp object
2321 (ses-col-width col))))))) ;Default value
2323 (error "Invalid column width"))
2325 (ses-reset-header-string)
2327 (let ((inhibit-quit t))
2328 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2329 (ses-set-parameter 'ses--col-widths newwidth col))
2330 (dotimes (row ses--numrows)
2331 (ses-print-cell-new-width row col))))
2334 ;;----------------------------------------------------------------------------
2335 ;; Cut and paste, import and export
2336 ;;----------------------------------------------------------------------------
2338 (defadvice copy-region-as-kill (around ses-copy-region-as-kill
2339 activate preactivate)
2340 "It doesn't make sense to copy read-only or intangible attributes into the
2341 kill ring. It probably doesn't make sense to copy keymap properties.
2342 We'll assume copying front-sticky properties doesn't make sense, either.
2344 This advice also includes some SES-specific code because otherwise it's too
2345 hard to override how mouse-1 works."
2350 (if (not (and (eq major-mode 'ses-mode)
2351 (eq (get-text-property beg 'read-only) 'ses)
2352 (eq (get-text-property (1- end) 'read-only) 'ses)))
2353 ad-do-it ;Normal copy-region-as-kill
2354 (kill-new (ses-copy-region beg end))
2355 (if transient-mark-mode
2356 (setq deactivate-mark t))
2359 (defun ses-copy-region (beg end)
2360 "Treat the region as rectangular. Convert the intangible attributes to
2361 SES attributes recording the contents of the cell as of the time of copying."
2362 (when (= end ses--data-marker)
2363 ;;Avoid overflow situation
2364 (setq end (1- ses--data-marker)))
2365 (let* ((inhibit-point-motion-hooks t)
2366 (x (mapconcat 'ses-copy-region-helper
2367 (extract-rectangle beg (1- end)) "\n")))
2368 (remove-text-properties 0 (length x)
2376 (defun ses-copy-region-helper (line)
2377 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2378 external form by attaching to each print cell a 'ses attribute that records
2379 the corresponding data cell."
2380 (or (> (length line) 1)
2381 (error "Empty range"))
2382 (let ((inhibit-read-only t)
2384 mycell next sym rowcol)
2386 (setq sym (get-text-property pos 'intangible line)
2387 next (next-single-property-change pos 'intangible line)
2388 rowcol (ses-sym-rowcol sym)
2389 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2390 (put-text-property pos (or next (length line))
2392 (list (ses-cell-symbol mycell)
2393 (ses-cell-formula mycell)
2394 (ses-cell-printer mycell))
2399 (defun ses-kill-override (beg end)
2400 "Generic override for any commands that kill text. We clear the killed
2401 cells instead of deleting them."
2403 (ses-check-curcell 'needrange)
2404 ;;For some reason, the text-read-only error is not caught by
2405 ;;`delete-region', so we have to use subterfuge.
2406 (let ((buffer-read-only t))
2407 (1value (condition-case x
2408 (noreturn (funcall (lookup-key (current-global-map)
2409 (this-command-keys))
2411 (buffer-read-only nil)))) ;The expected error
2412 ;;Because the buffer was marked read-only, the kill command turned itself
2413 ;;into a copy. Now we clear the cells or signal the error. First we
2414 ;;check whether the buffer really is read-only.
2415 (barf-if-buffer-read-only)
2417 (ses-dorange ses--curcell
2418 (ses-clear-cell row col))
2419 (ses-jump (car ses--curcell)))
2421 (defadvice yank (around ses-yank activate preactivate)
2422 "In SES mode, the yanked text is inserted as cells.
2424 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2425 SES buffer), the formulas and print functions are restored for the cells. If
2426 the text contains tabs, this is an insertion of tab-separated formulas.
2427 Otherwise the text is inserted as the formula for the current cell.
2429 When inserting cells, the formulas are usually relocated to keep the same
2430 relative references to neighboring cells. This is best if the formulas
2431 generally refer to other cells within the yanked text. You can use the C-u
2432 prefix to specify insertion without relocation, which is best when the
2433 formulas refer to cells outsite the yanked text.
2435 When inserting formulas, the text is treated as a string constant if it doesn't
2436 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2437 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2439 (if (not (and (eq major-mode 'ses-mode)
2440 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2441 ad-do-it ;Normal non-SES yank
2442 (ses-check-curcell 'end)
2444 (let ((text (current-kill (cond
2448 (or (ses-yank-cells text arg)
2449 (ses-yank-tsf text arg)
2450 (ses-yank-one (ses-yank-resize 1 1)
2453 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2454 ;;Just one cell - delete final tab or newline
2458 (exchange-point-and-mark))))
2460 (defun ses-yank-pop (arg)
2461 "Replace just-yanked stretch of killed text with a different stretch.
2462 This command is allowed only immediately after a `yank' or a `yank-pop', when
2463 the region contains a stretch of reinserted previously-killed text. We
2464 replace it with a different stretch of killed text.
2465 Unlike standard `yank-pop', this function uses `undo' to delete the
2466 previous insertion."
2468 (or (eq last-command 'yank)
2469 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2471 (noreturn (error "Previous command was not a yank")))
2474 (yank (1+ (or arg 1)))
2475 (setq this-command 'yank))
2477 (defun ses-yank-cells (text arg)
2478 "If the TEXT has a proper set of 'ses attributes, inserts the text as
2479 cells, else return nil. The cells are reprinted--the supplied text is
2480 ignored because the column widths, default printer, etc. at yank time might
2481 be different from those at kill-time. ARG is a list to indicate that
2482 formulas are to be inserted without relocation."
2483 (let ((first (get-text-property 0 'ses text))
2484 (last (get-text-property (1- (length text)) 'ses text)))
2485 (when (and first last) ;;Otherwise not proper set of attributes
2486 (setq first (ses-sym-rowcol (car first))
2487 last (ses-sym-rowcol (car last)))
2488 (let* ((needrows (- (car last) (car first) -1))
2489 (needcols (- (cdr last) (cdr first) -1))
2490 (rowcol (ses-yank-resize needrows needcols))
2491 (rowincr (- (car rowcol) (car first)))
2492 (colincr (- (cdr rowcol) (cdr first)))
2495 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2496 (setq myrow (+ row (car rowcol)))
2497 (dotimes (col needcols)
2498 (setq mycol (+ col (cdr rowcol))
2499 last (get-text-property pos 'ses text)
2500 pos (next-single-property-change pos 'ses text)
2501 x (ses-sym-rowcol (car last)))
2503 ;;Newline - all remaining cells on row are skipped
2504 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2505 last (list nil nil nil)
2507 (if (/= (car x) (- myrow rowincr))
2508 (error "Cell row error"))
2509 (if (< (- mycol colincr) (cdr x))
2510 ;;Some columns were skipped
2511 (let ((oldcol mycol))
2512 (while (< (- mycol colincr) (cdr x))
2513 (ses-clear-cell myrow mycol)
2516 (ses-print-cell myrow (1- oldcol)))) ;;This inserts *skip*
2517 (when (car last) ;Skip this for *skip* cells
2518 (setq x (nth 2 last))
2519 (unless (equal x (ses-cell-printer myrow mycol))
2522 (eq (car-safe x) 'ses-safe-printer)
2523 (setq x `(ses-safe-printer ,x)))
2524 (ses-set-cell myrow mycol 'printer x))
2525 (setq x (cadr last))
2527 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2529 (eq (car-safe x) 'ses-safe-formula)
2530 (setq x `(ses-safe-formula ,x)))
2531 (ses-cell-set-formula myrow mycol x)))
2533 (if (get-text-property pos 'ses text)
2534 (error "Missing newline between rows"))
2535 (setq pos (next-single-property-change pos 'ses text))))
2538 (defun ses-yank-one (rowcol text from to arg)
2539 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2540 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2541 (let ((val (condition-case nil
2542 (read-from-string text from to)
2543 (error (cons nil from)))))
2545 ((< (cdr val) (or to (length text)))
2546 ;;Invalid sexp - leave it as a string
2547 (setq val (substring text from to)))
2548 ((and (car val) (symbolp (car val)))
2550 (setq val (list 'quote (car val))) ;Keep symbol
2551 (setq val (substring text from to)))) ;Treat symbol as text
2553 (setq val (car val))))
2554 (let ((row (car rowcol))
2557 (setq val `(ses-safe-formula ,val)))
2558 (ses-cell-set-formula row col val))))
2560 (defun ses-yank-tsf (text arg)
2561 "If TEXT contains tabs and/or newlines, treats the tabs as
2562 column-separators and the newlines as row-separators and inserts the text as
2563 cell formulas--else return nil. Treat plain symbols as strings unless ARG
2564 is a list. Ignore a final newline."
2565 (if (or (not (string-match "[\t\n]" text))
2566 (= (match-end 0) (length text)))
2569 (if (/= (aref text (1- (length text))) ?\n)
2570 (setq text (concat text "\n")))
2576 ;;Find all the tabs and newlines
2577 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
2579 (setq cols (1+ cols))
2580 (when (eq (aref text pos) ?\n)
2582 (setq needcols cols)
2583 (or (= needcols cols)
2584 (error "Inconsistent row lengths")))
2586 needrows (1+ needrows))))
2587 ;;Insert the formulas
2588 (setq rowcol (ses-yank-resize needrows needcols))
2589 (dotimes (row needrows)
2590 (dotimes (col needcols)
2591 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
2592 (+ (cdr rowcol) needcols (- col) -1))
2593 text (1+ (cadr spots)) (car spots) arg)
2594 (setq spots (cdr spots))))
2595 (ses-goto-print (+ (car rowcol) needrows -1)
2596 (+ (cdr rowcol) needcols -1))
2599 (defun ses-yank-resize (needrows needcols)
2600 "If this yank will require inserting rows and/or columns, asks for
2601 confirmation and then inserts them. Result is (row,col) for top left of yank
2602 spot, or error signal if user requests cancel."
2604 (let ((rowcol (if ses--curcell
2605 (ses-sym-rowcol ses--curcell)
2606 (cons ses--numrows 0)))
2608 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
2609 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
2610 rowbool (> needrows 0)
2611 colbool (> needcols 0))
2612 (when (or rowbool colbool)
2613 ;;Need to insert. Get confirm
2614 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
2615 (if rowbool (format "%d rows" needrows) "")
2616 (if (and rowbool colbool) " and " "")
2617 (if colbool (format "%d columns" needcols) "")))
2618 (error "Cancelled"))
2622 (ses-goto-print ses--numrows 0)
2623 (ses-insert-row needrows))))
2625 (ses-insert-column needcols
2627 (ses-col-width (1- ses--numcols))
2628 (ses-col-printer (1- ses--numcols)))))
2631 (defun ses-export-tsv (beg end)
2632 "Export values from the current range, with tabs between columns and
2633 newlines between rows. Result is placed in kill ring."
2635 (ses-export-tab nil))
2637 (defun ses-export-tsf (beg end)
2638 "Export formulas from the current range, with tabs between columns and
2639 newlines between rows. Result is placed in kill ring."
2643 (defun ses-export-tab (want-formulas)
2644 "Export the current range with tabs between columns and newlines between
2645 rows. Result is placed in kill ring. The export is values unless
2646 WANT-FORMULAS is non-nil. Newlines and tabs in the export text are escaped."
2647 (ses-check-curcell 'needrange)
2648 (let ((print-escape-newlines t)
2650 (ses-dorange ses--curcell
2651 (setq item (if want-formulas
2652 (ses-cell-formula row col)
2653 (ses-cell-value row col)))
2654 (if (eq (car-safe item) 'ses-safe-formula)
2655 ;;Hide our deferred safety-check marker
2656 (setq item (cadr item)))
2657 (if (or (not item) (eq item '*skip*))
2659 (when (eq (car-safe item) 'quote)
2661 (setq item (cadr item)))
2662 (setq item (prin1-to-string item t))
2663 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
2669 (push "\n" result))))
2670 (setq result (apply 'concat (nreverse result)))
2674 ;;----------------------------------------------------------------------------
2675 ;; Other user commands
2676 ;;----------------------------------------------------------------------------
2678 (defun ses-unset-header-row ()
2679 "Select the default header row."
2681 (ses-set-header-row 0))
2683 (defun ses-set-header-row (row)
2684 "Set the ROW to display in the header-line.
2685 With a numerical prefix arg, use that row.
2686 With no prefix arg, use the current row.
2687 With a \\[universal-argument] prefix arg, prompt the user.
2688 The top row is row 1. Selecting row 0 displays the default header row."
2690 (list (if (numberp current-prefix-arg) current-prefix-arg
2691 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
2692 (if current-prefix-arg
2693 (read-number "Header row: " currow)
2695 (if (or (< row 0) (> row ses--numrows))
2696 (error "Invalid header-row"))
2698 (let ((oldval ses--header-row))
2699 (let (buffer-undo-list)
2700 (ses-set-parameter 'ses--header-row row))
2701 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
2702 (ses-reset-header-string))
2704 (defun ses-mark-row ()
2705 "Marks the entirety of current row as a range."
2707 (ses-check-curcell 'range)
2708 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
2710 (ses-goto-print (1+ row) 0)
2711 (push-mark (point) nil t)
2712 (ses-goto-print row 0)))
2714 (defun ses-mark-column ()
2715 "Marks the entirety of current column as a range."
2717 (ses-check-curcell 'range)
2718 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
2721 (ses-goto-print (1- ses--numrows) col)
2723 (push-mark (point) nil t)
2724 (while (eq '*skip* (ses-cell-value row col))
2725 ;;Skip over initial cells in column that can't be selected
2726 (setq row (1+ row)))
2727 (ses-goto-print row col)))
2729 (defun ses-end-of-line ()
2730 "Move point to last cell on line."
2732 (ses-check-curcell 'end 'range)
2733 (when ses--curcell ;Otherwise we're at the bottom row, which is empty anyway
2734 (let ((col (1- ses--numcols))
2736 (if (symbolp ses--curcell)
2738 (setq row (car (ses-sym-rowcol ses--curcell)))
2739 ;;Range - use whichever end of the range the point is at
2740 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
2742 (cdr ses--curcell))))
2743 ;;If range already includes the last cell in a row, point is actually
2744 ;;in the following row
2745 (if (<= (cdr rowcol) (1- col))
2746 (setq row (car rowcol))
2747 (setq row (1+ (car rowcol)))
2748 (if (= row ses--numrows)
2749 ;;Already at end - can't go anywhere
2751 (when (< row ses--numrows) ;Otherwise it's a range that includes last cell
2752 (while (eq (ses-cell-value row col) '*skip*)
2753 ;;Back to beginning of multi-column cell
2754 (setq col (1- col)))
2755 (ses-goto-print row col)))))
2757 (defun ses-renarrow-buffer ()
2758 "Narrow the buffer so only the print area is visible. Use after \\[widen]."
2760 (setq ses--deferred-narrow t))
2762 (defun ses-sort-column (sorter &optional reverse)
2763 "Sorts the range by a specified column. With prefix, sorts in
2765 (interactive "*sSort column: \nP")
2766 (ses-check-curcell 'needrange)
2767 (let ((min (ses-sym-rowcol (car ses--curcell)))
2768 (max (ses-sym-rowcol (cdr ses--curcell))))
2769 (let ((minrow (car min))
2774 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
2775 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
2776 (error "Invalid sort column"))
2777 ;;Get key columns and sort them
2778 (dotimes (x (- maxrow minrow -1))
2779 (ses-goto-print (+ minrow x) sorter)
2780 (setq end (next-single-property-change (point) 'intangible))
2781 (push (cons (buffer-substring-no-properties (point) end)
2784 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
2785 ;;Extract the lines in reverse sorted order
2787 (setq keys (nreverse keys)))
2789 (ses-goto-print (cdr x) (1+ maxcol))
2791 (ses-goto-print (cdr x) mincol)
2792 (push (ses-copy-region (point) end) extracts))
2794 ;;Paste the lines sequentially
2795 (dotimes (x (- maxrow minrow -1))
2796 (ses-goto-print (+ minrow x) mincol)
2798 (ses-yank-cells (pop extracts) nil)))))
2800 (defun ses-sort-column-click (event reverse)
2801 "Mouse version of `ses-sort-column'."
2802 (interactive "*e\nP")
2803 (setq event (event-end event))
2804 (select-window (posn-window event))
2805 (setq event (car (posn-col-row event))) ;Click column
2807 (while (and (< col ses--numcols) (> event (ses-col-width col)))
2808 (setq event (- event (ses-col-width col) 1)
2810 (if (>= col ses--numcols)
2812 (ses-sort-column (ses-column-letter col) reverse))))
2814 (defun ses-insert-range ()
2815 "Inserts into minibuffer the list of cells currently highlighted in the
2819 (with-current-buffer (window-buffer minibuffer-scroll-window)
2820 (ses-command-hook) ;For ses-coverage
2821 (ses-check-curcell 'needrange)
2822 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
2823 ,(cdr ses--curcell))))))
2824 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
2826 (defun ses-insert-ses-range ()
2827 "Inserts \"(ses-range x y)\" in the minibuffer to represent the currently
2828 highlighted range in the spreadsheet."
2831 (with-current-buffer (window-buffer minibuffer-scroll-window)
2832 (ses-command-hook) ;For ses-coverage
2833 (ses-check-curcell 'needrange)
2834 (setq x (format "(ses-range %S %S)"
2836 (cdr ses--curcell))))
2839 (defun ses-insert-range-click (event)
2840 "Mouse version of `ses-insert-range'."
2842 (mouse-set-point event)
2845 (defun ses-insert-ses-range-click (event)
2846 "Mouse version of `ses-insert-ses-range'."
2848 (mouse-set-point event)
2849 (ses-insert-ses-range))
2852 ;;----------------------------------------------------------------------------
2853 ;; Checking formulas for safety
2854 ;;----------------------------------------------------------------------------
2856 (defun ses-safe-printer (printer)
2857 "Returns PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
2858 (if (or (stringp printer)
2859 (stringp (car-safe printer))
2861 (ses-warn-unsafe printer 'unsafep-function))
2865 (defun ses-safe-formula (formula)
2866 "Returns FORMULA if safe, or the substitute formula *unsafe* otherwise."
2867 (if (ses-warn-unsafe formula 'unsafep)
2869 `(ses-unsafe ',formula)))
2871 (defun ses-warn-unsafe (formula checker)
2872 "Applies CHECKER to FORMULA. If result is non-nil, asks user for
2873 confirmation about FORMULA, which might be unsafe. Returns t if formula
2874 is safe or user allows execution anyway. Always returns t if
2875 `safe-functions' is t."
2876 (if (eq safe-functions t)
2878 (setq checker (funcall checker formula))
2881 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
2882 formula checker)))))
2885 ;;----------------------------------------------------------------------------
2886 ;; Standard formulas
2887 ;;----------------------------------------------------------------------------
2889 (defmacro ses-range (from to)
2890 "Expands to a list of cell-symbols for the range. The range automatically
2891 expands to include any new row or column inserted into its middle. The SES
2892 library code specifically looks for the symbol `ses-range', so don't create an
2893 alias for this macro!"
2895 (ses-dorange (cons from to)
2896 (push (ses-cell-symbol row col) result))
2897 (cons 'list result)))
2899 (defun ses-delete-blanks (&rest args)
2900 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
2903 (unless (memq cur '(nil *skip*))
2907 (defun ses+ (&rest args)
2908 "Compute the sum of the arguments, ignoring blanks."
2909 (apply '+ (apply 'ses-delete-blanks args)))
2911 (defun ses-average (list)
2912 "Computes the sum of the numbers in LIST, divided by their length. Blanks
2913 are ignored. Result is always floating-point, even if all args are integers."
2914 (setq list (apply 'ses-delete-blanks list))
2915 (/ (float (apply '+ list)) (length list)))
2917 (defmacro ses-select (fromrange test torange)
2918 "Select cells in FROMRANGE that are `equal' to TEST. For each match, return
2919 the corresponding cell from TORANGE. The ranges are macroexpanded but not
2920 evaluated so they should be either (ses-range BEG END) or (list ...). The
2922 (setq fromrange (cdr (macroexpand fromrange))
2923 torange (cdr (macroexpand torange))
2925 (or (= (length fromrange) (length torange))
2926 (error "ses-select: Ranges not same length"))
2928 (dolist (x fromrange)
2929 (if (equal test (symbol-value x))
2930 (push (car torange) result))
2931 (setq torange (cdr torange)))
2932 (cons 'list result)))
2934 ;;All standard formulas are safe
2935 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
2937 (put x 'side-effect-free t))
2940 ;;----------------------------------------------------------------------------
2941 ;; Standard print functions
2942 ;;----------------------------------------------------------------------------
2944 ;;These functions use the variables 'row' and 'col' that are
2945 ;;dynamically bound by ses-print-cell. We define these variables at
2946 ;;compile-time to make the compiler happy.
2948 (dolist (x '(row col))
2949 (make-local-variable x)
2952 (defun ses-center (value &optional span fill)
2953 "Print VALUE, centered within column. FILL is the fill character for
2954 centering (default = space). SPAN indicates how many additional rightward
2955 columns to include in width (default = 0)."
2956 (let ((printer (or (ses-col-printer col) ses--default-printer))
2957 (width (ses-col-width col))
2959 (or fill (setq fill ?\s))
2960 (or span (setq span 0))
2961 (setq value (ses-call-printer printer value))
2963 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
2965 (setq width (- width (string-width value)))
2967 value ;Too large for field, anyway
2968 (setq half (make-string (/ width 2) fill))
2969 (concat half value half
2970 (if (> (% width 2) 0) (char-to-string fill))))))
2972 (defun ses-center-span (value &optional fill)
2973 "Print VALUE, centered within the span that starts in the current column
2974 and continues until the next nonblank column. FILL specifies the fill
2975 character (default = space)."
2976 (let ((end (1+ col)))
2977 (while (and (< end ses--numcols)
2978 (memq (ses-cell-value row end) '(nil *skip*)))
2979 (setq end (1+ end)))
2980 (ses-center value (- end col 1) fill)))
2982 (defun ses-dashfill (value &optional span)
2983 "Print VALUE centered using dashes. SPAN indicates how many rightward
2984 columns to include in width (default = 0)."
2985 (ses-center value span ?-))
2987 (defun ses-dashfill-span (value)
2988 "Print VALUE, centered using dashes within the span that starts in the
2989 current column and continues until the next nonblank column."
2990 (ses-center-span value ?-))
2992 (defun ses-tildefill-span (value)
2993 "Print VALUE, centered using tildes within the span that starts in the
2994 current column and continues until the next nonblank column."
2995 (ses-center-span value ?~))
2997 (defun ses-unsafe (value)
2998 "Substitute for an unsafe formula or printer"
2999 (error "Unsafe formula or printer"))
3001 ;;All standard printers are safe, including ses-unsafe!
3002 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3003 (put x 'side-effect-free t))
3005 (defun ses-unload-function ()
3006 "Unload the Simple Emacs Spreadsheet."
3007 (dolist (fun '(copy-region-as-kill yank))
3008 (ad-remove-advice fun 'around (intern (concat "ses-" (symbol-name fun))))
3010 (save-current-buffer
3011 (dolist (buf (buffer-list))
3013 (when (eq major-mode 'ses-mode)
3014 (funcall (or (default-value 'major-mode) 'fundamental-mode)))))
3015 ;; continue standard unloading
3020 ;; arch-tag: 88c1ccf0-4293-4824-8c5d-0757b52217f3
3021 ;;; ses.el ends here