Switch to recommended form of GPLv3 permissions notice.
[emacs.git] / lisp / ses.el
blob64b966bfa9142df8e0489f2212e1172386d05029
1 ;;; ses.el -- Simple Emacs Spreadsheet -*- coding: utf-8 -*-
3 ;; Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5 ;; Author: Jonathan Yavner <jyavner@member.fsf.org>
6 ;; Maintainer: Jonathan Yavner <jyavner@member.fsf.org>
7 ;; Keywords: spreadsheet
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;;; To-do list:
28 ;; * Use $ or … for truncated fields
29 ;; * Add command to make a range of columns be temporarily invisible.
30 ;; * Allow paste of one cell to a range of cells -- copy formula to each.
31 ;; * Do something about control characters & octal codes in cell print
32 ;; areas. Use string-width?
33 ;; * Input validation functions. How specified?
34 ;; * Faces (colors & styles) in print cells.
35 ;; * Move a column by dragging its letter in the header line.
36 ;; * Left-margin column for row number.
37 ;; * Move a row by dragging its number in the left-margin.
40 ;;; Code:
42 (require 'unsafep)
45 ;;----------------------------------------------------------------------------
46 ;; User-customizable variables
47 ;;----------------------------------------------------------------------------
49 (defgroup ses nil
50 "Simple Emacs Spreadsheet."
51 :group 'applications
52 :prefix "ses-"
53 :version "21.1")
55 (defcustom ses-initial-size '(1 . 1)
56 "Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
57 :group 'ses
58 :type '(cons (integer :tag "numrows") (integer :tag "numcols")))
60 (defcustom ses-initial-column-width 7
61 "Initial width of columns in a new spreadsheet."
62 :group 'ses
63 :type '(integer :match (lambda (widget value) (> value 0))))
65 (defcustom ses-initial-default-printer "%.7g"
66 "Initial default printer for a new spreadsheet."
67 :group 'ses
68 :type '(choice string
69 (list :tag "Parenthesized string" string)
70 function))
72 (defcustom ses-after-entry-functions '(forward-char)
73 "Things to do after entering a value into a cell.
74 An abnormal hook that usually runs a cursor-movement function.
75 Each function is called with ARG=1."
76 :group 'ses
77 :type 'hook
78 :options '(forward-char backward-char next-line previous-line))
80 (defcustom ses-mode-hook nil
81 "Hook functions to be run upon entering SES mode."
82 :group 'ses
83 :type 'hook)
86 ;;----------------------------------------------------------------------------
87 ;; Global variables and constants
88 ;;----------------------------------------------------------------------------
90 (defvar ses-read-cell-history nil
91 "List of formulas that have been typed in.")
93 (defvar ses-read-printer-history nil
94 "List of printer functions that have been typed in.")
96 (easy-menu-define ses-header-line-menu nil
97 "Context menu when mouse-3 is used on the header-line in an SES buffer."
98 '("SES header row"
99 ["Set current row" ses-set-header-row t]
100 ["Unset row" ses-unset-header-row (> ses--header-row 0)]))
102 (defconst ses-mode-map
103 (let ((keys `("\C-c\M-\C-l" ses-reconstruct-all
104 "\C-c\C-l" ses-recalculate-all
105 "\C-c\C-n" ses-renarrow-buffer
106 "\C-c\C-c" ses-recalculate-cell
107 "\C-c\M-\C-s" ses-sort-column
108 "\C-c\M-\C-h" ses-set-header-row
109 "\C-c\C-t" ses-truncate-cell
110 "\C-c\C-j" ses-jump
111 "\C-c\C-p" ses-read-default-printer
112 "\M-\C-l" ses-reprint-all
113 [?\S-\C-l] ses-reprint-all
114 [header-line down-mouse-3] ,ses-header-line-menu
115 [header-line mouse-2] ses-sort-column-click))
116 (newmap (make-sparse-keymap)))
117 (while keys
118 (define-key (1value newmap) (car keys) (cadr keys))
119 (setq keys (cddr keys)))
120 newmap)
121 "Local keymap for Simple Emacs Spreadsheet.")
123 (easy-menu-define ses-menu ses-mode-map
124 "Menu bar menu for SES."
125 '("SES"
126 ["Insert row" ses-insert-row (ses-in-print-area)]
127 ["Delete row" ses-delete-row (ses-in-print-area)]
128 ["Insert column" ses-insert-column (ses-in-print-area)]
129 ["Delete column" ses-delete-column (ses-in-print-area)]
130 ["Set column printer" ses-read-column-printer t]
131 ["Set column width" ses-set-column-width t]
132 ["Set default printer" ses-read-default-printer t]
133 ["Jump to cell" ses-jump t]
134 ["Set cell printer" ses-read-cell-printer t]
135 ["Recalculate cell" ses-recalculate-cell t]
136 ["Truncate cell display" ses-truncate-cell t]
137 ["Export values" ses-export-tsv t]
138 ["Export formulas" ses-export-tsf t]))
140 (defconst ses-mode-edit-map
141 (let ((keys '("\C-c\C-r" ses-insert-range
142 "\C-c\C-s" ses-insert-ses-range
143 [S-mouse-3] ses-insert-range-click
144 [C-S-mouse-3] ses-insert-ses-range-click
145 "\M-\C-i" lisp-complete-symbol))
146 (newmap (make-sparse-keymap)))
147 (set-keymap-parent newmap minibuffer-local-map)
148 (while keys
149 (define-key newmap (pop keys) (pop keys)))
150 newmap)
151 "Local keymap for SES minibuffer cell-editing.")
153 ;Local keymap for SES print area
154 (defalias 'ses-mode-print-map
155 (let ((keys '([backtab] backward-char
156 [tab] ses-forward-or-insert
157 "\C-i" ses-forward-or-insert ;Needed for ses-coverage.el?
158 "\M-o" ses-insert-column
159 "\C-o" ses-insert-row
160 "\C-m" ses-edit-cell
161 "\M-k" ses-delete-column
162 "\M-y" ses-yank-pop
163 "\C-k" ses-delete-row
164 "\C-j" ses-append-row-jump-first-column
165 "\M-h" ses-mark-row
166 "\M-H" ses-mark-column
167 "\C-d" ses-clear-cell-forward
168 "\C-?" ses-clear-cell-backward
169 "(" ses-read-cell
170 "\"" ses-read-cell
171 "'" ses-read-symbol
172 "=" ses-edit-cell
173 "c" ses-recalculate-cell
174 "j" ses-jump
175 "p" ses-read-cell-printer
176 "t" ses-truncate-cell
177 "w" ses-set-column-width
178 "x" ses-export-keymap
179 "\M-p" ses-read-column-printer))
180 (repl '(;;We'll replace these wherever they appear in the keymap
181 clipboard-kill-region ses-kill-override
182 end-of-line ses-end-of-line
183 kill-line ses-delete-row
184 kill-region ses-kill-override
185 open-line ses-insert-row))
186 (numeric "0123456789.-")
187 (newmap (make-keymap)))
188 ;;Get rid of printables
189 (suppress-keymap newmap t)
190 ;;These keys insert themselves as the beginning of a numeric value
191 (dotimes (x (length numeric))
192 (define-key newmap (substring numeric x (1+ x)) 'ses-read-cell))
193 ;;Override these global functions wherever they're bound
194 (while repl
195 (substitute-key-definition (car repl) (cadr repl) newmap
196 (current-global-map))
197 (setq repl (cddr repl)))
198 ;;Apparently substitute-key-definition doesn't catch this?
199 (define-key newmap [(menu-bar) edit cut] 'ses-kill-override)
200 ;;Define our other local keys
201 (while keys
202 (define-key newmap (car keys) (cadr keys))
203 (setq keys (cddr keys)))
204 newmap))
206 ;;Helptext for ses-mode wants keymap as variable, not function
207 (defconst ses-mode-print-map (symbol-function 'ses-mode-print-map))
209 ;;Key map used for 'x' key.
210 (defalias 'ses-export-keymap
211 (let ((map (make-sparse-keymap "SES export")))
212 (define-key map "T" (cons " tab-formulas" 'ses-export-tsf))
213 (define-key map "t" (cons " tab-values" 'ses-export-tsv))
214 map))
216 (defconst ses-print-data-boundary "\n\014\n"
217 "Marker string denoting the boundary between print area and data area.")
219 (defconst ses-initial-global-parameters
220 "\n( ;Global parameters (these are read first)\n 2 ;SES file-format\n 1 ;numrows\n 1 ;numcols\n)\n\n"
221 "Initial contents for the three-element list at the bottom of the data area.")
223 (defconst ses-initial-file-trailer
224 ";; Local Variables:\n;; mode: ses\n;; End:\n"
225 "Initial contents for the file-trailer area at the bottom of the file.")
227 (defconst ses-initial-file-contents
228 (concat " \n" ;One blank cell in print area
229 ses-print-data-boundary
230 "(ses-cell A1 nil nil nil nil)\n" ;One blank cell in data area
231 "\n" ;End-of-row terminator for the one row in data area
232 "(ses-column-widths [7])\n"
233 "(ses-column-printers [nil])\n"
234 "(ses-default-printer \"%.7g\")\n"
235 "(ses-header-row 0)\n"
236 ses-initial-global-parameters
237 ses-initial-file-trailer)
238 "The initial contents of an empty spreadsheet.")
240 (defconst ses-box-prop '(:box (:line-width 2 :style released-button))
241 "Display properties to create a raised box for cells in the header line.")
243 (defconst ses-standard-printer-functions
244 '(ses-center ses-center-span ses-dashfill ses-dashfill-span
245 ses-tildefill-span)
246 "List of print functions to be included in initial history of printer
247 functions. None of these standard-printer functions is suitable for use as a
248 column printer or a global-default printer because they invoke the column or
249 default printer and then modify its output.")
252 ;;----------------------------------------------------------------------------
253 ;; Local variables and constants
254 ;;----------------------------------------------------------------------------
256 (eval-and-compile
257 (defconst ses-localvars
258 '(ses--blank-line ses--cells ses--col-printers ses--col-widths ses--curcell
259 ses--curcell-overlay ses--default-printer ses--deferred-narrow
260 ses--deferred-recalc ses--deferred-write ses--file-format
261 ses--header-hscroll ses--header-row ses--header-string ses--linewidth
262 ses--numcols ses--numrows ses--symbolic-formulas ses--data-marker
263 ses--params-marker
264 ;;Global variables that we override
265 mode-line-process next-line-add-newlines transient-mark-mode)
266 "Buffer-local variables used by SES."))
268 ;;When compiling, create all the buffer locals and give them values
269 (eval-when-compile
270 (dolist (x ses-localvars)
271 (make-local-variable x)
272 (set x nil)))
274 ;;;This variable is documented as being permitted in file-locals:
275 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
277 (defconst ses-paramlines-plist
278 '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
279 ses--header-row -2 ses--file-format 1 ses--numrows 2
280 ses--numcols 3)
281 "Offsets from 'Global parameters' line to various parameter lines in the
282 data area of a spreadsheet.")
286 ;; "Side-effect variables". They are set in one function, altered in
287 ;; another as a side effect, then read back by the first, as a way of
288 ;; passing back more than one value. These declarations are just to make
289 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
290 ;; think the make-local-variable trick above is cleaner).
293 (defvar ses-relocate-return nil
294 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
295 `ses-relocate-all'. Set to 'delete if a cell-reference was deleted from a
296 formula--so the formula needs recalculation. Set to 'range if the size of a
297 `ses-range' was changed--so both the formula's value and list of dependents
298 need to be recalculated.")
300 (defvar ses-call-printer-return nil
301 "Set to t if last cell printer invoked by `ses-call-printer' requested
302 left-justification of the result. Set to error-signal if ses-call-printer
303 encountered an error during printing. Otherwise nil.")
305 (defvar ses-start-time nil
306 "Time when current operation started. Used by `ses-time-check' to decide
307 when to emit a progress message.")
310 ;;----------------------------------------------------------------------------
311 ;; Macros
312 ;;----------------------------------------------------------------------------
314 (defmacro ses-get-cell (row col)
315 "Return the cell structure that stores information about cell (ROW,COL)."
316 `(aref (aref ses--cells ,row) ,col))
318 ;; We might want to use defstruct here, but cells are explicitly used as
319 ;; arrays in ses-set-cell, so we'd need to fix this first. --Stef
320 (defsubst ses-make-cell (&optional symbol formula printer references)
321 (vector symbol formula printer references))
323 (defmacro ses-cell-symbol (row &optional col)
324 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
325 `(aref ,(if col `(ses-get-cell ,row ,col) row) 0))
327 (defmacro ses-cell-formula (row &optional col)
328 "From a CELL or a pair (ROW,COL), get the function that computes its value."
329 `(aref ,(if col `(ses-get-cell ,row ,col) row) 1))
331 (defmacro ses-cell-printer (row &optional col)
332 "From a CELL or a pair (ROW,COL), get the function that prints its value."
333 `(aref ,(if col `(ses-get-cell ,row ,col) row) 2))
335 (defmacro ses-cell-references (row &optional col)
336 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
337 functions refer to its value."
338 `(aref ,(if col `(ses-get-cell ,row ,col) row) 3))
340 (defmacro ses-cell-value (row &optional col)
341 "From a CELL or a pair (ROW,COL), get the current value for that cell."
342 `(symbol-value (ses-cell-symbol ,row ,col)))
344 (defmacro ses-col-width (col)
345 "Return the width for column COL."
346 `(aref ses--col-widths ,col))
348 (defmacro ses-col-printer (col)
349 "Return the default printer for column COL."
350 `(aref ses--col-printers ,col))
352 (defmacro ses-sym-rowcol (sym)
353 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0). Result
354 is nil if SYM is not a symbol that names a cell."
355 `(and (symbolp ,sym) (get ,sym 'ses-cell)))
357 (defmacro ses-cell (sym value formula printer references)
358 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
359 FORMULA, does not reprint using PRINTER, does not check REFERENCES. This is a
360 macro to prevent propagate-on-load viruses. Safety-checking for FORMULA and
361 PRINTER are deferred until first use."
362 (let ((rowcol (ses-sym-rowcol sym)))
363 (ses-formula-record formula)
364 (ses-printer-record printer)
365 (or (atom formula)
366 (eq safe-functions t)
367 (setq formula `(ses-safe-formula ,formula)))
368 (or (not printer)
369 (stringp printer)
370 (eq safe-functions t)
371 (setq printer `(ses-safe-printer ,printer)))
372 (aset (aref ses--cells (car rowcol))
373 (cdr rowcol)
374 (ses-make-cell sym formula printer references)))
375 (set sym value)
376 sym)
378 (defmacro ses-column-widths (widths)
379 "Load the vector of column widths from the spreadsheet file. This is a
380 macro to prevent propagate-on-load viruses."
381 (or (and (vectorp widths) (= (length widths) ses--numcols))
382 (error "Bad column-width vector"))
383 ;;To save time later, we also calculate the total width of each line in the
384 ;;print area (excluding the terminating newline)
385 (setq ses--col-widths widths
386 ses--linewidth (apply '+ -1 (mapcar '1+ widths))
387 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
390 (defmacro ses-column-printers (printers)
391 "Load the vector of column printers from the spreadsheet file and checks
392 them for safety. This is a macro to prevent propagate-on-load viruses."
393 (or (and (vectorp printers) (= (length printers) ses--numcols))
394 (error "Bad column-printers vector"))
395 (dotimes (x ses--numcols)
396 (aset printers x (ses-safe-printer (aref printers x))))
397 (setq ses--col-printers printers)
398 (mapc 'ses-printer-record printers)
401 (defmacro ses-default-printer (def)
402 "Load the global default printer from the spreadsheet file and checks it
403 for safety. This is a macro to prevent propagate-on-load viruses."
404 (setq ses--default-printer (ses-safe-printer def))
405 (ses-printer-record def)
408 (defmacro ses-header-row (row)
409 "Load the header row from the spreadsheet file and checks it
410 for safety. This is a macro to prevent propagate-on-load viruses."
411 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
412 (error "Bad header-row"))
413 (setq ses--header-row row)
416 (defmacro ses-dorange (curcell &rest body)
417 "Execute BODY repeatedly, with the variables `row' and `col' set to each
418 cell in the range specified by CURCELL. The range is available in the
419 variables `minrow', `maxrow', `mincol', and `maxcol'."
420 (declare (indent defun) (debug (form body)))
421 (let ((cur (make-symbol "cur"))
422 (min (make-symbol "min"))
423 (max (make-symbol "max"))
424 (r (make-symbol "r"))
425 (c (make-symbol "c")))
426 `(let* ((,cur ,curcell)
427 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
428 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
429 (let ((minrow (car ,min))
430 (maxrow (car ,max))
431 (mincol (cdr ,min))
432 (maxcol (cdr ,max))
433 row col)
434 (if (or (> minrow maxrow) (> mincol maxcol))
435 (error "Empty range"))
436 (dotimes (,r (- maxrow minrow -1))
437 (setq row (+ ,r minrow))
438 (dotimes (,c (- maxcol mincol -1))
439 (setq col (+ ,c mincol))
440 ,@body))))))
442 ;;Support for coverage testing.
443 (defmacro 1value (form)
444 "For code-coverage testing, indicate that FORM is expected to always have
445 the same value."
446 form)
447 (defmacro noreturn (form)
448 "For code-coverage testing, indicate that FORM will always signal an error."
449 form)
452 ;;----------------------------------------------------------------------------
453 ;; Utility functions
454 ;;----------------------------------------------------------------------------
456 (defun ses-vector-insert (array idx new)
457 "Create a new vector which is one larger than ARRAY and has NEW inserted
458 before element IDX."
459 (let* ((len (length array))
460 (result (make-vector (1+ len) new)))
461 (dotimes (x len)
462 (aset result
463 (if (< x idx) x (1+ x))
464 (aref array x)))
465 result))
467 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
468 (defun ses-vector-delete (array idx count)
469 "Create a new vector which is a copy of ARRAY with COUNT objects removed
470 starting at element IDX. ARRAY is either a vector or a symbol whose value
471 is a vector--if a symbol, the new vector is assigned as the symbol's value."
472 (let* ((a (if (arrayp array) array (symbol-value array)))
473 (len (- (length a) count))
474 (result (make-vector len nil)))
475 (dotimes (x len)
476 (aset result x (aref a (if (< x idx) x (+ x count)))))
477 (if (symbolp array)
478 (set array result))
479 result))
481 (defun ses-delete-line (count)
482 "Like `kill-line', but no kill ring."
483 (let ((pos (point)))
484 (forward-line count)
485 (delete-region pos (point))))
487 (defun ses-printer-validate (printer)
488 "Signals an error if PRINTER is not a valid SES cell printer."
489 (or (not printer)
490 (stringp printer)
491 (functionp printer)
492 (and (stringp (car-safe printer)) (not (cdr printer)))
493 (error "Invalid printer function"))
494 printer)
496 (defun ses-printer-record (printer)
497 "Add PRINTER to `ses-read-printer-history' if not already there, after first
498 checking that it is a valid printer function."
499 (ses-printer-validate printer)
500 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
501 (if printer
502 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
504 (defun ses-formula-record (formula)
505 "If FORMULA is of the form 'symbol, adds it to the list of symbolic formulas
506 for this spreadsheet."
507 (when (and (eq (car-safe formula) 'quote)
508 (symbolp (cadr formula)))
509 (add-to-list 'ses--symbolic-formulas
510 (list (symbol-name (cadr formula))))))
512 (defun ses-column-letter (col)
513 "Return the alphabetic name of column number COL.
514 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
515 (let ((units (char-to-string (+ ?A (% col 26)))))
516 (if (< col 26)
517 units
518 (concat (ses-column-letter (1- (/ col 26))) units))))
520 (defun ses-create-cell-symbol (row col)
521 "Produce a symbol that names the cell (ROW,COL). (0,0) => 'A1."
522 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
524 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
525 "Create buffer-local variables for cells. This is undoable."
526 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
527 buffer-undo-list)
528 (let (sym xrow xcol)
529 (dotimes (row (1+ (- maxrow minrow)))
530 (dotimes (col (1+ (- maxcol mincol)))
531 (setq xrow (+ row minrow)
532 xcol (+ col mincol)
533 sym (ses-create-cell-symbol xrow xcol))
534 (put sym 'ses-cell (cons xrow xcol))
535 (make-local-variable sym)))))
537 ;;We do not delete the ses-cell properties for the cell-variables, in case a
538 ;;formula that refers to this cell is in the kill-ring and is later pasted
539 ;;back in.
540 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
541 "Destroy buffer-local variables for cells. This is undoable."
542 (let (sym)
543 (dotimes (row (1+ (- maxrow minrow)))
544 (dotimes (col (1+ (- maxcol mincol)))
545 (setq sym (ses-create-cell-symbol (+ row minrow) (+ col mincol)))
546 (if (boundp sym)
547 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
548 buffer-undo-list))
549 (kill-local-variable sym))))
550 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
551 buffer-undo-list))
553 (defun ses-reset-header-string ()
554 "Flags the header string for update. Upon undo, the header string will be
555 updated again."
556 (push '(apply ses-reset-header-string) buffer-undo-list)
557 (setq ses--header-hscroll -1))
559 ;;Split this code off into a function to avoid coverage-testing difficulties
560 (defun ses-time-check (format arg)
561 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
562 and (eval ARG) and reset `ses-start-time' to the current time."
563 (when (> (- (float-time) ses-start-time) 1.0)
564 (message format (eval arg))
565 (setq ses-start-time (float-time)))
566 nil)
569 ;;----------------------------------------------------------------------------
570 ;; The cells
571 ;;----------------------------------------------------------------------------
573 (defun ses-set-cell (row col field val)
574 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
575 cell (ROW,COL). This is undoable. The cell's data will be updated through
576 `post-command-hook'."
577 (let ((cell (ses-get-cell row col))
578 (elt (plist-get '(value t symbol 0 formula 1 printer 2 references 3)
579 field))
580 change)
581 (or elt (signal 'args-out-of-range nil))
582 (setq change (if (eq elt t)
583 (ses-set-with-undo (ses-cell-symbol cell) val)
584 (ses-aset-with-undo cell elt val)))
585 (if change
586 (add-to-list 'ses--deferred-write (cons row col))))
587 nil) ;Make coverage-tester happy
589 (defun ses-cell-set-formula (row col formula)
590 "Store a new formula for (ROW . COL) and enqueues the cell for
591 recalculation via `post-command-hook'. Updates the reference lists for the
592 cells that this cell refers to. Does not update cell value or reprint the
593 cell. To avoid inconsistencies, this function is not interruptible, which
594 means Emacs will crash if FORMULA contains a circular list."
595 (let* ((cell (ses-get-cell row col))
596 (old (ses-cell-formula cell)))
597 (let ((sym (ses-cell-symbol cell))
598 (oldref (ses-formula-references old))
599 (newref (ses-formula-references formula))
600 (inhibit-quit t)
601 x xrow xcol)
602 (add-to-list 'ses--deferred-recalc sym)
603 ;;Delete old references from this cell. Skip the ones that are also
604 ;;in the new list.
605 (dolist (ref oldref)
606 (unless (memq ref newref)
607 (setq x (ses-sym-rowcol ref)
608 xrow (car x)
609 xcol (cdr x))
610 (ses-set-cell xrow xcol 'references
611 (delq sym (ses-cell-references xrow xcol)))))
612 ;;Add new ones. Skip ones left over from old list
613 (dolist (ref newref)
614 (setq x (ses-sym-rowcol ref)
615 xrow (car x)
616 xcol (cdr x)
617 x (ses-cell-references xrow xcol))
618 (or (memq sym x)
619 (ses-set-cell xrow xcol 'references (cons sym x))))
620 (ses-formula-record formula)
621 (ses-set-cell row col 'formula formula))))
623 (defun ses-calculate-cell (row col force)
624 "Calculate and print the value for cell (ROW,COL) using the cell's formula
625 function and print functions, if any. Result is nil for normal operation, or
626 the error signal if the formula or print function failed. The old value is
627 left unchanged if it was *skip* and the new value is nil.
628 Any cells that depend on this cell are queued for update after the end of
629 processing for the current keystroke, unless the new value is the same as
630 the old and FORCE is nil."
631 (let ((cell (ses-get-cell row col))
632 formula-error printer-error)
633 (let ((oldval (ses-cell-value cell))
634 (formula (ses-cell-formula cell))
635 newval)
636 (when (eq (car-safe formula) 'ses-safe-formula)
637 (setq formula (ses-safe-formula (cadr formula)))
638 (ses-set-cell row col 'formula formula))
639 (condition-case sig
640 (setq newval (eval formula))
641 (error
642 (setq formula-error sig
643 newval '*error*)))
644 (if (and (not newval) (eq oldval '*skip*))
645 ;;Don't lose the *skip* - previous field spans this one
646 (setq newval '*skip*))
647 (when (or force (not (eq newval oldval)))
648 (add-to-list 'ses--deferred-write (cons row col)) ;In case force=t
649 (ses-set-cell row col 'value newval)
650 (dolist (ref (ses-cell-references cell))
651 (add-to-list 'ses--deferred-recalc ref))))
652 (setq printer-error (ses-print-cell row col))
653 (or formula-error printer-error)))
655 (defun ses-clear-cell (row col)
656 "Delete formula and printer for cell (ROW,COL)."
657 (ses-set-cell row col 'printer nil)
658 (ses-cell-set-formula row col nil))
660 (defun ses-update-cells (list &optional force)
661 "Recalculate cells in LIST, checking for dependency loops. Prints
662 progress messages every second. Dependent cells are not recalculated
663 if the cell's value is unchanged and FORCE is nil."
664 (let ((ses--deferred-recalc list)
665 (nextlist list)
666 (pos (point))
667 curlist prevlist rowcol formula)
668 (with-temp-message " "
669 (while (and ses--deferred-recalc (not (equal nextlist prevlist)))
670 ;;In each loop, recalculate cells that refer only to other cells that
671 ;;have already been recalculated or aren't in the recalculation
672 ;;region. Repeat until all cells have been processed or until the
673 ;;set of cells being worked on stops changing.
674 (if prevlist
675 (message "Recalculating... (%d cells left)"
676 (length ses--deferred-recalc)))
677 (setq curlist ses--deferred-recalc
678 ses--deferred-recalc nil
679 prevlist nextlist)
680 (while curlist
681 (setq rowcol (ses-sym-rowcol (car curlist))
682 formula (ses-cell-formula (car rowcol) (cdr rowcol)))
683 (or (catch 'ref
684 (dolist (ref (ses-formula-references formula))
685 (when (or (memq ref curlist)
686 (memq ref ses--deferred-recalc))
687 ;;This cell refers to another that isn't done yet
688 (add-to-list 'ses--deferred-recalc (car curlist))
689 (throw 'ref t))))
690 ;;ses-update-cells is called from post-command-hook, so
691 ;;inhibit-quit is implicitly bound to t.
692 (when quit-flag
693 ;;Abort the recalculation. User will probably undo now.
694 (error "Quit"))
695 (ses-calculate-cell (car rowcol) (cdr rowcol) force))
696 (setq curlist (cdr curlist)))
697 (dolist (ref ses--deferred-recalc)
698 (add-to-list 'nextlist ref))
699 (setq nextlist (sort (copy-sequence nextlist) 'string<))
700 (if (equal nextlist prevlist)
701 ;;We'll go around the loop one more time.
702 (add-to-list 'nextlist t)))
703 (when ses--deferred-recalc
704 ;;Just couldn't finish these
705 (dolist (x ses--deferred-recalc)
706 (let ((rowcol (ses-sym-rowcol x)))
707 (ses-set-cell (car rowcol) (cdr rowcol) 'value '*error*)
708 (1value (ses-print-cell (car rowcol) (cdr rowcol)))))
709 (error "Circular references: %s" ses--deferred-recalc))
710 (message " "))
711 ;;Can't use save-excursion here: if the cell under point is
712 ;;updated, save-excusion's marker will move past the cell.
713 (goto-char pos)))
716 ;;----------------------------------------------------------------------------
717 ;; The print area
718 ;;----------------------------------------------------------------------------
720 (defun ses-in-print-area ()
721 "Returns t if point is in print area of spreadsheet."
722 (<= (point) ses--data-marker))
724 ;;We turn off point-motion-hooks and explicitly position the cursor, in case
725 ;;the intangible properties have gotten screwed up (e.g., when
726 ;;ses-goto-print is called during a recursive ses-print-cell).
727 (defun ses-goto-print (row col)
728 "Move point to print area for cell (ROW,COL)."
729 (let ((inhibit-point-motion-hooks t))
730 (goto-char (point-min))
731 (forward-line row)
732 (dotimes (c col)
733 (forward-char (1+ (ses-col-width c))))))
735 (defun ses-set-curcell ()
736 "Sets `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
737 region, or nil if cursor is not at a cell."
738 (if (or (not mark-active)
739 deactivate-mark
740 (= (region-beginning) (region-end)))
741 ;;Single cell
742 (setq ses--curcell (get-text-property (point) 'intangible))
743 ;;Range
744 (let ((bcell (get-text-property (region-beginning) 'intangible))
745 (ecell (get-text-property (1- (region-end)) 'intangible)))
746 (when (= (region-end) ses--data-marker)
747 ;;Correct for overflow
748 (setq ecell (get-text-property (- (region-end) 2) 'intangible)))
749 (setq ses--curcell (if (and bcell ecell)
750 (cons bcell ecell)
751 nil))))
752 nil)
754 (defun ses-check-curcell (&rest args)
755 "Signal an error if ses--curcell is inappropriate. The end marker is
756 appropriate if some argument is 'end. A range is appropriate if some
757 argument is 'range. A single cell is appropriate unless some argument is
758 'needrange."
759 (if (eq ses--curcell t)
760 ;;curcell recalculation was postponed, but user typed ahead
761 (ses-set-curcell))
762 (cond
763 ((not ses--curcell)
764 (or (memq 'end args)
765 (error "Not at cell")))
766 ((consp ses--curcell)
767 (or (memq 'range args)
768 (memq 'needrange args)
769 (error "Can't use a range")))
770 ((memq 'needrange args)
771 (error "Need a range"))))
773 (defun ses-print-cell (row col)
774 "Format and print the value of cell (ROW,COL) to the print area.
775 Use the cell's printer function. If the cell's new print form is too wide,
776 it will spill over into the following cell, but will not run off the end of the
777 row or overwrite the next non-nil field. Result is nil for normal operation,
778 or the error signal if the printer function failed and the cell was formatted
779 with \"%s\". If the cell's value is *skip*, nothing is printed because the
780 preceding cell has spilled over."
781 (catch 'ses-print-cell
782 (let* ((cell (ses-get-cell row col))
783 (value (ses-cell-value cell))
784 (printer (ses-cell-printer cell))
785 (maxcol (1+ col))
786 text sig startpos x)
787 ;;Create the string to print
788 (cond
789 ((eq value '*skip*)
790 ;;Don't print anything
791 (throw 'ses-print-cell nil))
792 ((eq value '*error*)
793 (setq text (make-string (ses-col-width col) ?#)))
795 ;;Deferred safety-check on printer
796 (if (eq (car-safe printer) 'ses-safe-printer)
797 (ses-set-cell row col 'printer
798 (setq printer (ses-safe-printer (cadr printer)))))
799 ;;Print the value
800 (setq text (ses-call-printer (or printer
801 (ses-col-printer col)
802 ses--default-printer)
803 value))
804 (if (consp ses-call-printer-return)
805 ;;Printer returned an error
806 (setq sig ses-call-printer-return))))
807 ;;Adjust print width to match column width
808 (let ((width (ses-col-width col))
809 (len (length text)))
810 (cond
811 ((< len width)
812 ;;Fill field to length with spaces
813 (setq len (make-string (- width len) ?\s)
814 text (if (eq ses-call-printer-return t)
815 (concat text len)
816 (concat len text))))
817 ((> len width)
818 ;;Spill over into following cells, if possible
819 (let ((maxwidth width))
820 (while (and (> len maxwidth)
821 (< maxcol ses--numcols)
822 (or (not (setq x (ses-cell-value row maxcol)))
823 (eq x '*skip*)))
824 (unless x
825 ;;Set this cell to '*skip* so it won't overwrite our spillover
826 (ses-set-cell row maxcol 'value '*skip*))
827 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
828 maxcol (1+ maxcol)))
829 (if (<= len maxwidth)
830 ;;Fill to complete width of all the fields spanned
831 (setq text (concat text (make-string (- maxwidth len) ?\s)))
832 ;;Not enough room to end of line or next non-nil field. Truncate
833 ;;if string or decimal; otherwise fill with error indicator
834 (setq sig `(error "Too wide" ,text))
835 (cond
836 ((stringp value)
837 (setq text (substring text 0 maxwidth)))
838 ((and (numberp value)
839 (string-match "\\.[0-9]+" text)
840 (>= 0 (setq width
841 (- len maxwidth
842 (- (match-end 0) (match-beginning 0))))))
843 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
844 (setq text (concat (substring text
846 (- (match-beginning 0) width))
847 (substring text (match-end 0)))))
849 (setq text (make-string maxwidth ?#)))))))))
850 ;;Substitute question marks for tabs and newlines. Newlines are
851 ;;used as row-separators; tabs could confuse the reimport logic.
852 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
853 (ses-goto-print row col)
854 (setq startpos (point))
855 ;;Install the printed result. This is not interruptible.
856 (let ((inhibit-read-only t)
857 (inhibit-quit t))
858 (delete-char (1+ (length text)))
859 ;;We use concat instead of inserting separate strings in order to
860 ;;reduce the number of cells in the undo list.
861 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
862 ;;We use set-text-properties to prevent a wacky print function
863 ;;from inserting rogue properties, and to ensure that the keymap
864 ;;property is inherited (is it a bug that only unpropertied strings
865 ;;actually inherit from surrounding text?)
866 (set-text-properties 0 (length x) nil x)
867 (insert-and-inherit x)
868 (put-text-property startpos (point) 'intangible
869 (ses-cell-symbol cell))
870 (when (and (zerop row) (zerop col))
871 ;;Reconstruct special beginning-of-buffer attributes
872 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
873 (put-text-property (point-min) (point) 'read-only 'ses)
874 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)))
875 (if (= row (1- ses--header-row))
876 ;;This line is part of the header - force recalc
877 (ses-reset-header-string))
878 ;;If this cell (or a preceding one on the line) previously spilled over
879 ;;and has gotten shorter, redraw following cells on line recursively.
880 (when (and (< maxcol ses--numcols)
881 (eq (ses-cell-value row maxcol) '*skip*))
882 (ses-set-cell row maxcol 'value nil)
883 (ses-print-cell row maxcol))
884 ;;Return to start of cell
885 (goto-char startpos)
886 sig)))
888 (defun ses-call-printer (printer &optional value)
889 "Invokes PRINTER (a string or parenthesized string or function-symbol or
890 lambda of one argument) on VALUE. Result is the printed cell as a string.
891 The variable `ses-call-printer-return' is set to t if the printer used
892 parenthesis to request left-justification, or the error-signal if the
893 printer signaled one (and \"%s\" is used as the default printer), else nil."
894 (setq ses-call-printer-return nil)
895 (unless value
896 (setq value ""))
897 (condition-case signal
898 (cond
899 ((stringp printer)
900 (format printer value))
901 ((stringp (car-safe printer))
902 (setq ses-call-printer-return t)
903 (format (car printer) value))
905 (setq value (funcall printer value))
906 (if (stringp value)
907 value
908 (or (stringp (car-safe value))
909 (error "Printer should return \"string\" or (\"string\")"))
910 (setq ses-call-printer-return t)
911 (car value))))
912 (error
913 (setq ses-call-printer-return signal)
914 (prin1-to-string value t))))
916 (defun ses-adjust-print-width (col change)
917 "Insert CHANGE spaces in front of column COL, or at end of line if
918 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
919 inhibit-quit to t."
920 (let ((inhibit-read-only t)
921 (blank (if (> change 0) (make-string change ?\s)))
922 (at-end (= col ses--numcols)))
923 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
924 ;;ses-set-with-undo always returns t for strings.
925 (1value (ses-set-with-undo 'ses--blank-line
926 (concat (make-string ses--linewidth ?\s) "\n")))
927 (dotimes (row ses--numrows)
928 (ses-goto-print row col)
929 (when at-end
930 ;;Insert new columns before newline
931 (let ((inhibit-point-motion-hooks t))
932 (backward-char 1)))
933 (if blank
934 (insert blank)
935 (delete-char (- change))))))
937 (defun ses-print-cell-new-width (row col)
938 "Same as ses-print-cell, except if the cell's value is *skip*, the preceding
939 nonskipped cell is reprinted. This function is used when the width of
940 cell (ROW,COL) has changed."
941 (if (not (eq (ses-cell-value row col) '*skip*))
942 (ses-print-cell row col)
943 ;;Cell was skipped over - reprint previous
944 (ses-goto-print row col)
945 (backward-char 1)
946 (let ((rowcol (ses-sym-rowcol (get-text-property (point) 'intangible))))
947 (ses-print-cell (car rowcol) (cdr rowcol)))))
950 ;;----------------------------------------------------------------------------
951 ;; The data area
952 ;;----------------------------------------------------------------------------
954 (defun ses-narrowed-p () (/= (- (point-max) (point-min)) (buffer-size)))
956 (defun ses-widen ()
957 "Turn off narrowing, to be reenabled at end of command loop."
958 (if (ses-narrowed-p)
959 (setq ses--deferred-narrow t))
960 (widen))
962 (defun ses-goto-data (def &optional col)
963 "Move point to data area for (DEF,COL). If DEF is a row
964 number, COL is the column number for a data cell -- otherwise DEF
965 is one of the symbols ses--col-widths, ses--col-printers,
966 ses--default-printer, ses--numrows, or ses--numcols."
967 (ses-widen)
968 (let ((inhibit-point-motion-hooks t)) ;In case intangible attrs are wrong
969 (if col
970 ;;It's a cell
971 (progn
972 (goto-char ses--data-marker)
973 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
974 ;;Convert def-symbol to offset
975 (setq def (plist-get ses-paramlines-plist def))
976 (or def (signal 'args-out-of-range nil))
977 (goto-char ses--params-marker)
978 (forward-line def))))
980 (defun ses-set-parameter (def value &optional elem)
981 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
982 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
983 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
984 (save-excursion
985 ;;We call ses-goto-data early, using the old values of numrows and
986 ;;numcols in case one of them is being changed.
987 (ses-goto-data def)
988 (let ((inhibit-read-only t)
989 (fmt (plist-get '(ses--col-widths "(ses-column-widths %S)"
990 ses--col-printers "(ses-column-printers %S)"
991 ses--default-printer "(ses-default-printer %S)"
992 ses--header-row "(ses-header-row %S)"
993 ses--file-format " %S ;SES file-format"
994 ses--numrows " %S ;numrows"
995 ses--numcols " %S ;numcols")
996 def))
997 oldval)
998 (if elem
999 (progn
1000 (setq oldval (aref (symbol-value def) elem))
1001 (aset (symbol-value def) elem value))
1002 (setq oldval (symbol-value def))
1003 (set def value))
1004 ;;Special undo since it's outside the narrowed buffer
1005 (let (buffer-undo-list)
1006 (delete-region (point) (line-end-position))
1007 (insert (format fmt (symbol-value def))))
1008 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1011 (defun ses-write-cells ()
1012 "Write cells in `ses--deferred-write' from local variables to data area.
1013 Newlines in the data are escaped."
1014 (let* ((inhibit-read-only t)
1015 (print-escape-newlines t)
1016 rowcol row col cell sym formula printer text)
1017 (setq ses-start-time (float-time))
1018 (with-temp-message " "
1019 (save-excursion
1020 (while ses--deferred-write
1021 (ses-time-check "Writing... (%d cells left)"
1022 '(length ses--deferred-write))
1023 (setq rowcol (pop ses--deferred-write)
1024 row (car rowcol)
1025 col (cdr rowcol)
1026 cell (ses-get-cell row col)
1027 sym (ses-cell-symbol cell)
1028 formula (ses-cell-formula cell)
1029 printer (ses-cell-printer cell))
1030 (if (eq (car-safe formula) 'ses-safe-formula)
1031 (setq formula (cadr formula)))
1032 (if (eq (car-safe printer) 'ses-safe-printer)
1033 (setq printer (cadr printer)))
1034 ;;This is noticably faster than (format "%S %S %S %S %S")
1035 (setq text (concat "(ses-cell "
1036 (symbol-name sym)
1038 (prin1-to-string (symbol-value sym))
1040 (prin1-to-string formula)
1042 (prin1-to-string printer)
1044 (if (atom (ses-cell-references cell))
1045 "nil"
1046 (concat "("
1047 (mapconcat 'symbol-name
1048 (ses-cell-references cell)
1049 " ")
1050 ")"))
1051 ")"))
1052 (ses-goto-data row col)
1053 (delete-region (point) (line-end-position))
1054 (insert text)))
1055 (message " "))))
1058 ;;----------------------------------------------------------------------------
1059 ;; Formula relocation
1060 ;;----------------------------------------------------------------------------
1062 (defun ses-formula-references (formula &optional result-so-far)
1063 "Produce a list of symbols for cells that this formula's value
1064 refers to. For recursive calls, RESULT-SO-FAR is the list being constructed,
1065 or t to get a wrong-type-argument error when the first reference is found."
1066 (if (atom formula)
1067 (if (ses-sym-rowcol formula)
1068 ;;Entire formula is one symbol
1069 (add-to-list 'result-so-far formula)
1070 ) ;;Ignore other atoms
1071 (dolist (cur formula)
1072 (cond
1073 ((ses-sym-rowcol cur)
1074 ;;Save this reference
1075 (add-to-list 'result-so-far cur))
1076 ((eq (car-safe cur) 'ses-range)
1077 ;;All symbols in range are referenced
1078 (dolist (x (cdr (macroexpand cur)))
1079 (add-to-list 'result-so-far x)))
1080 ((and (consp cur) (not (eq (car cur) 'quote)))
1081 ;;Recursive call for subformulas
1082 (setq result-so-far (ses-formula-references cur result-so-far)))
1084 ;;Ignore other stuff
1085 ))))
1086 result-so-far)
1088 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1089 "Relocate one symbol SYM, whichs corresponds to ROWCOL (a cons of ROW and
1090 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1091 by (ROWINCR,COLINCR)."
1092 (let ((row (car rowcol))
1093 (col (cdr rowcol)))
1094 (if (or (< row startrow) (< col startcol))
1096 (setq row (+ row rowincr)
1097 col (+ col colincr))
1098 (if (and (>= row startrow) (>= col startcol)
1099 (< row ses--numrows) (< col ses--numcols))
1100 ;;Relocate this variable
1101 (ses-create-cell-symbol row col)
1102 ;;Delete reference to a deleted cell
1103 nil))))
1105 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1106 "Produce a copy of FORMULA where all symbols that refer to cells in row
1107 STARTROW or above and col STARTCOL or above are altered by adding ROWINCR
1108 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1109 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1110 => (+ A1 B2 C4)
1111 If ROWINCR or COLINCR is negative, references to cells being deleted are
1112 removed. Example:
1113 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1114 => (+ A1 C3)
1115 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1116 (let (rowcol result)
1117 (if (or (atom formula) (eq (car formula) 'quote))
1118 (if (setq rowcol (ses-sym-rowcol formula))
1119 (ses-relocate-symbol formula rowcol
1120 startrow startcol rowincr colincr)
1121 formula) ;Pass through as-is
1122 (dolist (cur formula)
1123 (setq rowcol (ses-sym-rowcol cur))
1124 (cond
1125 (rowcol
1126 (setq cur (ses-relocate-symbol cur rowcol
1127 startrow startcol rowincr colincr))
1128 (if cur
1129 (push cur result)
1130 ;;Reference to a deleted cell. Set a flag in ses-relocate-return.
1131 ;;don't change the flag if it's already 'range, since range
1132 ;;implies 'delete.
1133 (unless ses-relocate-return
1134 (setq ses-relocate-return 'delete))))
1135 ((eq (car-safe cur) 'ses-range)
1136 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1137 (if cur
1138 (push cur result)))
1139 ((or (atom cur) (eq (car cur) 'quote))
1140 ;;Constants pass through unchanged
1141 (push cur result))
1143 ;;Recursively copy and alter subformulas
1144 (push (ses-relocate-formula cur startrow startcol
1145 rowincr colincr)
1146 result))))
1147 (nreverse result))))
1149 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1150 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1151 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1152 new range, or nil if the entire range is deleted. If new rows are being added
1153 just beyond the end of a row range, or new columns just beyond a column range,
1154 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1155 if the range was altered."
1156 (let* ((minorig (cadr range))
1157 (minrowcol (ses-sym-rowcol minorig))
1158 (min (ses-relocate-symbol minorig minrowcol
1159 startrow startcol
1160 rowincr colincr))
1161 (maxorig (nth 2 range))
1162 (maxrowcol (ses-sym-rowcol maxorig))
1163 (max (ses-relocate-symbol maxorig maxrowcol
1164 startrow startcol
1165 rowincr colincr))
1166 field)
1167 (cond
1168 ((and (not min) (not max))
1169 (setq range nil)) ;;The entire range is deleted
1170 ((zerop colincr)
1171 ;;Inserting or deleting rows
1172 (setq field 'car)
1173 (if (not min)
1174 ;;Chopped off beginning of range
1175 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1176 ses-relocate-return 'range))
1177 (if (not max)
1178 (if (> rowincr 0)
1179 ;;Trying to insert a nonexistent row
1180 (setq max (ses-create-cell-symbol (1- ses--numrows)
1181 (cdr minrowcol)))
1182 ;;End of range is being deleted
1183 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1184 ses-relocate-return 'range))
1185 (and (> rowincr 0)
1186 (= (car maxrowcol) (1- startrow))
1187 (= (cdr minrowcol) (cdr maxrowcol))
1188 ;;Insert after ending row of vertical range - include it
1189 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1190 (cdr maxrowcol))))))
1192 ;;Inserting or deleting columns
1193 (setq field 'cdr)
1194 (if (not min)
1195 ;;Chopped off beginning of range
1196 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1197 ses-relocate-return 'range))
1198 (if (not max)
1199 (if (> colincr 0)
1200 ;;Trying to insert a nonexistent column
1201 (setq max (ses-create-cell-symbol (car maxrowcol)
1202 (1- ses--numcols)))
1203 ;;End of range is being deleted
1204 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1205 ses-relocate-return 'range))
1206 (and (> colincr 0)
1207 (= (cdr maxrowcol) (1- startcol))
1208 (= (car minrowcol) (car maxrowcol))
1209 ;;Insert after ending column of horizontal range - include it
1210 (setq max (ses-create-cell-symbol (car maxrowcol)
1211 (+ startcol colincr -1)))))))
1212 (when range
1213 (if (/= (- (funcall field maxrowcol)
1214 (funcall field minrowcol))
1215 (- (funcall field (ses-sym-rowcol max))
1216 (funcall field (ses-sym-rowcol min))))
1217 ;;This range has changed size
1218 (setq ses-relocate-return 'range))
1219 (list 'ses-range min max))))
1221 (defun ses-relocate-all (minrow mincol rowincr colincr)
1222 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1223 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1224 to each symbol."
1225 (let (reform)
1226 (let (mycell newval)
1227 (dotimes-with-progress-reporter
1228 (row ses--numrows) "Relocating formulas..."
1229 (dotimes (col ses--numcols)
1230 (setq ses-relocate-return nil
1231 mycell (ses-get-cell row col)
1232 newval (ses-relocate-formula (ses-cell-formula mycell)
1233 minrow mincol rowincr colincr))
1234 (ses-set-cell row col 'formula newval)
1235 (if (eq ses-relocate-return 'range)
1236 ;;This cell contains a (ses-range X Y) where a cell has been
1237 ;;inserted or deleted in the middle of the range.
1238 (push (cons row col) reform))
1239 (if ses-relocate-return
1240 ;;This cell referred to a cell that's been deleted or is no
1241 ;;longer part of the range. We can't fix that now because
1242 ;;reference lists cells have been partially updated.
1243 (add-to-list 'ses--deferred-recalc
1244 (ses-create-cell-symbol row col)))
1245 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1246 minrow mincol rowincr colincr))
1247 (ses-set-cell row col 'references newval)
1248 (and (>= row minrow) (>= col mincol)
1249 (ses-set-cell row col 'symbol
1250 (ses-create-cell-symbol row col))))))
1251 ;;Relocate the cell values
1252 (let (oldval myrow mycol xrow xcol)
1253 (cond
1254 ((and (<= rowincr 0) (<= colincr 0))
1255 ;;Deletion of rows and/or columns
1256 (dotimes-with-progress-reporter
1257 (row (- ses--numrows minrow)) "Relocating variables..."
1258 (setq myrow (+ row minrow))
1259 (dotimes (col (- ses--numcols mincol))
1260 (setq mycol (+ col mincol)
1261 xrow (- myrow rowincr)
1262 xcol (- mycol colincr))
1263 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1264 (setq oldval (ses-cell-value xrow xcol))
1265 ;;Cell is off the end of the array
1266 (setq oldval (symbol-value (ses-create-cell-symbol xrow xcol))))
1267 (ses-set-cell myrow mycol 'value oldval))))
1268 ((and (wholenump rowincr) (wholenump colincr))
1269 ;;Insertion of rows and/or columns. Run the loop backwards.
1270 (let ((disty (1- ses--numrows))
1271 (distx (1- ses--numcols))
1272 myrow mycol)
1273 (dotimes-with-progress-reporter
1274 (row (- ses--numrows minrow)) "Relocating variables..."
1275 (setq myrow (- disty row))
1276 (dotimes (col (- ses--numcols mincol))
1277 (setq mycol (- distx col)
1278 xrow (- myrow rowincr)
1279 xcol (- mycol colincr))
1280 (if (or (< xrow minrow) (< xcol mincol))
1281 ;;Newly-inserted value
1282 (setq oldval nil)
1283 ;;Transfer old value
1284 (setq oldval (ses-cell-value xrow xcol)))
1285 (ses-set-cell myrow mycol 'value oldval)))
1286 t)) ;Make testcover happy by returning non-nil here
1288 (error "ROWINCR and COLINCR must have the same sign"))))
1289 ;;Reconstruct reference lists for cells that contain ses-ranges that
1290 ;;have changed size.
1291 (when reform
1292 (message "Fixing ses-ranges...")
1293 (let (row col)
1294 (setq ses-start-time (float-time))
1295 (while reform
1296 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1297 (setq row (caar reform)
1298 col (cdar reform)
1299 reform (cdr reform))
1300 (ses-cell-set-formula row col (ses-cell-formula row col))))
1301 (message nil))))
1304 ;;----------------------------------------------------------------------------
1305 ;; Undo control
1306 ;;----------------------------------------------------------------------------
1308 (defun ses-begin-change ()
1309 "For undo, remember point before we start changing hidden stuff."
1310 (let ((inhibit-read-only t))
1311 (insert-and-inherit "X")
1312 (delete-region (1- (point)) (point))))
1314 (defun ses-set-with-undo (sym newval)
1315 "Like set, but undoable. Result is t if value has changed."
1316 ;;We try to avoid adding redundant entries to the undo list, but this is
1317 ;;unavoidable for strings because equal ignores text properties and there's
1318 ;;no easy way to get the whole property list to see if it's different!
1319 (unless (and (boundp sym)
1320 (equal (symbol-value sym) newval)
1321 (not (stringp newval)))
1322 (push (if (boundp sym)
1323 `(apply ses-set-with-undo ,sym ,(symbol-value sym))
1324 `(apply ses-unset-with-undo ,sym))
1325 buffer-undo-list)
1326 (set sym newval)
1329 (defun ses-unset-with-undo (sym)
1330 "Set SYM to be unbound. This is undoable."
1331 (when (1value (boundp sym)) ;;Always bound, except after a programming error
1332 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
1333 (makunbound sym)))
1335 (defun ses-aset-with-undo (array idx newval)
1336 "Like aset, but undoable. Result is t if element has changed"
1337 (unless (equal (aref array idx) newval)
1338 (push `(apply ses-aset-with-undo ,array ,idx ,(aref array idx)) buffer-undo-list)
1339 (aset array idx newval)
1343 ;;----------------------------------------------------------------------------
1344 ;; Startup for major mode
1345 ;;----------------------------------------------------------------------------
1347 (defun ses-load ()
1348 "Parse the current buffer and sets up buffer-local variables. Does not
1349 execute cell formulas or print functions."
1350 (widen)
1351 ;;Read our global parameters, which should be a 3-element list
1352 (goto-char (point-max))
1353 (search-backward ";; Local Variables:\n" nil t)
1354 (backward-list 1)
1355 (setq ses--params-marker (point-marker))
1356 (let ((params (condition-case nil (read (current-buffer)) (error nil))))
1357 (or (and (= (safe-length params) 3)
1358 (numberp (car params))
1359 (numberp (cadr params))
1360 (>= (cadr params) 0)
1361 (numberp (nth 2 params))
1362 (> (nth 2 params) 0))
1363 (error "Invalid SES file"))
1364 (setq ses--file-format (car params)
1365 ses--numrows (cadr params)
1366 ses--numcols (nth 2 params))
1367 (when (= ses--file-format 1)
1368 (let (buffer-undo-list) ;This is not undoable
1369 (ses-goto-data 'ses--header-row)
1370 (insert "(ses-header-row 0)\n")
1371 (ses-set-parameter 'ses--file-format 2)
1372 (message "Upgrading from SES-1 file format")))
1373 (or (= ses--file-format 2)
1374 (error "This file needs a newer version of the SES library code"))
1375 (ses-create-cell-variable-range 0 (1- ses--numrows) 0 (1- ses--numcols))
1376 ;;Initialize cell array
1377 (setq ses--cells (make-vector ses--numrows nil))
1378 (dotimes (row ses--numrows)
1379 (aset ses--cells row (make-vector ses--numcols nil))))
1380 ;;Skip over print area, which we assume is correct
1381 (goto-char (point-min))
1382 (forward-line ses--numrows)
1383 (or (looking-at ses-print-data-boundary)
1384 (error "Missing marker between print and data areas"))
1385 (forward-char 1)
1386 (setq ses--data-marker (point-marker))
1387 (forward-char (1- (length ses-print-data-boundary)))
1388 ;;Initialize printer and symbol lists
1389 (mapc 'ses-printer-record ses-standard-printer-functions)
1390 (setq ses--symbolic-formulas nil)
1391 ;;Load cell definitions
1392 (dotimes (row ses--numrows)
1393 (dotimes (col ses--numcols)
1394 (let* ((x (read (current-buffer)))
1395 (rowcol (ses-sym-rowcol (car-safe (cdr-safe x)))))
1396 (or (and (looking-at "\n")
1397 (eq (car-safe x) 'ses-cell)
1398 (eq row (car rowcol))
1399 (eq col (cdr rowcol)))
1400 (error "Cell-def error"))
1401 (eval x)))
1402 (or (looking-at "\n\n")
1403 (error "Missing blank line between rows")))
1404 ;;Load global parameters
1405 (let ((widths (read (current-buffer)))
1406 (n1 (char-after (point)))
1407 (printers (read (current-buffer)))
1408 (n2 (char-after (point)))
1409 (def-printer (read (current-buffer)))
1410 (n3 (char-after (point)))
1411 (head-row (read (current-buffer)))
1412 (n4 (char-after (point))))
1413 (or (and (eq (car-safe widths) 'ses-column-widths)
1414 (= n1 ?\n)
1415 (eq (car-safe printers) 'ses-column-printers)
1416 (= n2 ?\n)
1417 (eq (car-safe def-printer) 'ses-default-printer)
1418 (= n3 ?\n)
1419 (eq (car-safe head-row) 'ses-header-row)
1420 (= n4 ?\n))
1421 (error "Invalid SES global parameters"))
1422 (1value (eval widths))
1423 (1value (eval def-printer))
1424 (1value (eval printers))
1425 (1value (eval head-row)))
1426 ;;Should be back at global-params
1427 (forward-char 1)
1428 (or (looking-at (replace-regexp-in-string "1" "[0-9]+"
1429 ses-initial-global-parameters))
1430 (error "Problem with column-defs or global-params"))
1431 ;;Check for overall newline count in definitions area
1432 (forward-line 3)
1433 (let ((start (point)))
1434 (ses-goto-data 'ses--numrows)
1435 (or (= (point) start)
1436 (error "Extraneous newlines someplace?"))))
1438 (defun ses-setup ()
1439 "Set up for display of only the printed cell values.
1441 Narrows the buffer to show only the print area. Gives it `read-only' and
1442 `intangible' properties. Sets up highlighting for current cell."
1443 (interactive)
1444 (let ((end (point-min))
1445 (inhibit-read-only t)
1446 (was-modified (buffer-modified-p))
1447 pos sym)
1448 (ses-goto-data 0 0) ;;Include marker between print-area and data-area
1449 (set-text-properties (point) (point-max) nil) ;Delete garbage props
1450 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1451 ;;The print area is read-only (except for our special commands) and uses a
1452 ;;special keymap.
1453 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1454 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1455 ;;For the beginning of the buffer, we want the read-only and keymap
1456 ;;attributes to be inherited from the first character
1457 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1458 ;;Create intangible properties, which also indicate which cell the text
1459 ;;came from.
1460 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1461 (dotimes (col ses--numcols)
1462 (setq pos end
1463 sym (ses-cell-symbol row col))
1464 ;;Include skipped cells following this one
1465 (while (and (< col (1- ses--numcols))
1466 (eq (ses-cell-value row (1+ col)) '*skip*))
1467 (setq end (+ end (ses-col-width col) 1)
1468 col (1+ col)))
1469 (setq end (+ end (ses-col-width col) 1))
1470 (put-text-property pos end 'intangible sym)))
1471 ;;Adding these properties did not actually alter the text
1472 (unless was-modified
1473 (restore-buffer-modified-p nil)
1474 (buffer-disable-undo)
1475 (buffer-enable-undo)))
1476 ;;Create the underlining overlay. It's impossible for (point) to be 2,
1477 ;;because column A must be at least 1 column wide.
1478 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1479 (overlay-put ses--curcell-overlay 'face 'underline))
1481 (defun ses-cleanup ()
1482 "Cleanup when changing a buffer from SES mode to something else.
1483 Delete overlays, remove special text properties."
1484 (widen)
1485 (let ((inhibit-read-only t)
1486 ;; When reverting, hide the buffer name, otherwise Emacs will ask
1487 ;; the user "the file is modified, do you really want to make
1488 ;; modifications to this buffer", where the "modifications" refer to
1489 ;; the irrelevant set-text-properties below.
1490 (buffer-file-name nil)
1491 (was-modified (buffer-modified-p)))
1492 ;;Delete read-only, keymap, and intangible properties
1493 (set-text-properties (point-min) (point-max) nil)
1494 ;;Delete overlay
1495 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1496 (unless was-modified
1497 (restore-buffer-modified-p nil))))
1499 ;;;###autoload
1500 (defun ses-mode ()
1501 "Major mode for Simple Emacs Spreadsheet.
1502 See \"ses-example.ses\" (in `data-directory') for more info.
1504 Key definitions:
1505 \\{ses-mode-map}
1506 These key definitions are active only in the print area (the visible part):
1507 \\{ses-mode-print-map}
1508 These are active only in the minibuffer, when entering or editing a formula:
1509 \\{ses-mode-edit-map}"
1510 (interactive)
1511 (unless (and (boundp 'ses--deferred-narrow)
1512 (eq ses--deferred-narrow 'ses-mode))
1513 (kill-all-local-variables)
1514 (mapc 'make-local-variable ses-localvars)
1515 (setq major-mode 'ses-mode
1516 mode-name "SES"
1517 next-line-add-newlines nil
1518 truncate-lines t
1519 ;;SES deliberately puts lots of trailing whitespace in its buffer
1520 show-trailing-whitespace nil
1521 ;;Cell ranges do not work reasonably without this
1522 transient-mark-mode t)
1523 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1524 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1525 (setq ses--curcell nil
1526 ses--deferred-recalc nil
1527 ses--deferred-write nil
1528 ses--header-hscroll -1 ;Flag for "initial recalc needed"
1529 header-line-format '(:eval (progn
1530 (when (/= (window-hscroll)
1531 ses--header-hscroll)
1532 ;;Reset ses--header-hscroll first, to
1533 ;;avoid recursion problems when
1534 ;;debugging ses-create-header-string
1535 (setq ses--header-hscroll
1536 (window-hscroll))
1537 (ses-create-header-string))
1538 ses--header-string)))
1539 (let ((was-empty (zerop (buffer-size)))
1540 (was-modified (buffer-modified-p)))
1541 (save-excursion
1542 (if was-empty
1543 ;;Initialize buffer to contain one cell, for now
1544 (insert ses-initial-file-contents))
1545 (ses-load)
1546 (ses-setup))
1547 (when was-empty
1548 (unless (equal ses-initial-default-printer (1value ses--default-printer))
1549 (1value (ses-read-default-printer ses-initial-default-printer)))
1550 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1551 (1value (ses-set-column-width 0 ses-initial-column-width)))
1552 (ses-set-curcell)
1553 (if (> (car ses-initial-size) (1value ses--numrows))
1554 (1value (ses-insert-row (1- (car ses-initial-size)))))
1555 (if (> (cdr ses-initial-size) (1value ses--numcols))
1556 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1557 (ses-write-cells)
1558 (restore-buffer-modified-p was-modified)
1559 (buffer-disable-undo)
1560 (buffer-enable-undo)
1561 (goto-char (point-min))))
1562 (use-local-map ses-mode-map)
1563 ;;Set the deferred narrowing flag (we can't narrow until after
1564 ;;after-find-file completes). If .ses is on the auto-load alist and the
1565 ;;file has "mode: ses", our ses-mode function will be called twice! Use
1566 ;;a special flag to detect this (will be reset by ses-command-hook).
1567 ;;For find-alternate-file, post-command-hook doesn't get run for some
1568 ;;reason, so use an idle timer to make sure.
1569 (setq ses--deferred-narrow 'ses-mode)
1570 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1571 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1572 (run-mode-hooks 'ses-mode-hook)))
1574 (put 'ses-mode 'mode-class 'special)
1576 (defun ses-command-hook ()
1577 "Invoked from `post-command-hook'. If point has moved to a different cell,
1578 moves the underlining overlay. Performs any recalculations or cell-data
1579 writes that have been deferred. If buffer-narrowing has been deferred,
1580 narrows the buffer now."
1581 (condition-case err
1582 (when (eq major-mode 'ses-mode) ;Otherwise, not our buffer anymore
1583 (when ses--deferred-recalc
1584 ;;We reset the deferred list before starting on the recalc -- in case
1585 ;;of error, we don't want to retry the recalc after every keystroke!
1586 (let ((old ses--deferred-recalc))
1587 (setq ses--deferred-recalc nil)
1588 (ses-update-cells old)))
1589 (when ses--deferred-write
1590 ;;We don't reset the deferred list before starting -- the most
1591 ;;likely error is keyboard-quit, and we do want to keep trying
1592 ;;these writes after a quit.
1593 (ses-write-cells)
1594 (push '(apply ses-widen) buffer-undo-list))
1595 (when ses--deferred-narrow
1596 ;;We're not allowed to narrow the buffer until after-find-file has
1597 ;;read the local variables at the end of the file. Now it's safe to
1598 ;;do the narrowing.
1599 (narrow-to-region (point-min) ses--data-marker)
1600 (setq ses--deferred-narrow nil))
1601 ;;Update the modeline
1602 (let ((oldcell ses--curcell))
1603 (ses-set-curcell)
1604 (unless (eq ses--curcell oldcell)
1605 (cond
1606 ((not ses--curcell)
1607 (setq mode-line-process nil))
1608 ((atom ses--curcell)
1609 (setq mode-line-process (list " cell "
1610 (symbol-name ses--curcell))))
1612 (setq mode-line-process (list " range "
1613 (symbol-name (car ses--curcell))
1615 (symbol-name (cdr ses--curcell))))))
1616 (force-mode-line-update)))
1617 ;;Use underline overlay for single-cells only, turn off otherwise
1618 (if (listp ses--curcell)
1619 (move-overlay ses--curcell-overlay 2 2)
1620 (let ((next (next-single-property-change (point) 'intangible)))
1621 (move-overlay ses--curcell-overlay (point) (1- next))))
1622 (when (not (pos-visible-in-window-p))
1623 ;;Scrolling will happen later
1624 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1625 (setq ses--curcell t)))
1626 ;;Prevent errors in this post-command-hook from silently erasing the hook!
1627 (error
1628 (unless executing-kbd-macro
1629 (ding))
1630 (message "%s" (error-message-string err))))
1631 nil) ;Make coverage-tester happy
1633 (defun ses-create-header-string ()
1634 "Set up `ses--header-string' as the buffer's header line.
1635 Based on the current set of columns and `window-hscroll' position."
1636 (let ((totwidth (- (window-hscroll)))
1637 result width x)
1638 ;;Leave room for the left-side fringe and scrollbar
1639 (push (propertize " " 'display '((space :align-to 0))) result)
1640 (dotimes (col ses--numcols)
1641 (setq width (ses-col-width col)
1642 totwidth (+ totwidth width 1))
1643 (if (= totwidth 1)
1644 ;;Scrolled so intercolumn space is leftmost
1645 (push " " result))
1646 (when (> totwidth 1)
1647 (if (> ses--header-row 0)
1648 (save-excursion
1649 (ses-goto-print (1- ses--header-row) col)
1650 (setq x (buffer-substring-no-properties (point)
1651 (+ (point) width)))
1652 ;; Strip trailing space.
1653 (if (string-match "[ \t]+\\'" x)
1654 (setq x (substring x 0 (match-beginning 0))))
1655 ;; Cut off excess text.
1656 (if (>= (length x) totwidth)
1657 (setq x (substring x 0 (- totwidth -1)))))
1658 (setq x (ses-column-letter col)))
1659 (push (propertize x 'face ses-box-prop) result)
1660 (push (propertize "."
1661 'display `((space :align-to ,(1- totwidth)))
1662 'face ses-box-prop)
1663 result)
1664 ;;Allow the following space to be squished to make room for the 3-D box
1665 ;;Coverage test ignores properties, thinks this is always a space!
1666 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
1667 result)))
1668 (if (> ses--header-row 0)
1669 (push (propertize (format " [row %d]" ses--header-row)
1670 'display '((height (- 1))))
1671 result))
1672 (setq ses--header-string (apply 'concat (nreverse result)))))
1675 ;;----------------------------------------------------------------------------
1676 ;; Redisplay and recalculation
1677 ;;----------------------------------------------------------------------------
1679 (defun ses-jump (sym)
1680 "Move point to cell SYM."
1681 (interactive "SJump to cell: ")
1682 (let ((rowcol (ses-sym-rowcol sym)))
1683 (or rowcol (error "Invalid cell name"))
1684 (if (eq (symbol-value sym) '*skip*)
1685 (error "Cell is covered by preceding cell"))
1686 (ses-goto-print (car rowcol) (cdr rowcol))))
1688 (defun ses-jump-safe (cell)
1689 "Like `ses-jump', but no error if invalid cell."
1690 (condition-case nil
1691 (ses-jump cell)
1692 (error)))
1694 (defun ses-reprint-all (&optional nonarrow)
1695 "Recreate the display area. Calls all printer functions. Narrows to
1696 print area if NONARROW is nil."
1697 (interactive "*P")
1698 (widen)
1699 (unless nonarrow
1700 (setq ses--deferred-narrow t))
1701 (let ((startcell (get-text-property (point) 'intangible))
1702 (inhibit-read-only t))
1703 (ses-begin-change)
1704 (goto-char (point-min))
1705 (search-forward ses-print-data-boundary)
1706 (backward-char (length ses-print-data-boundary))
1707 (delete-region (point-min) (point))
1708 ;;Insert all blank lines before printing anything, so ses-print-cell can
1709 ;;find the data area when inserting or deleting *skip* values for cells
1710 (dotimes (row ses--numrows)
1711 (insert-and-inherit ses--blank-line))
1712 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
1713 (if (eq (ses-cell-value row 0) '*skip*)
1714 ;;Column deletion left a dangling skip
1715 (ses-set-cell row 0 'value nil))
1716 (dotimes (col ses--numcols)
1717 (ses-print-cell row col))
1718 (beginning-of-line 2))
1719 (ses-jump-safe startcell)))
1721 (defun ses-recalculate-cell ()
1722 "Recalculate and reprint the current cell or range.
1724 For an individual cell, shows the error if the formula or printer
1725 signals one, or otherwise shows the cell's complete value. For a range, the
1726 cells are recalculated in \"natural\" order, so cells that other cells refer
1727 to are recalculated first."
1728 (interactive "*")
1729 (ses-check-curcell 'range)
1730 (ses-begin-change)
1731 (let (sig)
1732 (setq ses-start-time (float-time))
1733 (if (atom ses--curcell)
1734 (setq sig (ses-sym-rowcol ses--curcell)
1735 sig (ses-calculate-cell (car sig) (cdr sig) t))
1736 ;;First, recalculate all cells that don't refer to other cells and
1737 ;;produce a list of cells with references.
1738 (ses-dorange ses--curcell
1739 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
1740 (condition-case nil
1741 (progn
1742 ;;The t causes an error if the cell has references.
1743 ;;If no references, the t will be the result value.
1744 (1value (ses-formula-references (ses-cell-formula row col) t))
1745 (setq sig (ses-calculate-cell row col t)))
1746 (wrong-type-argument
1747 ;;The formula contains a reference
1748 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
1749 ;;Do the update now, so we can force recalculation
1750 (let ((x ses--deferred-recalc))
1751 (setq ses--deferred-recalc nil)
1752 (condition-case hold
1753 (ses-update-cells x t)
1754 (error (setq sig hold))))
1755 (cond
1756 (sig
1757 (message "%s" (error-message-string sig)))
1758 ((consp ses--curcell)
1759 (message " "))
1761 (princ (symbol-value ses--curcell))))))
1763 (defun ses-recalculate-all ()
1764 "Recalculate and reprint all cells."
1765 (interactive "*")
1766 (let ((startcell (get-text-property (point) 'intangible))
1767 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
1768 (1- ses--numcols)))))
1769 (ses-recalculate-cell)
1770 (ses-jump-safe startcell)))
1772 (defun ses-truncate-cell ()
1773 "Reprint current cell, but without spillover into any following blank
1774 cells."
1775 (interactive "*")
1776 (ses-check-curcell)
1777 (let* ((rowcol (ses-sym-rowcol ses--curcell))
1778 (row (car rowcol))
1779 (col (cdr rowcol)))
1780 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
1781 (eq (ses-cell-value row (1+ col)) '*skip*))
1782 ;;This cell has spill-over. We'll momentarily pretend the following
1783 ;;cell has a `t' in it.
1784 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
1785 (ses-print-cell row col)))
1786 ;;Now remove the *skip*. ses-print-cell is always nil here
1787 (ses-set-cell row (1+ col) 'value nil)
1788 (1value (ses-print-cell row (1+ col))))))
1790 (defun ses-reconstruct-all ()
1791 "Reconstruct buffer based on cell data stored in Emacs variables."
1792 (interactive "*")
1793 (ses-begin-change)
1794 ;;Reconstruct reference lists.
1795 (let (x yrow ycol)
1796 ;;Delete old reference lists
1797 (dotimes-with-progress-reporter
1798 (row ses--numrows) "Deleting references..."
1799 (dotimes (col ses--numcols)
1800 (ses-set-cell row col 'references nil)))
1801 ;;Create new reference lists
1802 (dotimes-with-progress-reporter
1803 (row ses--numrows) "Computing references..."
1804 (dotimes (col ses--numcols)
1805 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
1806 (setq x (ses-sym-rowcol ref)
1807 yrow (car x)
1808 ycol (cdr x))
1809 (ses-set-cell yrow ycol 'references
1810 (cons (ses-cell-symbol row col)
1811 (ses-cell-references yrow ycol)))))))
1812 ;;Delete everything and reconstruct basic data area
1813 (ses-widen)
1814 (let ((inhibit-read-only t))
1815 (goto-char (point-max))
1816 (if (search-backward ";; Local Variables:\n" nil t)
1817 (delete-region (point-min) (point))
1818 ;;Buffer is quite screwed up - can't even save the user-specified locals
1819 (delete-region (point-min) (point-max))
1820 (insert ses-initial-file-trailer)
1821 (goto-char (point-min)))
1822 ;;Create a blank display area
1823 (dotimes (row ses--numrows)
1824 (insert ses--blank-line))
1825 (insert ses-print-data-boundary)
1826 (backward-char (1- (length ses-print-data-boundary)))
1827 (setq ses--data-marker (point-marker))
1828 (forward-char (1- (length ses-print-data-boundary)))
1829 ;;Placeholders for cell data
1830 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
1831 ;;Placeholders for col-widths, col-printers, default-printer, header-row
1832 (insert "\n\n\n\n")
1833 (insert ses-initial-global-parameters)
1834 (backward-char (1- (length ses-initial-global-parameters)))
1835 (setq ses--params-marker (point-marker))
1836 (forward-char (1- (length ses-initial-global-parameters))))
1837 (ses-set-parameter 'ses--col-widths ses--col-widths)
1838 (ses-set-parameter 'ses--col-printers ses--col-printers)
1839 (ses-set-parameter 'ses--default-printer ses--default-printer)
1840 (ses-set-parameter 'ses--header-row ses--header-row)
1841 (ses-set-parameter 'ses--numrows ses--numrows)
1842 (ses-set-parameter 'ses--numcols ses--numcols)
1843 ;;Keep our old narrowing
1844 (ses-setup)
1845 (ses-recalculate-all)
1846 (goto-char (point-min)))
1849 ;;----------------------------------------------------------------------------
1850 ;; Input of cell formulas
1851 ;;----------------------------------------------------------------------------
1853 (defun ses-edit-cell (row col newval)
1854 "Display current cell contents in minibuffer, for editing. Returns nil if
1855 cell formula was unsafe and user declined confirmation."
1856 (interactive
1857 (progn
1858 (barf-if-buffer-read-only)
1859 (ses-check-curcell)
1860 (let* ((rowcol (ses-sym-rowcol ses--curcell))
1861 (row (car rowcol))
1862 (col (cdr rowcol))
1863 (formula (ses-cell-formula row col))
1864 initial)
1865 (if (eq (car-safe formula) 'ses-safe-formula)
1866 (setq formula (cadr formula)))
1867 (if (eq (car-safe formula) 'quote)
1868 (setq initial (format "'%S" (cadr formula)))
1869 (setq initial (prin1-to-string formula)))
1870 (if (stringp formula)
1871 ;;Position cursor inside close-quote
1872 (setq initial (cons initial (length initial))))
1873 (list row col
1874 (read-from-minibuffer (format "Cell %s: " ses--curcell)
1875 initial
1876 ses-mode-edit-map
1877 t ;Convert to Lisp object
1878 'ses-read-cell-history)))))
1879 (when (ses-warn-unsafe newval 'unsafep)
1880 (ses-begin-change)
1881 (ses-cell-set-formula row col newval)
1884 (defun ses-read-cell (row col newval)
1885 "Self-insert for initial character of cell function."
1886 (interactive
1887 (let* ((initial (this-command-keys))
1888 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
1889 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
1890 (barf-if-buffer-read-only)
1891 (list (car rowcol)
1892 (cdr rowcol)
1893 (read-from-minibuffer
1894 (format "Cell %s: " ses--curcell)
1895 (cons (if (equal initial "\"") "\"\""
1896 (if (equal initial "(") "()" initial)) 2)
1897 ses-mode-edit-map
1898 t ;Convert to Lisp object
1899 'ses-read-cell-history
1900 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
1901 (cadr curval)
1902 curval))))))
1903 (when (ses-edit-cell row col newval)
1904 (ses-command-hook) ;Update cell widths before movement
1905 (dolist (x ses-after-entry-functions)
1906 (funcall x 1))))
1908 (defun ses-read-symbol (row col symb)
1909 "Self-insert for a symbol as a cell formula. The set of all symbols that
1910 have been used as formulas in this spreadsheet is available for completions."
1911 (interactive
1912 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
1913 newval)
1914 (barf-if-buffer-read-only)
1915 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
1916 ses--symbolic-formulas))
1917 (list (car rowcol)
1918 (cdr rowcol)
1919 (if (string= newval "")
1920 nil ;Don't create zero-length symbols!
1921 (list 'quote (intern newval))))))
1922 (when (ses-edit-cell row col symb)
1923 (ses-command-hook) ;Update cell widths before movement
1924 (dolist (x ses-after-entry-functions)
1925 (funcall x 1))))
1927 (defun ses-clear-cell-forward (count)
1928 "Delete formula and printer for current cell and then move to next cell.
1929 With prefix, deletes several cells."
1930 (interactive "*p")
1931 (if (< count 0)
1932 (1value (ses-clear-cell-backward (- count)))
1933 (ses-check-curcell)
1934 (ses-begin-change)
1935 (dotimes (x count)
1936 (ses-set-curcell)
1937 (let ((rowcol (ses-sym-rowcol ses--curcell)))
1938 (or rowcol (signal 'end-of-buffer nil))
1939 (ses-clear-cell (car rowcol) (cdr rowcol)))
1940 (forward-char 1))))
1942 (defun ses-clear-cell-backward (count)
1943 "Move to previous cell and then delete it. With prefix, deletes several
1944 cells."
1945 (interactive "*p")
1946 (if (< count 0)
1947 (1value (ses-clear-cell-forward (- count)))
1948 (ses-check-curcell 'end)
1949 (ses-begin-change)
1950 (dotimes (x count)
1951 (backward-char 1) ;Will signal 'beginning-of-buffer if appropriate
1952 (ses-set-curcell)
1953 (let ((rowcol (ses-sym-rowcol ses--curcell)))
1954 (ses-clear-cell (car rowcol) (cdr rowcol))))))
1957 ;;----------------------------------------------------------------------------
1958 ;; Input of cell-printer functions
1959 ;;----------------------------------------------------------------------------
1961 (defun ses-read-printer (prompt default)
1962 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
1963 PROMPT should end with \": \". Result is t if operation was cancelled."
1964 (barf-if-buffer-read-only)
1965 (if (eq default t)
1966 (setq default "")
1967 (setq prompt (format "%s [currently %S]: "
1968 (substring prompt 0 -2)
1969 default)))
1970 (let ((new (read-from-minibuffer prompt
1971 nil ;Initial contents
1972 ses-mode-edit-map
1973 t ;Evaluate the result
1974 'ses-read-printer-history
1975 (prin1-to-string default))))
1976 (if (equal new default)
1977 ;;User changed mind, decided not to change printer
1978 (setq new t)
1979 (ses-printer-validate new)
1980 (or (not new)
1981 (stringp new)
1982 (stringp (car-safe new))
1983 (ses-warn-unsafe new 'unsafep-function)
1984 (setq new t)))
1985 new))
1987 (defun ses-read-cell-printer (newval)
1988 "Set the printer function for the current cell or range.
1990 A printer function is either a string (a format control-string with one
1991 %-sequence -- result from format will be right-justified), or a list of one
1992 string (result from format will be left-justified), or a lambda-expression of
1993 one argument, or a symbol that names a function of one argument. In the
1994 latter two cases, the function's result should be either a string (will be
1995 right-justified) or a list of one string (will be left-justified)."
1996 (interactive
1997 (let ((default t)
1999 (ses-check-curcell 'range)
2000 ;;Default is none if not all cells in range have same printer
2001 (catch 'ses-read-cell-printer
2002 (ses-dorange ses--curcell
2003 (setq x (ses-cell-printer row col))
2004 (if (eq (car-safe x) 'ses-safe-printer)
2005 (setq x (cadr x)))
2006 (if (eq default t)
2007 (setq default x)
2008 (unless (equal default x)
2009 ;;Range contains differing printer functions
2010 (setq default t)
2011 (throw 'ses-read-cell-printer t)))))
2012 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2013 default))))
2014 (unless (eq newval t)
2015 (ses-begin-change)
2016 (ses-dorange ses--curcell
2017 (ses-set-cell row col 'printer newval)
2018 (ses-print-cell row col))))
2020 (defun ses-read-column-printer (col newval)
2021 "Set the printer function for the current column. See
2022 `ses-read-cell-printer' for input forms."
2023 (interactive
2024 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2025 (ses-check-curcell)
2026 (list col (ses-read-printer (format "Column %s printer: "
2027 (ses-column-letter col))
2028 (ses-col-printer col)))))
2030 (unless (eq newval t)
2031 (ses-begin-change)
2032 (ses-set-parameter 'ses--col-printers newval col)
2033 (save-excursion
2034 (dotimes (row ses--numrows)
2035 (ses-print-cell row col)))))
2037 (defun ses-read-default-printer (newval)
2038 "Set the default printer function for cells that have no other. See
2039 `ses-read-cell-printer' for input forms."
2040 (interactive
2041 (list (ses-read-printer "Default printer: " ses--default-printer)))
2042 (unless (eq newval t)
2043 (ses-begin-change)
2044 (ses-set-parameter 'ses--default-printer newval)
2045 (ses-reprint-all t)))
2048 ;;----------------------------------------------------------------------------
2049 ;; Spreadsheet size adjustments
2050 ;;----------------------------------------------------------------------------
2052 (defun ses-insert-row (count)
2053 "Insert a new row before the current one. With prefix, insert COUNT rows
2054 before current one."
2055 (interactive "*p")
2056 (ses-check-curcell 'end)
2057 (or (> count 0) (signal 'args-out-of-range nil))
2058 (ses-begin-change)
2059 (let ((inhibit-quit t)
2060 (inhibit-read-only t)
2061 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2062 newrow)
2063 ;;Create a new set of cell-variables
2064 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2065 0 (1- ses--numcols))
2066 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2067 ;;Insert each row
2068 (ses-goto-print row 0)
2069 (dotimes-with-progress-reporter (x count) "Inserting row..."
2070 ;;Create a row of empty cells. The `symbol' fields will be set by
2071 ;;the call to ses-relocate-all.
2072 (setq newrow (make-vector ses--numcols nil))
2073 (dotimes (col ses--numcols)
2074 (aset newrow col (ses-make-cell)))
2075 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2076 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2077 (insert ses--blank-line))
2078 ;;Insert empty lines in cell data area (will be replaced by
2079 ;;ses-relocate-all)
2080 (ses-goto-data row 0)
2081 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2082 (ses-relocate-all row 0 count 0)
2083 ;;If any cell printers insert constant text, insert that text
2084 ;;into the line.
2085 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2086 (global (ses-call-printer ses--default-printer)))
2087 (if (or (> (length cols) 0) (> (length global) 0))
2088 (dotimes (x count)
2089 (dotimes (col ses--numcols)
2090 ;;These cells are always nil, only constant formatting printed
2091 (1value (ses-print-cell (+ x row) col))))))
2092 (when (> ses--header-row row)
2093 ;;Inserting before header
2094 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2095 (ses-reset-header-string)))
2096 ;;Reconstruct text attributes
2097 (ses-setup)
2098 ;;Prepare for undo
2099 (push '(apply ses-widen) buffer-undo-list)
2100 ;;Return to current cell
2101 (if ses--curcell
2102 (ses-jump-safe ses--curcell)
2103 (ses-goto-print (1- ses--numrows) 0)))
2105 (defun ses-delete-row (count)
2106 "Delete the current row. With prefix, Deletes COUNT rows starting from the
2107 current one."
2108 (interactive "*p")
2109 (ses-check-curcell)
2110 (or (> count 0) (signal 'args-out-of-range nil))
2111 (let ((inhibit-quit t)
2112 (inhibit-read-only t)
2113 (row (car (ses-sym-rowcol ses--curcell))))
2114 (setq count (min count (- ses--numrows row)))
2115 (ses-begin-change)
2116 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2117 ;;Delete lines from print area
2118 (ses-goto-print row 0)
2119 (ses-delete-line count)
2120 ;;Delete lines from cell data area
2121 (ses-goto-data row 0)
2122 (ses-delete-line (* count (1+ ses--numcols)))
2123 ;;Relocate variables and formulas
2124 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2125 (ses-relocate-all row 0 (- count) 0)
2126 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2127 0 (1- ses--numcols))
2128 (when (> ses--header-row row)
2129 (if (<= ses--header-row (+ row count))
2130 ;;Deleting the header row
2131 (ses-set-parameter 'ses--header-row 0)
2132 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2133 (ses-reset-header-string)))
2134 ;;Reconstruct attributes
2135 (ses-setup)
2136 ;;Prepare for undo
2137 (push '(apply ses-widen) buffer-undo-list)
2138 (ses-jump-safe ses--curcell))
2140 (defun ses-insert-column (count &optional col width printer)
2141 "Insert a new column before COL (default is the current one).
2142 With prefix, insert COUNT columns before current one.
2143 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2144 \(otherwise they're taken from the current column)."
2145 (interactive "*p")
2146 (ses-check-curcell)
2147 (or (> count 0) (signal 'args-out-of-range nil))
2148 (or col
2149 (setq col (cdr (ses-sym-rowcol ses--curcell))
2150 width (ses-col-width col)
2151 printer (ses-col-printer col)))
2152 (ses-begin-change)
2153 (let ((inhibit-quit t)
2154 (inhibit-read-only t)
2155 (widths ses--col-widths)
2156 (printers ses--col-printers)
2157 has-skip)
2158 ;;Create a new set of cell-variables
2159 (ses-create-cell-variable-range 0 (1- ses--numrows)
2160 ses--numcols (+ ses--numcols count -1))
2161 ;;Insert each column.
2162 (dotimes-with-progress-reporter (x count) "Inserting column..."
2163 ;;Create a column of empty cells. The `symbol' fields will be set by
2164 ;;the call to ses-relocate-all.
2165 (ses-adjust-print-width col (1+ width))
2166 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2167 (dotimes (row ses--numrows)
2168 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2169 ;;Inserting in the middle of a spill-over
2170 (setq has-skip t))
2171 (ses-aset-with-undo ses--cells row
2172 (ses-vector-insert (aref ses--cells row)
2173 col (ses-make-cell)))
2174 ;;Insert empty lines in cell data area (will be replaced by
2175 ;;ses-relocate-all)
2176 (ses-goto-data row col)
2177 (insert ?\n))
2178 ;;Insert column width and printer
2179 (setq widths (ses-vector-insert widths col width)
2180 printers (ses-vector-insert printers col printer)))
2181 (ses-set-parameter 'ses--col-widths widths)
2182 (ses-set-parameter 'ses--col-printers printers)
2183 (ses-reset-header-string)
2184 (ses-relocate-all 0 col 0 count)
2185 (if has-skip
2186 (ses-reprint-all t)
2187 (when (or (> (length (ses-call-printer printer)) 0)
2188 (> (length (ses-call-printer ses--default-printer)) 0))
2189 ;;Either column printer or global printer inserts some constant text
2190 ;;Reprint the new columns to insert that text.
2191 (dotimes (x ses--numrows)
2192 (dotimes (y count)
2193 ;Always nil here - this is a blank column
2194 (1value (ses-print-cell-new-width x (+ y col))))))
2195 (ses-setup)))
2196 (ses-jump-safe ses--curcell))
2198 (defun ses-delete-column (count)
2199 "Delete the current column. With prefix, Deletes COUNT columns starting
2200 from the current one."
2201 (interactive "*p")
2202 (ses-check-curcell)
2203 (or (> count 0) (signal 'args-out-of-range nil))
2204 (let ((inhibit-quit t)
2205 (inhibit-read-only t)
2206 (rowcol (ses-sym-rowcol ses--curcell))
2207 (width 0)
2208 col origrow has-skip)
2209 (setq origrow (car rowcol)
2210 col (cdr rowcol)
2211 count (min count (- ses--numcols col)))
2212 (if (= count ses--numcols)
2213 (error "Can't delete all columns!"))
2214 ;;Determine width of column(s) being deleted
2215 (dotimes (x count)
2216 (setq width (+ width (ses-col-width (+ col x)) 1)))
2217 (ses-begin-change)
2218 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2219 (ses-adjust-print-width col (- width))
2220 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2221 ;;Delete lines from cell data area
2222 (ses-goto-data row col)
2223 (ses-delete-line count)
2224 ;;Delete cells. Check if deletion area begins or ends with a skip.
2225 (if (or (eq (ses-cell-value row col) '*skip*)
2226 (and (< col ses--numcols)
2227 (eq (ses-cell-value row (+ col count)) '*skip*)))
2228 (setq has-skip t))
2229 (ses-aset-with-undo ses--cells row
2230 (ses-vector-delete (aref ses--cells row) col count)))
2231 ;;Update globals
2232 (ses-set-parameter 'ses--col-widths
2233 (ses-vector-delete ses--col-widths col count))
2234 (ses-set-parameter 'ses--col-printers
2235 (ses-vector-delete ses--col-printers col count))
2236 (ses-reset-header-string)
2237 ;;Relocate variables and formulas
2238 (ses-relocate-all 0 col 0 (- count))
2239 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2240 ses--numcols (+ ses--numcols count -1))
2241 (if has-skip
2242 (ses-reprint-all t)
2243 (ses-setup))
2244 (if (>= col ses--numcols)
2245 (setq col (1- col)))
2246 (ses-goto-print origrow col)))
2248 (defun ses-forward-or-insert (&optional count)
2249 "Move to next cell in row, or inserts a new cell if already in last one, or
2250 inserts a new row if at bottom of print area. Repeat COUNT times."
2251 (interactive "p")
2252 (ses-check-curcell 'end)
2253 (setq deactivate-mark t) ;Doesn't combine well with ranges
2254 (dotimes (x count)
2255 (ses-set-curcell)
2256 (if (not ses--curcell)
2257 (progn ;At bottom of print area
2258 (barf-if-buffer-read-only)
2259 (ses-insert-row 1))
2260 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2261 (when (/= 32
2262 (char-before (next-single-property-change (point)
2263 'intangible)))
2264 ;;We're already in last nonskipped cell on line. Need to create a
2265 ;;new column.
2266 (barf-if-buffer-read-only)
2267 (ses-insert-column (- count x)
2268 ses--numcols
2269 (ses-col-width col)
2270 (ses-col-printer col)))))
2271 (forward-char)))
2273 (defun ses-append-row-jump-first-column ()
2274 "Insert a new row after current one and jumps to its first column."
2275 (interactive "*")
2276 (ses-check-curcell)
2277 (ses-begin-change)
2278 (beginning-of-line 2)
2279 (ses-set-curcell)
2280 (ses-insert-row 1))
2282 (defun ses-set-column-width (col newwidth)
2283 "Set the width of the current column."
2284 (interactive
2285 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2286 (barf-if-buffer-read-only)
2287 (list col
2288 (if current-prefix-arg
2289 (prefix-numeric-value current-prefix-arg)
2290 (read-from-minibuffer (format "Column %s width [currently %d]: "
2291 (ses-column-letter col)
2292 (ses-col-width col))
2293 nil ;No initial contents
2294 nil ;No override keymap
2295 t ;Convert to Lisp object
2296 nil ;No history
2297 (number-to-string
2298 (ses-col-width col))))))) ;Default value
2299 (if (< newwidth 1)
2300 (error "Invalid column width"))
2301 (ses-begin-change)
2302 (ses-reset-header-string)
2303 (save-excursion
2304 (let ((inhibit-quit t))
2305 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2306 (ses-set-parameter 'ses--col-widths newwidth col))
2307 (dotimes (row ses--numrows)
2308 (ses-print-cell-new-width row col))))
2311 ;;----------------------------------------------------------------------------
2312 ;; Cut and paste, import and export
2313 ;;----------------------------------------------------------------------------
2315 (defadvice copy-region-as-kill (around ses-copy-region-as-kill
2316 activate preactivate)
2317 "It doesn't make sense to copy read-only or intangible attributes into the
2318 kill ring. It probably doesn't make sense to copy keymap properties.
2319 We'll assume copying front-sticky properties doesn't make sense, either.
2321 This advice also includes some SES-specific code because otherwise it's too
2322 hard to override how mouse-1 works."
2323 (when (> beg end)
2324 (let ((temp beg))
2325 (setq beg end
2326 end temp)))
2327 (if (not (and (eq major-mode 'ses-mode)
2328 (eq (get-text-property beg 'read-only) 'ses)
2329 (eq (get-text-property (1- end) 'read-only) 'ses)))
2330 ad-do-it ;Normal copy-region-as-kill
2331 (kill-new (ses-copy-region beg end))
2332 (if transient-mark-mode
2333 (setq deactivate-mark t))
2334 nil))
2336 (defun ses-copy-region (beg end)
2337 "Treat the region as rectangular. Convert the intangible attributes to
2338 SES attributes recording the contents of the cell as of the time of copying."
2339 (when (= end ses--data-marker)
2340 ;;Avoid overflow situation
2341 (setq end (1- ses--data-marker)))
2342 (let* ((inhibit-point-motion-hooks t)
2343 (x (mapconcat 'ses-copy-region-helper
2344 (extract-rectangle beg (1- end)) "\n")))
2345 (remove-text-properties 0 (length x)
2346 '(read-only t
2347 intangible t
2348 keymap t
2349 front-sticky t)
2353 (defun ses-copy-region-helper (line)
2354 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2355 external form by attaching to each print cell a 'ses attribute that records
2356 the corresponding data cell."
2357 (or (> (length line) 1)
2358 (error "Empty range"))
2359 (let ((inhibit-read-only t)
2360 (pos 0)
2361 mycell next sym rowcol)
2362 (while pos
2363 (setq sym (get-text-property pos 'intangible line)
2364 next (next-single-property-change pos 'intangible line)
2365 rowcol (ses-sym-rowcol sym)
2366 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2367 (put-text-property pos (or next (length line))
2368 'ses
2369 (list (ses-cell-symbol mycell)
2370 (ses-cell-formula mycell)
2371 (ses-cell-printer mycell))
2372 line)
2373 (setq pos next)))
2374 line)
2376 (defun ses-kill-override (beg end)
2377 "Generic override for any commands that kill text. We clear the killed
2378 cells instead of deleting them."
2379 (interactive "r")
2380 (ses-check-curcell 'needrange)
2381 ;;For some reason, the text-read-only error is not caught by
2382 ;;`delete-region', so we have to use subterfuge.
2383 (let ((buffer-read-only t))
2384 (1value (condition-case x
2385 (noreturn (funcall (lookup-key (current-global-map)
2386 (this-command-keys))
2387 beg end))
2388 (buffer-read-only nil)))) ;The expected error
2389 ;;Because the buffer was marked read-only, the kill command turned itself
2390 ;;into a copy. Now we clear the cells or signal the error. First we
2391 ;;check whether the buffer really is read-only.
2392 (barf-if-buffer-read-only)
2393 (ses-begin-change)
2394 (ses-dorange ses--curcell
2395 (ses-clear-cell row col))
2396 (ses-jump (car ses--curcell)))
2398 (defadvice yank (around ses-yank activate preactivate)
2399 "In SES mode, the yanked text is inserted as cells.
2401 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2402 SES buffer), the formulas and print functions are restored for the cells. If
2403 the text contains tabs, this is an insertion of tab-separated formulas.
2404 Otherwise the text is inserted as the formula for the current cell.
2406 When inserting cells, the formulas are usually relocated to keep the same
2407 relative references to neighboring cells. This is best if the formulas
2408 generally refer to other cells within the yanked text. You can use the C-u
2409 prefix to specify insertion without relocation, which is best when the
2410 formulas refer to cells outsite the yanked text.
2412 When inserting formulas, the text is treated as a string constant if it doesn't
2413 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2414 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2415 as symbols."
2416 (if (not (and (eq major-mode 'ses-mode)
2417 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2418 ad-do-it ;Normal non-SES yank
2419 (ses-check-curcell 'end)
2420 (push-mark (point))
2421 (let ((text (current-kill (cond
2422 ((listp arg) 0)
2423 ((eq arg '-) -1)
2424 (t (1- arg))))))
2425 (or (ses-yank-cells text arg)
2426 (ses-yank-tsf text arg)
2427 (ses-yank-one (ses-yank-resize 1 1)
2428 text
2430 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2431 ;;Just one cell - delete final tab or newline
2432 (1- (length text)))
2433 arg)))
2434 (if (consp arg)
2435 (exchange-point-and-mark))))
2437 (defun ses-yank-pop (arg)
2438 "Replace just-yanked stretch of killed text with a different stretch.
2439 This command is allowed only immediately after a `yank' or a `yank-pop', when
2440 the region contains a stretch of reinserted previously-killed text. We
2441 replace it with a different stretch of killed text.
2442 Unlike standard `yank-pop', this function uses `undo' to delete the
2443 previous insertion."
2444 (interactive "*p")
2445 (or (eq last-command 'yank)
2446 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2447 ;;macro definition.
2448 (noreturn (error "Previous command was not a yank")))
2449 (undo)
2450 (ses-set-curcell)
2451 (yank (1+ (or arg 1)))
2452 (setq this-command 'yank))
2454 (defun ses-yank-cells (text arg)
2455 "If the TEXT has a proper set of 'ses attributes, inserts the text as
2456 cells, else return nil. The cells are reprinted--the supplied text is
2457 ignored because the column widths, default printer, etc. at yank time might
2458 be different from those at kill-time. ARG is a list to indicate that
2459 formulas are to be inserted without relocation."
2460 (let ((first (get-text-property 0 'ses text))
2461 (last (get-text-property (1- (length text)) 'ses text)))
2462 (when (and first last) ;;Otherwise not proper set of attributes
2463 (setq first (ses-sym-rowcol (car first))
2464 last (ses-sym-rowcol (car last)))
2465 (let* ((needrows (- (car last) (car first) -1))
2466 (needcols (- (cdr last) (cdr first) -1))
2467 (rowcol (ses-yank-resize needrows needcols))
2468 (rowincr (- (car rowcol) (car first)))
2469 (colincr (- (cdr rowcol) (cdr first)))
2470 (pos 0)
2471 myrow mycol x)
2472 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2473 (setq myrow (+ row (car rowcol)))
2474 (dotimes (col needcols)
2475 (setq mycol (+ col (cdr rowcol))
2476 last (get-text-property pos 'ses text)
2477 pos (next-single-property-change pos 'ses text)
2478 x (ses-sym-rowcol (car last)))
2479 (if (not last)
2480 ;;Newline - all remaining cells on row are skipped
2481 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2482 last (list nil nil nil)
2483 pos (1- pos)))
2484 (if (/= (car x) (- myrow rowincr))
2485 (error "Cell row error"))
2486 (if (< (- mycol colincr) (cdr x))
2487 ;;Some columns were skipped
2488 (let ((oldcol mycol))
2489 (while (< (- mycol colincr) (cdr x))
2490 (ses-clear-cell myrow mycol)
2491 (setq col (1+ col)
2492 mycol (1+ mycol)))
2493 (ses-print-cell myrow (1- oldcol)))) ;;This inserts *skip*
2494 (when (car last) ;Skip this for *skip* cells
2495 (setq x (nth 2 last))
2496 (unless (equal x (ses-cell-printer myrow mycol))
2497 (or (not x)
2498 (stringp x)
2499 (eq (car-safe x) 'ses-safe-printer)
2500 (setq x `(ses-safe-printer ,x)))
2501 (ses-set-cell myrow mycol 'printer x))
2502 (setq x (cadr last))
2503 (if (atom arg)
2504 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2505 (or (atom x)
2506 (eq (car-safe x) 'ses-safe-formula)
2507 (setq x `(ses-safe-formula ,x)))
2508 (ses-cell-set-formula myrow mycol x)))
2509 (when pos
2510 (if (get-text-property pos 'ses text)
2511 (error "Missing newline between rows"))
2512 (setq pos (next-single-property-change pos 'ses text))))
2513 t))))
2515 (defun ses-yank-one (rowcol text from to arg)
2516 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2517 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2518 (let ((val (condition-case nil
2519 (read-from-string text from to)
2520 (error (cons nil from)))))
2521 (cond
2522 ((< (cdr val) (or to (length text)))
2523 ;;Invalid sexp - leave it as a string
2524 (setq val (substring text from to)))
2525 ((and (car val) (symbolp (car val)))
2526 (if (consp arg)
2527 (setq val (list 'quote (car val))) ;Keep symbol
2528 (setq val (substring text from to)))) ;Treat symbol as text
2530 (setq val (car val))))
2531 (let ((row (car rowcol))
2532 (col (cdr rowcol)))
2533 (or (atom val)
2534 (setq val `(ses-safe-formula ,val)))
2535 (ses-cell-set-formula row col val))))
2537 (defun ses-yank-tsf (text arg)
2538 "If TEXT contains tabs and/or newlines, treats the tabs as
2539 column-separators and the newlines as row-separators and inserts the text as
2540 cell formulas--else return nil. Treat plain symbols as strings unless ARG
2541 is a list. Ignore a final newline."
2542 (if (or (not (string-match "[\t\n]" text))
2543 (= (match-end 0) (length text)))
2544 ;;Not TSF format
2546 (if (/= (aref text (1- (length text))) ?\n)
2547 (setq text (concat text "\n")))
2548 (let ((pos -1)
2549 (spots (list -1))
2550 (cols 0)
2551 (needrows 0)
2552 needcols rowcol)
2553 ;;Find all the tabs and newlines
2554 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
2555 (push pos spots)
2556 (setq cols (1+ cols))
2557 (when (eq (aref text pos) ?\n)
2558 (if (not needcols)
2559 (setq needcols cols)
2560 (or (= needcols cols)
2561 (error "Inconsistent row lengths")))
2562 (setq cols 0
2563 needrows (1+ needrows))))
2564 ;;Insert the formulas
2565 (setq rowcol (ses-yank-resize needrows needcols))
2566 (dotimes (row needrows)
2567 (dotimes (col needcols)
2568 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
2569 (+ (cdr rowcol) needcols (- col) -1))
2570 text (1+ (cadr spots)) (car spots) arg)
2571 (setq spots (cdr spots))))
2572 (ses-goto-print (+ (car rowcol) needrows -1)
2573 (+ (cdr rowcol) needcols -1))
2574 t)))
2576 (defun ses-yank-resize (needrows needcols)
2577 "If this yank will require inserting rows and/or columns, asks for
2578 confirmation and then inserts them. Result is (row,col) for top left of yank
2579 spot, or error signal if user requests cancel."
2580 (ses-begin-change)
2581 (let ((rowcol (if ses--curcell
2582 (ses-sym-rowcol ses--curcell)
2583 (cons ses--numrows 0)))
2584 rowbool colbool)
2585 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
2586 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
2587 rowbool (> needrows 0)
2588 colbool (> needcols 0))
2589 (when (or rowbool colbool)
2590 ;;Need to insert. Get confirm
2591 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
2592 (if rowbool (format "%d rows" needrows) "")
2593 (if (and rowbool colbool) " and " "")
2594 (if colbool (format "%d columns" needcols) "")))
2595 (error "Cancelled"))
2596 (when rowbool
2597 (let (ses--curcell)
2598 (save-excursion
2599 (ses-goto-print ses--numrows 0)
2600 (ses-insert-row needrows))))
2601 (when colbool
2602 (ses-insert-column needcols
2603 ses--numcols
2604 (ses-col-width (1- ses--numcols))
2605 (ses-col-printer (1- ses--numcols)))))
2606 rowcol))
2608 (defun ses-export-tsv (beg end)
2609 "Export values from the current range, with tabs between columns and
2610 newlines between rows. Result is placed in kill ring."
2611 (interactive "r")
2612 (ses-export-tab nil))
2614 (defun ses-export-tsf (beg end)
2615 "Export formulas from the current range, with tabs between columns and
2616 newlines between rows. Result is placed in kill ring."
2617 (interactive "r")
2618 (ses-export-tab t))
2620 (defun ses-export-tab (want-formulas)
2621 "Export the current range with tabs between columns and newlines between
2622 rows. Result is placed in kill ring. The export is values unless
2623 WANT-FORMULAS is non-nil. Newlines and tabs in the export text are escaped."
2624 (ses-check-curcell 'needrange)
2625 (let ((print-escape-newlines t)
2626 result item)
2627 (ses-dorange ses--curcell
2628 (setq item (if want-formulas
2629 (ses-cell-formula row col)
2630 (ses-cell-value row col)))
2631 (if (eq (car-safe item) 'ses-safe-formula)
2632 ;;Hide our deferred safety-check marker
2633 (setq item (cadr item)))
2634 (if (or (not item) (eq item '*skip*))
2635 (setq item ""))
2636 (when (eq (car-safe item) 'quote)
2637 (push "'" result)
2638 (setq item (cadr item)))
2639 (setq item (prin1-to-string item t))
2640 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
2641 (push item result)
2642 (cond
2643 ((< col maxcol)
2644 (push "\t" result))
2645 ((< row maxrow)
2646 (push "\n" result))))
2647 (setq result (apply 'concat (nreverse result)))
2648 (kill-new result)))
2651 ;;----------------------------------------------------------------------------
2652 ;; Other user commands
2653 ;;----------------------------------------------------------------------------
2655 (defun ses-unset-header-row ()
2656 "Select the default header row."
2657 (interactive)
2658 (ses-set-header-row 0))
2660 (defun ses-set-header-row (row)
2661 "Set the ROW to display in the header-line.
2662 With a numerical prefix arg, use that row.
2663 With no prefix arg, use the current row.
2664 With a \\[universal-argument] prefix arg, prompt the user.
2665 The top row is row 1. Selecting row 0 displays the default header row."
2666 (interactive
2667 (list (if (numberp current-prefix-arg) current-prefix-arg
2668 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
2669 (if current-prefix-arg
2670 (read-number "Header row: " currow)
2671 currow)))))
2672 (if (or (< row 0) (> row ses--numrows))
2673 (error "Invalid header-row"))
2674 (ses-begin-change)
2675 (let ((oldval ses--header-row))
2676 (let (buffer-undo-list)
2677 (ses-set-parameter 'ses--header-row row))
2678 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
2679 (ses-reset-header-string))
2681 (defun ses-mark-row ()
2682 "Marks the entirety of current row as a range."
2683 (interactive)
2684 (ses-check-curcell 'range)
2685 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
2686 (push-mark (point))
2687 (ses-goto-print (1+ row) 0)
2688 (push-mark (point) nil t)
2689 (ses-goto-print row 0)))
2691 (defun ses-mark-column ()
2692 "Marks the entirety of current column as a range."
2693 (interactive)
2694 (ses-check-curcell 'range)
2695 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
2696 (row 0))
2697 (push-mark (point))
2698 (ses-goto-print (1- ses--numrows) col)
2699 (forward-char 1)
2700 (push-mark (point) nil t)
2701 (while (eq '*skip* (ses-cell-value row col))
2702 ;;Skip over initial cells in column that can't be selected
2703 (setq row (1+ row)))
2704 (ses-goto-print row col)))
2706 (defun ses-end-of-line ()
2707 "Move point to last cell on line."
2708 (interactive)
2709 (ses-check-curcell 'end 'range)
2710 (when ses--curcell ;Otherwise we're at the bottom row, which is empty anyway
2711 (let ((col (1- ses--numcols))
2712 row rowcol)
2713 (if (symbolp ses--curcell)
2714 ;;Single cell
2715 (setq row (car (ses-sym-rowcol ses--curcell)))
2716 ;;Range - use whichever end of the range the point is at
2717 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
2718 (car ses--curcell)
2719 (cdr ses--curcell))))
2720 ;;If range already includes the last cell in a row, point is actually
2721 ;;in the following row
2722 (if (<= (cdr rowcol) (1- col))
2723 (setq row (car rowcol))
2724 (setq row (1+ (car rowcol)))
2725 (if (= row ses--numrows)
2726 ;;Already at end - can't go anywhere
2727 (setq col 0))))
2728 (when (< row ses--numrows) ;Otherwise it's a range that includes last cell
2729 (while (eq (ses-cell-value row col) '*skip*)
2730 ;;Back to beginning of multi-column cell
2731 (setq col (1- col)))
2732 (ses-goto-print row col)))))
2734 (defun ses-renarrow-buffer ()
2735 "Narrow the buffer so only the print area is visible. Use after \\[widen]."
2736 (interactive)
2737 (setq ses--deferred-narrow t))
2739 (defun ses-sort-column (sorter &optional reverse)
2740 "Sorts the range by a specified column. With prefix, sorts in
2741 REVERSE order."
2742 (interactive "*sSort column: \nP")
2743 (ses-check-curcell 'needrange)
2744 (let ((min (ses-sym-rowcol (car ses--curcell)))
2745 (max (ses-sym-rowcol (cdr ses--curcell))))
2746 (let ((minrow (car min))
2747 (mincol (cdr min))
2748 (maxrow (car max))
2749 (maxcol (cdr max))
2750 keys extracts end)
2751 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
2752 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
2753 (error "Invalid sort column"))
2754 ;;Get key columns and sort them
2755 (dotimes (x (- maxrow minrow -1))
2756 (ses-goto-print (+ minrow x) sorter)
2757 (setq end (next-single-property-change (point) 'intangible))
2758 (push (cons (buffer-substring-no-properties (point) end)
2759 (+ minrow x))
2760 keys))
2761 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
2762 ;;Extract the lines in reverse sorted order
2763 (or reverse
2764 (setq keys (nreverse keys)))
2765 (dolist (x keys)
2766 (ses-goto-print (cdr x) (1+ maxcol))
2767 (setq end (point))
2768 (ses-goto-print (cdr x) mincol)
2769 (push (ses-copy-region (point) end) extracts))
2770 (deactivate-mark)
2771 ;;Paste the lines sequentially
2772 (dotimes (x (- maxrow minrow -1))
2773 (ses-goto-print (+ minrow x) mincol)
2774 (ses-set-curcell)
2775 (ses-yank-cells (pop extracts) nil)))))
2777 (defun ses-sort-column-click (event reverse)
2778 "Mouse version of `ses-sort-column'."
2779 (interactive "*e\nP")
2780 (setq event (event-end event))
2781 (select-window (posn-window event))
2782 (setq event (car (posn-col-row event))) ;Click column
2783 (let ((col 0))
2784 (while (and (< col ses--numcols) (> event (ses-col-width col)))
2785 (setq event (- event (ses-col-width col) 1)
2786 col (1+ col)))
2787 (if (>= col ses--numcols)
2788 (ding)
2789 (ses-sort-column (ses-column-letter col) reverse))))
2791 (defun ses-insert-range ()
2792 "Inserts into minibuffer the list of cells currently highlighted in the
2793 spreadsheet."
2794 (interactive "*")
2795 (let (x)
2796 (with-current-buffer (window-buffer minibuffer-scroll-window)
2797 (ses-command-hook) ;For ses-coverage
2798 (ses-check-curcell 'needrange)
2799 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
2800 ,(cdr ses--curcell))))))
2801 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
2803 (defun ses-insert-ses-range ()
2804 "Inserts \"(ses-range x y)\" in the minibuffer to represent the currently
2805 highlighted range in the spreadsheet."
2806 (interactive "*")
2807 (let (x)
2808 (with-current-buffer (window-buffer minibuffer-scroll-window)
2809 (ses-command-hook) ;For ses-coverage
2810 (ses-check-curcell 'needrange)
2811 (setq x (format "(ses-range %S %S)"
2812 (car ses--curcell)
2813 (cdr ses--curcell))))
2814 (insert x)))
2816 (defun ses-insert-range-click (event)
2817 "Mouse version of `ses-insert-range'."
2818 (interactive "*e")
2819 (mouse-set-point event)
2820 (ses-insert-range))
2822 (defun ses-insert-ses-range-click (event)
2823 "Mouse version of `ses-insert-ses-range'."
2824 (interactive "*e")
2825 (mouse-set-point event)
2826 (ses-insert-ses-range))
2829 ;;----------------------------------------------------------------------------
2830 ;; Checking formulas for safety
2831 ;;----------------------------------------------------------------------------
2833 (defun ses-safe-printer (printer)
2834 "Returns PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
2835 (if (or (stringp printer)
2836 (stringp (car-safe printer))
2837 (not printer)
2838 (ses-warn-unsafe printer 'unsafep-function))
2839 printer
2840 'ses-unsafe))
2842 (defun ses-safe-formula (formula)
2843 "Returns FORMULA if safe, or the substitute formula *unsafe* otherwise."
2844 (if (ses-warn-unsafe formula 'unsafep)
2845 formula
2846 `(ses-unsafe ',formula)))
2848 (defun ses-warn-unsafe (formula checker)
2849 "Applies CHECKER to FORMULA. If result is non-nil, asks user for
2850 confirmation about FORMULA, which might be unsafe. Returns t if formula
2851 is safe or user allows execution anyway. Always returns t if
2852 `safe-functions' is t."
2853 (if (eq safe-functions t)
2855 (setq checker (funcall checker formula))
2856 (if (not checker)
2858 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
2859 formula checker)))))
2862 ;;----------------------------------------------------------------------------
2863 ;; Standard formulas
2864 ;;----------------------------------------------------------------------------
2866 (defmacro ses-range (from to)
2867 "Expands to a list of cell-symbols for the range. The range automatically
2868 expands to include any new row or column inserted into its middle. The SES
2869 library code specifically looks for the symbol `ses-range', so don't create an
2870 alias for this macro!"
2871 (let (result)
2872 (ses-dorange (cons from to)
2873 (push (ses-cell-symbol row col) result))
2874 (cons 'list result)))
2876 (defun ses-delete-blanks (&rest args)
2877 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
2878 (let (result)
2879 (dolist (cur args)
2880 (unless (memq cur '(nil *skip*))
2881 (push cur result)))
2882 result))
2884 (defun ses+ (&rest args)
2885 "Compute the sum of the arguments, ignoring blanks."
2886 (apply '+ (apply 'ses-delete-blanks args)))
2888 (defun ses-average (list)
2889 "Computes the sum of the numbers in LIST, divided by their length. Blanks
2890 are ignored. Result is always floating-point, even if all args are integers."
2891 (setq list (apply 'ses-delete-blanks list))
2892 (/ (float (apply '+ list)) (length list)))
2894 (defmacro ses-select (fromrange test torange)
2895 "Select cells in FROMRANGE that are `equal' to TEST. For each match, return
2896 the corresponding cell from TORANGE. The ranges are macroexpanded but not
2897 evaluated so they should be either (ses-range BEG END) or (list ...). The
2898 TEST is evaluated."
2899 (setq fromrange (cdr (macroexpand fromrange))
2900 torange (cdr (macroexpand torange))
2901 test (eval test))
2902 (or (= (length fromrange) (length torange))
2903 (error "ses-select: Ranges not same length"))
2904 (let (result)
2905 (dolist (x fromrange)
2906 (if (equal test (symbol-value x))
2907 (push (car torange) result))
2908 (setq torange (cdr torange)))
2909 (cons 'list result)))
2911 ;;All standard formulas are safe
2912 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
2913 ses-select))
2914 (put x 'side-effect-free t))
2917 ;;----------------------------------------------------------------------------
2918 ;; Standard print functions
2919 ;;----------------------------------------------------------------------------
2921 ;;These functions use the variables 'row' and 'col' that are
2922 ;;dynamically bound by ses-print-cell. We define these variables at
2923 ;;compile-time to make the compiler happy.
2924 (eval-when-compile
2925 (dolist (x '(row col))
2926 (make-local-variable x)
2927 (set x nil)))
2929 (defun ses-center (value &optional span fill)
2930 "Print VALUE, centered within column. FILL is the fill character for
2931 centering (default = space). SPAN indicates how many additional rightward
2932 columns to include in width (default = 0)."
2933 (let ((printer (or (ses-col-printer col) ses--default-printer))
2934 (width (ses-col-width col))
2935 half)
2936 (or fill (setq fill ?\s))
2937 (or span (setq span 0))
2938 (setq value (ses-call-printer printer value))
2939 (dotimes (x span)
2940 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
2941 (setq width (- width (length value)))
2942 (if (<= width 0)
2943 value ;Too large for field, anyway
2944 (setq half (make-string (/ width 2) fill))
2945 (concat half value half
2946 (if (> (% width 2) 0) (char-to-string fill))))))
2948 (defun ses-center-span (value &optional fill)
2949 "Print VALUE, centered within the span that starts in the current column
2950 and continues until the next nonblank column. FILL specifies the fill
2951 character (default = space)."
2952 (let ((end (1+ col)))
2953 (while (and (< end ses--numcols)
2954 (memq (ses-cell-value row end) '(nil *skip*)))
2955 (setq end (1+ end)))
2956 (ses-center value (- end col 1) fill)))
2958 (defun ses-dashfill (value &optional span)
2959 "Print VALUE centered using dashes. SPAN indicates how many rightward
2960 columns to include in width (default = 0)."
2961 (ses-center value span ?-))
2963 (defun ses-dashfill-span (value)
2964 "Print VALUE, centered using dashes within the span that starts in the
2965 current column and continues until the next nonblank column."
2966 (ses-center-span value ?-))
2968 (defun ses-tildefill-span (value)
2969 "Print VALUE, centered using tildes within the span that starts in the
2970 current column and continues until the next nonblank column."
2971 (ses-center-span value ?~))
2973 (defun ses-unsafe (value)
2974 "Substitute for an unsafe formula or printer"
2975 (error "Unsafe formula or printer"))
2977 ;;All standard printers are safe, including ses-unsafe!
2978 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
2979 (put x 'side-effect-free t))
2981 (defun ses-unload-function ()
2982 "Unload the Simple Emacs Spreadsheet."
2983 (dolist (fun '(copy-region-as-kill yank))
2984 (ad-remove-advice fun 'around (intern (concat "ses-" (symbol-name fun))))
2985 (ad-update fun))
2986 (save-current-buffer
2987 (dolist (buf (buffer-list))
2988 (set-buffer buf)
2989 (when (eq major-mode 'ses-mode)
2990 (funcall (or default-major-mode 'fundamental-mode)))))
2991 ;; continue standard unloading
2992 nil)
2994 (provide 'ses)
2996 ;; arch-tag: 88c1ccf0-4293-4824-8c5d-0757b52217f3
2997 ;;; ses.el ends here