* process.h (PSET): Remove.
[emacs.git] / lisp / ses.el
blob8add16a69964c735dfa6bf522c6f30a1c1071fee
1 ;;; ses.el -- Simple Emacs Spreadsheet -*- coding: utf-8 -*-
3 ;; Copyright (C) 2002-2012 Free Software Foundation, Inc.
5 ;; Author: Jonathan Yavner <jyavner@member.fsf.org>
6 ;; Maintainer: Vincent Belaïche <vincentb1@users.sourceforge.net>
7 ;; Keywords: spreadsheet Dijkstra
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;;; To-do list:
28 ;; * split (catch 'cycle ...) call back into one or more functions
29 ;; * Use $ or … for truncated fields
30 ;; * Add command to make a range of columns be temporarily invisible.
31 ;; * Allow paste of one cell to a range of cells -- copy formula to each.
32 ;; * Do something about control characters & octal codes in cell print
33 ;; areas. Use string-width?
34 ;; * Input validation functions. How specified?
35 ;; * Faces (colors & styles) in print cells.
36 ;; * Move a column by dragging its letter in the header line.
37 ;; * Left-margin column for row number.
38 ;; * Move a row by dragging its number in the left-margin.
40 ;;; Cycle detection
42 ;; Cycles used to be detected by stationarity of ses--deferred-recalc. This was
43 ;; working fine in most cases, however failed in some cases of several path
44 ;; racing together.
46 ;; The current algorithm is based on Dijkstra's algorithm. The cycle length is
47 ;; stored in some cell property. In order not to reset in all cells such
48 ;; property at each update, the cycle length is stored in this property along
49 ;; with some update attempt id that is incremented at each update. The current
50 ;; update id is ses--Dijkstra-attempt-nb. In case there is a cycle the cycle
51 ;; length diverge to infinite so it will exceed ses--Dijkstra-weight-bound at
52 ;; some point of time that allows detection. Otherwise it converges to the
53 ;; longest path length in the update tree.
56 ;;; Code:
58 (require 'unsafep)
59 (eval-when-compile (require 'cl-lib))
62 ;;----------------------------------------------------------------------------
63 ;; User-customizable variables
64 ;;----------------------------------------------------------------------------
66 (defgroup ses nil
67 "Simple Emacs Spreadsheet."
68 :tag "SES"
69 :group 'applications
70 :prefix "ses-"
71 :version "21.1")
73 (defcustom ses-initial-size '(1 . 1)
74 "Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
75 :group 'ses
76 :type '(cons (integer :tag "numrows") (integer :tag "numcols")))
78 (defcustom ses-initial-column-width 7
79 "Initial width of columns in a new spreadsheet."
80 :group 'ses
81 :type '(integer :match (lambda (widget value) (> value 0))))
83 (defcustom ses-initial-default-printer "%.7g"
84 "Initial default printer for a new spreadsheet."
85 :group 'ses
86 :type '(choice string
87 (list :tag "Parenthesized string" string)
88 function))
90 (defcustom ses-after-entry-functions '(forward-char)
91 "Things to do after entering a value into a cell.
92 An abnormal hook that usually runs a cursor-movement function.
93 Each function is called with ARG=1."
94 :group 'ses
95 :type 'hook
96 :options '(forward-char backward-char next-line previous-line))
98 (defcustom ses-mode-hook nil
99 "Hook functions to be run upon entering SES mode."
100 :group 'ses
101 :type 'hook)
104 ;;----------------------------------------------------------------------------
105 ;; Global variables and constants
106 ;;----------------------------------------------------------------------------
108 (defvar ses-read-cell-history nil
109 "List of formulas that have been typed in.")
111 (defvar ses-read-printer-history nil
112 "List of printer functions that have been typed in.")
114 (easy-menu-define ses-header-line-menu nil
115 "Context menu when mouse-3 is used on the header-line in an SES buffer."
116 '("SES header row"
117 ["Set current row" ses-set-header-row t]
118 ["Unset row" ses-unset-header-row (> ses--header-row 0)]))
120 (defconst ses-mode-map
121 (let ((keys `("\C-c\M-\C-l" ses-reconstruct-all
122 "\C-c\C-l" ses-recalculate-all
123 "\C-c\C-n" ses-renarrow-buffer
124 "\C-c\C-c" ses-recalculate-cell
125 "\C-c\M-\C-s" ses-sort-column
126 "\C-c\M-\C-h" ses-set-header-row
127 "\C-c\C-t" ses-truncate-cell
128 "\C-c\C-j" ses-jump
129 "\C-c\C-p" ses-read-default-printer
130 "\M-\C-l" ses-reprint-all
131 [?\S-\C-l] ses-reprint-all
132 [header-line down-mouse-3] ,ses-header-line-menu
133 [header-line mouse-2] ses-sort-column-click))
134 (newmap (make-sparse-keymap)))
135 (while keys
136 (define-key (1value newmap) (car keys) (cadr keys))
137 (setq keys (cddr keys)))
138 newmap)
139 "Local keymap for Simple Emacs Spreadsheet.")
141 (easy-menu-define ses-menu ses-mode-map
142 "Menu bar menu for SES."
143 '("SES"
144 ["Insert row" ses-insert-row (ses-in-print-area)]
145 ["Delete row" ses-delete-row (ses-in-print-area)]
146 ["Insert column" ses-insert-column (ses-in-print-area)]
147 ["Delete column" ses-delete-column (ses-in-print-area)]
148 ["Set column printer" ses-read-column-printer t]
149 ["Set column width" ses-set-column-width t]
150 ["Set default printer" ses-read-default-printer t]
151 ["Jump to cell" ses-jump t]
152 ["Set cell printer" ses-read-cell-printer t]
153 ["Recalculate cell" ses-recalculate-cell t]
154 ["Truncate cell display" ses-truncate-cell t]
155 ["Export values" ses-export-tsv t]
156 ["Export formulas" ses-export-tsf t]))
158 (defconst ses-mode-edit-map
159 (let ((keys '("\C-c\C-r" ses-insert-range
160 "\C-c\C-s" ses-insert-ses-range
161 [S-mouse-3] ses-insert-range-click
162 [C-S-mouse-3] ses-insert-ses-range-click
163 "\M-\C-i" lisp-complete-symbol))
164 (newmap (make-sparse-keymap)))
165 (set-keymap-parent newmap minibuffer-local-map)
166 (while keys
167 (define-key newmap (pop keys) (pop keys)))
168 newmap)
169 "Local keymap for SES minibuffer cell-editing.")
171 ;Local keymap for SES print area
172 (defalias 'ses-mode-print-map
173 (let ((keys '([backtab] backward-char
174 [tab] ses-forward-or-insert
175 "\C-i" ses-forward-or-insert ; Needed for ses-coverage.el?
176 "\M-o" ses-insert-column
177 "\C-o" ses-insert-row
178 "\C-m" ses-edit-cell
179 "\M-k" ses-delete-column
180 "\M-y" ses-yank-pop
181 "\C-k" ses-delete-row
182 "\C-j" ses-append-row-jump-first-column
183 "\M-h" ses-mark-row
184 "\M-H" ses-mark-column
185 "\C-d" ses-clear-cell-forward
186 "\C-?" ses-clear-cell-backward
187 "(" ses-read-cell
188 "\"" ses-read-cell
189 "'" ses-read-symbol
190 "=" ses-edit-cell
191 "c" ses-recalculate-cell
192 "j" ses-jump
193 "p" ses-read-cell-printer
194 "t" ses-truncate-cell
195 "w" ses-set-column-width
196 "x" ses-export-keymap
197 "\M-p" ses-read-column-printer))
198 (repl '(;;We'll replace these wherever they appear in the keymap
199 clipboard-kill-region ses-kill-override
200 end-of-line ses-end-of-line
201 kill-line ses-delete-row
202 kill-region ses-kill-override
203 open-line ses-insert-row))
204 (numeric "0123456789.-")
205 (newmap (make-keymap)))
206 ;;Get rid of printables
207 (suppress-keymap newmap t)
208 ;;These keys insert themselves as the beginning of a numeric value
209 (dotimes (x (length numeric))
210 (define-key newmap (substring numeric x (1+ x)) 'ses-read-cell))
211 ;;Override these global functions wherever they're bound
212 (while repl
213 (substitute-key-definition (car repl) (cadr repl) newmap
214 (current-global-map))
215 (setq repl (cddr repl)))
216 ;;Apparently substitute-key-definition doesn't catch this?
217 (define-key newmap [(menu-bar) edit cut] 'ses-kill-override)
218 ;;Define our other local keys
219 (while keys
220 (define-key newmap (car keys) (cadr keys))
221 (setq keys (cddr keys)))
222 newmap))
224 ;;Helptext for ses-mode wants keymap as variable, not function
225 (defconst ses-mode-print-map (symbol-function 'ses-mode-print-map))
227 ;;Key map used for 'x' key.
228 (defalias 'ses-export-keymap
229 (let ((map (make-sparse-keymap "SES export")))
230 (define-key map "T" (cons " tab-formulas" 'ses-export-tsf))
231 (define-key map "t" (cons " tab-values" 'ses-export-tsv))
232 map))
234 (defconst ses-print-data-boundary "\n\014\n"
235 "Marker string denoting the boundary between print area and data area.")
237 (defconst ses-initial-global-parameters
238 "\n( ;Global parameters (these are read first)\n 2 ;SES file-format\n 1 ;numrows\n 1 ;numcols\n)\n\n"
239 "Initial contents for the three-element list at the bottom of the data area.")
241 (defconst ses-initial-file-trailer
242 ";; Local Variables:\n;; mode: ses\n;; End:\n"
243 "Initial contents for the file-trailer area at the bottom of the file.")
245 (defconst ses-initial-file-contents
246 (concat " \n" ; One blank cell in print area.
247 ses-print-data-boundary
248 "(ses-cell A1 nil nil nil nil)\n" ; One blank cell in data area.
249 "\n" ; End-of-row terminator for the one row in data area.
250 "(ses-column-widths [7])\n"
251 "(ses-column-printers [nil])\n"
252 "(ses-default-printer \"%.7g\")\n"
253 "(ses-header-row 0)\n"
254 ses-initial-global-parameters
255 ses-initial-file-trailer)
256 "The initial contents of an empty spreadsheet.")
258 (defconst ses-box-prop '(:box (:line-width 2 :style released-button))
259 "Display properties to create a raised box for cells in the header line.")
261 (defconst ses-standard-printer-functions
262 '(ses-center ses-center-span ses-dashfill ses-dashfill-span
263 ses-tildefill-span)
264 "List of print functions to be included in initial history of printer
265 functions. None of these standard-printer functions is suitable for use as a
266 column printer or a global-default printer because they invoke the column or
267 default printer and then modify its output.")
270 ;;----------------------------------------------------------------------------
271 ;; Local variables and constants
272 ;;----------------------------------------------------------------------------
274 (eval-and-compile
275 (defconst ses-localvars
276 '(ses--blank-line ses--cells ses--col-printers
277 ses--col-widths ses--curcell ses--curcell-overlay
278 ses--default-printer
279 ses--deferred-narrow ses--deferred-recalc
280 ses--deferred-write ses--file-format
281 (ses--header-hscroll . -1) ; Flag for "initial recalc needed"
282 ses--header-row ses--header-string ses--linewidth
283 ses--numcols ses--numrows ses--symbolic-formulas
284 ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
285 ses--Dijkstra-weight-bound
286 ;; This list is useful to speed-up clean-up of symbols when
287 ;; an area containing renamed cell is deleted.
288 ses--renamed-cell-symb-list
289 ;; Global variables that we override
290 mode-line-process next-line-add-newlines transient-mark-mode)
291 "Buffer-local variables used by SES.")
293 (defun ses-set-localvars ()
294 "Set buffer-local and initialize some SES variables."
295 (dolist (x ses-localvars)
296 (cond
297 ((symbolp x)
298 (set (make-local-variable x) nil))
299 ((consp x)
300 (set (make-local-variable (car x)) (cdr x)))
301 (t (error "Unexpected elements `%S' in list `ses-localvars'" x))))))
303 (eval-when-compile ; silence compiler
304 (ses-set-localvars))
306 ;;; This variable is documented as being permitted in file-locals:
307 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
309 (defconst ses-paramlines-plist
310 '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
311 ses--header-row -2 ses--file-format 1 ses--numrows 2
312 ses--numcols 3)
313 "Offsets from 'Global parameters' line to various parameter lines in the
314 data area of a spreadsheet.")
318 ;; "Side-effect variables". They are set in one function, altered in
319 ;; another as a side effect, then read back by the first, as a way of
320 ;; passing back more than one value. These declarations are just to make
321 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
322 ;; think the make-local-variable trick above is cleaner).
325 (defvar ses-relocate-return nil
326 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
327 `ses-relocate-all'. Set to 'delete if a cell-reference was deleted from a
328 formula--so the formula needs recalculation. Set to 'range if the size of a
329 `ses-range' was changed--so both the formula's value and list of dependents
330 need to be recalculated.")
332 (defvar ses-call-printer-return nil
333 "Set to t if last cell printer invoked by `ses-call-printer' requested
334 left-justification of the result. Set to error-signal if `ses-call-printer'
335 encountered an error during printing. Otherwise nil.")
337 (defvar ses-start-time nil
338 "Time when current operation started. Used by `ses-time-check' to decide
339 when to emit a progress message.")
342 ;;----------------------------------------------------------------------------
343 ;; Macros
344 ;;----------------------------------------------------------------------------
346 (defmacro ses-get-cell (row col)
347 "Return the cell structure that stores information about cell (ROW,COL)."
348 `(aref (aref ses--cells ,row) ,col))
350 ;; We might want to use defstruct here, but cells are explicitly used as
351 ;; arrays in ses-set-cell, so we'd need to fix this first. --Stef
352 (defsubst ses-make-cell (&optional symbol formula printer references
353 property-list)
354 (vector symbol formula printer references property-list))
356 (defmacro ses-cell-symbol (row &optional col)
357 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
358 `(aref ,(if col `(ses-get-cell ,row ,col) row) 0))
359 (put 'ses-cell-symbol 'safe-function t)
361 (defmacro ses-cell-formula (row &optional col)
362 "From a CELL or a pair (ROW,COL), get the function that computes its value."
363 `(aref ,(if col `(ses-get-cell ,row ,col) row) 1))
365 (defmacro ses-cell-formula-aset (cell formula)
366 "From a CELL set the function that computes its value."
367 `(aset ,cell 1 ,formula))
369 (defmacro ses-cell-printer (row &optional col)
370 "From a CELL or a pair (ROW,COL), get the function that prints its value."
371 `(aref ,(if col `(ses-get-cell ,row ,col) row) 2))
373 (defmacro ses-cell-references (row &optional col)
374 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
375 functions refer to its value."
376 `(aref ,(if col `(ses-get-cell ,row ,col) row) 3))
378 (defmacro ses-cell-references-aset (cell references)
379 "From a CELL set the list REFERENCES of symbols for cells the
380 function of which refer to its value."
381 `(aset ,cell 3 ,references))
383 (defun ses-cell-p (cell)
384 "Return non `nil' is CELL is a cell of current buffer."
385 (and (vectorp cell)
386 (= (length cell) 5)
387 (eq cell (let ((rowcol (ses-sym-rowcol (ses-cell-symbol cell))))
388 (and (consp rowcol)
389 (ses-get-cell (car rowcol) (cdr rowcol)))))))
391 (defun ses-cell-property-get-fun (property-name cell)
392 ;; To speed up property fetching, each time a property is found it is placed
393 ;; in the first position. This way, after the first get, the full property
394 ;; list needs to be scanned only when the property does not exist for that
395 ;; cell.
396 (let* ((plist (aref cell 4))
397 (ret (plist-member plist property-name)))
398 (if ret
399 ;; Property was found.
400 (let ((val (cadr ret)))
401 (if (eq ret plist)
402 ;; Property found is already in the first position, so just return
403 ;; its value.
405 ;; Property is not in the first position, the following will move it
406 ;; there before returning its value.
407 (let ((next (cddr ret)))
408 (if next
409 (progn
410 (setcdr ret (cdr next))
411 (setcar ret (car next)))
412 (setcdr (last plist 1) nil)))
413 (aset cell 4
414 `(,property-name ,val ,@plist))
415 val)))))
417 (defmacro ses-cell-property-get (property-name row &optional col)
418 "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
420 When COL is omitted, CELL=ROW is a cell object. When COL is
421 present ROW and COL are the integer coordinates of the cell of
422 interest."
423 (declare (debug t))
424 `(ses-cell-property-get-fun
425 ,property-name
426 ,(if col `(ses-get-cell ,row ,col) row)))
428 (defun ses-cell-property-delq-fun (property-name cell)
429 (let ((ret (plist-get (aref cell 4) property-name)))
430 (if ret
431 (setcdr ret (cddr ret)))))
433 (defun ses-cell-property-set-fun (property-name property-val cell)
434 (let* ((plist (aref cell 4))
435 (ret (plist-member plist property-name)))
436 (if ret
437 (setcar (cdr ret) property-val)
438 (aset cell 4 `(,property-name ,property-val ,@plist)))))
440 (defmacro ses-cell-property-set (property-name property-value row &optional col)
441 "From a CELL or a pair (ROW,COL), set the property value of
442 the corresponding cell with name PROPERTY-NAME to PROPERTY-VALUE."
443 (if property-value
444 `(ses-cell-property-set-fun ,property-name ,property-value
445 ,(if col `(ses-get-cell ,row ,col) row))
446 `(ses-cell-property-delq-fun ,property-name
447 ,(if col `(ses-get-cell ,row ,col) row))))
449 (defun ses-cell-property-pop-fun (property-name cell)
450 (let* ((plist (aref cell 4))
451 (ret (plist-member plist property-name)))
452 (if ret
453 (prog1 (cadr ret)
454 (let ((next (cddr ret)))
455 (if next
456 (progn
457 (setcdr ret (cdr next))
458 (setcar ret (car next)))
459 (if (eq plist ret)
460 (aset cell 4 nil)
461 (setcdr (last plist 2) nil))))))))
464 (defmacro ses-cell-property-pop (property-name row &optional col)
465 "From a CELL or a pair (ROW,COL), get and remove the property value of
466 the corresponding cell with name PROPERTY-NAME."
467 `(ses-cell-property-pop-fun ,property-name
468 ,(if col `(ses-get-cell ,row ,col) row)))
470 (defun ses-cell-property-get-handle-fun (property-name cell)
471 (let* ((plist (aref cell 4))
472 (ret (plist-member plist property-name)))
473 (if ret
474 (if (eq ret plist)
475 (cdr ret)
476 (let ((val (cadr ret))
477 (next (cddr ret)))
478 (if next
479 (progn
480 (setcdr ret (cdr next))
481 (setcar ret (car next)))
482 (setcdr (last plist 2) nil))
483 (setq ret (cons val plist))
484 (aset cell 4 (cons property-name ret))
485 ret))
486 (setq ret (cons nil plist))
487 (aset cell 4 (cons property-name ret))
488 ret)))
490 (defmacro ses-cell-property-get-handle (property-name row &optional col)
491 "From a CELL or a pair (ROW,COL), get a cons cell whose car is
492 the property value of the corresponding cell property with name
493 PROPERTY-NAME."
494 `(ses-cell-property-get-handle-fun ,property-name
495 ,(if col `(ses-get-cell ,row ,col) row)))
498 (defalias 'ses-cell-property-handle-car 'car)
499 (defalias 'ses-cell-property-handle-setcar 'setcar)
501 (defmacro ses-cell-value (row &optional col)
502 "From a CELL or a pair (ROW,COL), get the current value for that cell."
503 `(symbol-value (ses-cell-symbol ,row ,col)))
505 (defmacro ses-col-width (col)
506 "Return the width for column COL."
507 `(aref ses--col-widths ,col))
509 (defmacro ses-col-printer (col)
510 "Return the default printer for column COL."
511 `(aref ses--col-printers ,col))
513 (defmacro ses-sym-rowcol (sym)
514 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0).
515 Result is nil if SYM is not a symbol that names a cell."
516 `(and (symbolp ,sym) (get ,sym 'ses-cell)))
518 (defmacro ses-cell (sym value formula printer references)
519 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
520 FORMULA, does not reprint using PRINTER, does not check REFERENCES. This is a
521 macro to prevent propagate-on-load viruses. Safety-checking for FORMULA and
522 PRINTER are deferred until first use."
523 (let ((rowcol (ses-sym-rowcol sym)))
524 (ses-formula-record formula)
525 (ses-printer-record printer)
526 (or (atom formula)
527 (eq safe-functions t)
528 (setq formula `(ses-safe-formula ,formula)))
529 (or (not printer)
530 (stringp printer)
531 (eq safe-functions t)
532 (setq printer `(ses-safe-printer ,printer)))
533 (aset (aref ses--cells (car rowcol))
534 (cdr rowcol)
535 (ses-make-cell sym formula printer references)))
536 (set sym value)
537 sym)
539 (defmacro ses-column-widths (widths)
540 "Load the vector of column widths from the spreadsheet file. This is a
541 macro to prevent propagate-on-load viruses."
542 (or (and (vectorp widths) (= (length widths) ses--numcols))
543 (error "Bad column-width vector"))
544 ;;To save time later, we also calculate the total width of each line in the
545 ;;print area (excluding the terminating newline)
546 (setq ses--col-widths widths
547 ses--linewidth (apply '+ -1 (mapcar '1+ widths))
548 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
551 (defmacro ses-column-printers (printers)
552 "Load the vector of column printers from the spreadsheet file and checks
553 them for safety. This is a macro to prevent propagate-on-load viruses."
554 (or (and (vectorp printers) (= (length printers) ses--numcols))
555 (error "Bad column-printers vector"))
556 (dotimes (x ses--numcols)
557 (aset printers x (ses-safe-printer (aref printers x))))
558 (setq ses--col-printers printers)
559 (mapc 'ses-printer-record printers)
562 (defmacro ses-default-printer (def)
563 "Load the global default printer from the spreadsheet file and checks it
564 for safety. This is a macro to prevent propagate-on-load viruses."
565 (setq ses--default-printer (ses-safe-printer def))
566 (ses-printer-record def)
569 (defmacro ses-header-row (row)
570 "Load the header row from the spreadsheet file and checks it
571 for safety. This is a macro to prevent propagate-on-load viruses."
572 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
573 (error "Bad header-row"))
574 (setq ses--header-row row)
577 (defmacro ses-dorange (curcell &rest body)
578 "Execute BODY repeatedly, with the variables `row' and `col' set to each
579 cell in the range specified by CURCELL. The range is available in the
580 variables `minrow', `maxrow', `mincol', and `maxcol'."
581 (declare (indent defun) (debug (form body)))
582 (let ((cur (make-symbol "cur"))
583 (min (make-symbol "min"))
584 (max (make-symbol "max"))
585 (r (make-symbol "r"))
586 (c (make-symbol "c")))
587 `(let* ((,cur ,curcell)
588 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
589 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
590 (let ((minrow (car ,min))
591 (maxrow (car ,max))
592 (mincol (cdr ,min))
593 (maxcol (cdr ,max))
594 row col)
595 (if (or (> minrow maxrow) (> mincol maxcol))
596 (error "Empty range"))
597 (dotimes (,r (- maxrow minrow -1))
598 (setq row (+ ,r minrow))
599 (dotimes (,c (- maxcol mincol -1))
600 (setq col (+ ,c mincol))
601 ,@body))))))
603 ;;Support for coverage testing.
604 (defmacro 1value (form)
605 "For code-coverage testing, indicate that FORM is expected to always have
606 the same value."
607 form)
608 (defmacro noreturn (form)
609 "For code-coverage testing, indicate that FORM will always signal an error."
610 form)
613 ;;----------------------------------------------------------------------------
614 ;; Utility functions
615 ;;----------------------------------------------------------------------------
617 (defun ses-vector-insert (array idx new)
618 "Create a new vector which is one larger than ARRAY and has NEW inserted
619 before element IDX."
620 (let* ((len (length array))
621 (result (make-vector (1+ len) new)))
622 (dotimes (x len)
623 (aset result
624 (if (< x idx) x (1+ x))
625 (aref array x)))
626 result))
628 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
629 (defun ses-vector-delete (array idx count)
630 "Create a new vector which is a copy of ARRAY with COUNT objects removed
631 starting at element IDX. ARRAY is either a vector or a symbol whose value
632 is a vector--if a symbol, the new vector is assigned as the symbol's value."
633 (let* ((a (if (arrayp array) array (symbol-value array)))
634 (len (- (length a) count))
635 (result (make-vector len nil)))
636 (dotimes (x len)
637 (aset result x (aref a (if (< x idx) x (+ x count)))))
638 (if (symbolp array)
639 (set array result))
640 result))
642 (defun ses-delete-line (count)
643 "Like `kill-line', but no kill ring."
644 (let ((pos (point)))
645 (forward-line count)
646 (delete-region pos (point))))
648 (defun ses-printer-validate (printer)
649 "Signal an error if PRINTER is not a valid SES cell printer."
650 (or (not printer)
651 (stringp printer)
652 (functionp printer)
653 (and (stringp (car-safe printer)) (not (cdr printer)))
654 (error "Invalid printer function"))
655 printer)
657 (defun ses-printer-record (printer)
658 "Add PRINTER to `ses-read-printer-history' if not already there, after first
659 checking that it is a valid printer function."
660 (ses-printer-validate printer)
661 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
662 (if printer
663 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
665 (defun ses-formula-record (formula)
666 "If FORMULA is of the form 'symbol, add it to the list of symbolic formulas
667 for this spreadsheet."
668 (when (and (eq (car-safe formula) 'quote)
669 (symbolp (cadr formula)))
670 (add-to-list 'ses--symbolic-formulas
671 (list (symbol-name (cadr formula))))))
673 (defun ses-column-letter (col)
674 "Return the alphabetic name of column number COL.
675 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
676 (let ((units (char-to-string (+ ?A (% col 26)))))
677 (if (< col 26)
678 units
679 (concat (ses-column-letter (1- (/ col 26))) units))))
681 (defun ses-create-cell-symbol (row col)
682 "Produce a symbol that names the cell (ROW,COL). (0,0) => 'A1."
683 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
685 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
686 "Create buffer-local variables for cells. This is undoable."
687 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
688 buffer-undo-list)
689 (let (sym xrow xcol)
690 (dotimes (row (1+ (- maxrow minrow)))
691 (dotimes (col (1+ (- maxcol mincol)))
692 (setq xrow (+ row minrow)
693 xcol (+ col mincol)
694 sym (ses-create-cell-symbol xrow xcol))
695 (put sym 'ses-cell (cons xrow xcol))
696 (make-local-variable sym)))))
698 (defun ses-create-cell-variable (sym row col)
699 "Create a buffer-local variable `SYM' for cell at position (ROW, COL).
701 SYM is the symbol for that variable, ROW and COL are integers for
702 row and column of the cell, with numbering starting from 0.
704 Return nil in case of failure."
705 (unless (local-variable-p sym)
706 (make-local-variable sym)
707 (put sym 'ses-cell (cons row col))))
709 ;; We do not delete the ses-cell properties for the cell-variables, in
710 ;; case a formula that refers to this cell is in the kill-ring and is
711 ;; later pasted back in.
712 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
713 "Destroy buffer-local variables for cells. This is undoable."
714 (let (sym)
715 (dotimes (row (1+ (- maxrow minrow)))
716 (dotimes (col (1+ (- maxcol mincol)))
717 (let ((xrow (+ row minrow)) (xcol (+ col mincol)))
718 (setq sym (if (and (< xrow ses--numrows) (< xcol ses--numcols))
719 (ses-cell-symbol xrow xcol)
720 (ses-create-cell-symbol xrow xcol))))
721 (if (boundp sym)
722 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
723 buffer-undo-list))
724 (kill-local-variable sym))))
725 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
726 buffer-undo-list))
728 (defun ses-reset-header-string ()
729 "Flag the header string for update. Upon undo, the header string will be
730 updated again."
731 (push '(apply ses-reset-header-string) buffer-undo-list)
732 (setq ses--header-hscroll -1))
734 ;;Split this code off into a function to avoid coverage-testing difficulties
735 (defun ses-time-check (format arg)
736 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
737 and (eval ARG) and reset `ses-start-time' to the current time."
738 (when (> (- (float-time) ses-start-time) 1.0)
739 (message format (eval arg))
740 (setq ses-start-time (float-time)))
741 nil)
744 ;;----------------------------------------------------------------------------
745 ;; The cells
746 ;;----------------------------------------------------------------------------
748 (defun ses-set-cell (row col field val)
749 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
750 cell (ROW,COL). This is undoable. The cell's data will be updated through
751 `post-command-hook'."
752 (let ((cell (ses-get-cell row col))
753 (elt (plist-get '(value t symbol 0 formula 1 printer 2 references 3)
754 field))
755 change)
756 (or elt (signal 'args-out-of-range nil))
757 (setq change (if (eq elt t)
758 (ses-set-with-undo (ses-cell-symbol cell) val)
759 (ses-aset-with-undo cell elt val)))
760 (if change
761 (add-to-list 'ses--deferred-write (cons row col))))
762 nil) ; Make coverage-tester happy.
764 (defun ses-cell-set-formula (row col formula)
765 "Store a new formula for (ROW . COL) and enqueue the cell for
766 recalculation via `post-command-hook'. Updates the reference lists for the
767 cells that this cell refers to. Does not update cell value or reprint the
768 cell. To avoid inconsistencies, this function is not interruptible, which
769 means Emacs will crash if FORMULA contains a circular list."
770 (let* ((cell (ses-get-cell row col))
771 (old (ses-cell-formula cell)))
772 (let ((sym (ses-cell-symbol cell))
773 (oldref (ses-formula-references old))
774 (newref (ses-formula-references formula))
775 (inhibit-quit t)
776 x xrow xcol)
777 (add-to-list 'ses--deferred-recalc sym)
778 ;;Delete old references from this cell. Skip the ones that are also
779 ;;in the new list.
780 (dolist (ref oldref)
781 (unless (memq ref newref)
782 (setq x (ses-sym-rowcol ref)
783 xrow (car x)
784 xcol (cdr x))
785 (ses-set-cell xrow xcol 'references
786 (delq sym (ses-cell-references xrow xcol)))))
787 ;;Add new ones. Skip ones left over from old list
788 (dolist (ref newref)
789 (setq x (ses-sym-rowcol ref)
790 xrow (car x)
791 xcol (cdr x)
792 x (ses-cell-references xrow xcol))
793 (or (memq sym x)
794 (ses-set-cell xrow xcol 'references (cons sym x))))
795 (ses-formula-record formula)
796 (ses-set-cell row col 'formula formula))))
799 (defun ses-repair-cell-reference-all ()
800 "Repair cell reference and warn if there was some reference corruption."
801 (interactive "*")
802 (let (errors)
803 ;; Step 1, reset :ses-repair-reference cell property in the whole sheet.
804 (dotimes (row ses--numrows)
805 (dotimes (col ses--numcols)
806 (let ((references (ses-cell-property-pop :ses-repair-reference
807 row col)))
808 (when references
809 (push (list
810 (ses-cell-symbol row col)
811 :corrupt-property
812 references) errors)))))
814 ;; Step 2, build new.
815 (dotimes (row ses--numrows)
816 (dotimes (col ses--numcols)
817 (let* ((cell (ses-get-cell row col))
818 (sym (ses-cell-symbol cell))
819 (formula (ses-cell-formula cell))
820 (new-ref (ses-formula-references formula)))
821 (dolist (ref new-ref)
822 (let* ((rowcol (ses-sym-rowcol ref))
823 (h (ses-cell-property-get-handle :ses-repair-reference
824 (car rowcol) (cdr rowcol))))
825 (unless (memq ref (ses-cell-property-handle-car h))
826 (ses-cell-property-handle-setcar
828 (cons sym
829 (ses-cell-property-handle-car h)))))))))
831 ;; Step 3, overwrite with check.
832 (dotimes (row ses--numrows)
833 (dotimes (col ses--numcols)
834 (let* ((cell (ses-get-cell row col))
835 (irrelevant (ses-cell-references cell))
836 (new-ref (ses-cell-property-pop :ses-repair-reference cell))
837 missing)
838 (dolist (ref new-ref)
839 (if (memq ref irrelevant)
840 (setq irrelevant (delq ref irrelevant))
841 (push ref missing)))
842 (ses-set-cell row col 'references new-ref)
843 (when (or missing irrelevant)
844 (push `( ,(ses-cell-symbol cell)
845 ,@(and missing (list :missing missing))
846 ,@(and irrelevant (list :irrelevant irrelevant)))
847 errors)))))
848 (if errors
849 (warn "----------------------------------------------------------------
850 Some references were corrupted.
852 The following is a list where each element ELT is such
853 that (car ELT) is the reference of cell CELL with corruption,
854 and (cdr ELT) is a property list where
856 * property `:corrupt-property' means that
857 property `:ses-repair-reference' of cell CELL was initially non
858 nil,
860 * property `:missing' is a list of missing references
862 * property `:irrelevant' is a list of non needed references
864 %S" errors)
865 (message "No reference corruption found"))))
867 (defun ses-calculate-cell (row col force)
868 "Calculate and print the value for cell (ROW,COL) using the cell's formula
869 function and print functions, if any. Result is nil for normal operation, or
870 the error signal if the formula or print function failed. The old value is
871 left unchanged if it was *skip* and the new value is nil.
872 Any cells that depend on this cell are queued for update after the end of
873 processing for the current keystroke, unless the new value is the same as
874 the old and FORCE is nil."
875 (let ((cell (ses-get-cell row col))
876 cycle-error formula-error printer-error)
877 (let ((oldval (ses-cell-value cell))
878 (formula (ses-cell-formula cell))
879 newval
880 this-cell-Dijkstra-attempt-h
881 this-cell-Dijkstra-attempt
882 this-cell-Dijkstra-attempt+1
883 ref-cell-Dijkstra-attempt-h
884 ref-cell-Dijkstra-attempt
885 ref-rowcol)
886 (when (eq (car-safe formula) 'ses-safe-formula)
887 (setq formula (ses-safe-formula (cadr formula)))
888 (ses-set-cell row col 'formula formula))
889 (condition-case sig
890 (setq newval (eval formula))
891 (error
892 ;; Variable `sig' can't be nil.
893 (nconc sig (list (ses-cell-symbol cell)))
894 (setq formula-error sig
895 newval '*error*)))
896 (if (and (not newval) (eq oldval '*skip*))
897 ;; Don't lose the *skip* --- previous field spans this one.
898 (setq newval '*skip*))
899 (catch 'cycle
900 (when (or force (not (eq newval oldval)))
901 (add-to-list 'ses--deferred-write (cons row col)) ; In case force=t.
902 (setq this-cell-Dijkstra-attempt-h
903 (ses-cell-property-get-handle :ses-Dijkstra-attempt cell);
904 this-cell-Dijkstra-attempt
905 (ses-cell-property-handle-car this-cell-Dijkstra-attempt-h))
906 (if (null this-cell-Dijkstra-attempt)
907 (ses-cell-property-handle-setcar
908 this-cell-Dijkstra-attempt-h
909 (setq this-cell-Dijkstra-attempt
910 (cons ses--Dijkstra-attempt-nb 0)))
911 (unless (= ses--Dijkstra-attempt-nb
912 (car this-cell-Dijkstra-attempt))
913 (setcar this-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
914 (setcdr this-cell-Dijkstra-attempt 0)))
915 (setq this-cell-Dijkstra-attempt+1
916 (1+ (cdr this-cell-Dijkstra-attempt)))
917 (ses-set-cell row col 'value newval)
918 (dolist (ref (ses-cell-references cell))
919 (add-to-list 'ses--deferred-recalc ref)
920 (setq ref-rowcol (ses-sym-rowcol ref)
921 ref-cell-Dijkstra-attempt-h
922 (ses-cell-property-get-handle
923 :ses-Dijkstra-attempt
924 (car ref-rowcol) (cdr ref-rowcol))
925 ref-cell-Dijkstra-attempt
926 (ses-cell-property-handle-car ref-cell-Dijkstra-attempt-h))
928 (if (null ref-cell-Dijkstra-attempt)
929 (ses-cell-property-handle-setcar
930 ref-cell-Dijkstra-attempt-h
931 (setq ref-cell-Dijkstra-attempt
932 (cons ses--Dijkstra-attempt-nb
933 this-cell-Dijkstra-attempt+1)))
934 (if (= (car ref-cell-Dijkstra-attempt) ses--Dijkstra-attempt-nb)
935 (setcdr ref-cell-Dijkstra-attempt
936 (max (cdr ref-cell-Dijkstra-attempt)
937 this-cell-Dijkstra-attempt+1))
938 (setcar ref-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
939 (setcdr ref-cell-Dijkstra-attempt
940 this-cell-Dijkstra-attempt+1)))
942 (when (> this-cell-Dijkstra-attempt+1 ses--Dijkstra-weight-bound)
943 ;; Update print of this cell.
944 (throw 'cycle (setq formula-error
945 `(error ,(format "Found cycle on cells %S"
946 (ses-cell-symbol cell)))
947 cycle-error formula-error)))))))
948 (setq printer-error (ses-print-cell row col))
950 (and cycle-error
951 (error (error-message-string cycle-error)))
952 formula-error printer-error)))
954 (defun ses-clear-cell (row col)
955 "Delete formula and printer for cell (ROW,COL)."
956 (ses-set-cell row col 'printer nil)
957 (ses-cell-set-formula row col nil))
959 (defcustom ses-self-reference-early-detection nil
960 "True if cycle detection is early for cells that refer to themselves."
961 :version "24.1"
962 :type 'boolean
963 :group 'ses)
965 (defun ses-update-cells (list &optional force)
966 "Recalculate cells in LIST, checking for dependency loops. Prints
967 progress messages every second. Dependent cells are not recalculated
968 if the cell's value is unchanged and FORCE is nil."
969 (let ((ses--deferred-recalc list)
970 (nextlist list)
971 (pos (point))
972 curlist prevlist this-sym this-rowcol formula)
973 (with-temp-message " "
974 (while ses--deferred-recalc
975 ;; In each loop, recalculate cells that refer only to other cells that
976 ;; have already been recalculated or aren't in the recalculation region.
977 ;; Repeat until all cells have been processed or until the set of cells
978 ;; being worked on stops changing.
979 (if prevlist
980 (message "Recalculating... (%d cells left)"
981 (length ses--deferred-recalc)))
982 (setq curlist ses--deferred-recalc
983 ses--deferred-recalc nil
984 prevlist nextlist)
985 (while curlist
986 ;; this-sym has to be popped from curlist *BEFORE* the check, and not
987 ;; after because of the case of cells referring to themselves.
988 (setq this-sym (pop curlist)
989 this-rowcol (ses-sym-rowcol this-sym)
990 formula (ses-cell-formula (car this-rowcol)
991 (cdr this-rowcol)))
992 (or (catch 'ref
993 (dolist (ref (ses-formula-references formula))
994 (if (and ses-self-reference-early-detection (eq ref this-sym))
995 (error "Cycle found: cell %S is self-referring" this-sym)
996 (when (or (memq ref curlist)
997 (memq ref ses--deferred-recalc))
998 ;; This cell refers to another that isn't done yet
999 (add-to-list 'ses--deferred-recalc this-sym)
1000 (throw 'ref t)))))
1001 ;; ses-update-cells is called from post-command-hook, so
1002 ;; inhibit-quit is implicitly bound to t.
1003 (when quit-flag
1004 ;; Abort the recalculation. User will probably undo now.
1005 (error "Quit"))
1006 (ses-calculate-cell (car this-rowcol) (cdr this-rowcol) force)))
1007 (dolist (ref ses--deferred-recalc)
1008 (add-to-list 'nextlist ref)))
1009 (when ses--deferred-recalc
1010 ;; Just couldn't finish these.
1011 (dolist (x ses--deferred-recalc)
1012 (let ((this-rowcol (ses-sym-rowcol x)))
1013 (ses-set-cell (car this-rowcol) (cdr this-rowcol) 'value '*error*)
1014 (1value (ses-print-cell (car this-rowcol) (cdr this-rowcol)))))
1015 (error "Circular references: %s" ses--deferred-recalc))
1016 (message " "))
1017 ;; Can't use save-excursion here: if the cell under point is updated,
1018 ;; save-excursion's marker will move past the cell.
1019 (goto-char pos)))
1022 ;;----------------------------------------------------------------------------
1023 ;; The print area
1024 ;;----------------------------------------------------------------------------
1026 (defun ses-in-print-area ()
1027 "Return t if point is in print area of spreadsheet."
1028 (<= (point) ses--data-marker))
1030 ;; We turn off point-motion-hooks and explicitly position the cursor, in case
1031 ;; the intangible properties have gotten screwed up (e.g., when ses-goto-print
1032 ;; is called during a recursive ses-print-cell).
1033 (defun ses-goto-print (row col)
1034 "Move point to print area for cell (ROW,COL)."
1035 (let ((inhibit-point-motion-hooks t)
1036 (n 0))
1037 (goto-char (point-min))
1038 (forward-line row)
1039 ;; Calculate column position.
1040 (dotimes (c col)
1041 (setq n (+ n (ses-col-width c) 1)))
1042 ;; Move to the position.
1043 (and (> n (move-to-column n))
1044 (eolp)
1045 ;; Move point to the bol of next line (for TAB at the last cell).
1046 (forward-char))))
1048 (defun ses-set-curcell ()
1049 "Set `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
1050 region, or nil if cursor is not at a cell."
1051 (if (or (not mark-active)
1052 deactivate-mark
1053 (= (region-beginning) (region-end)))
1054 ;; Single cell.
1055 (setq ses--curcell (get-text-property (point) 'intangible))
1056 ;; Range.
1057 (let ((bcell (get-text-property (region-beginning) 'intangible))
1058 (ecell (get-text-property (1- (region-end)) 'intangible)))
1059 (when (= (region-end) ses--data-marker)
1060 ;; Correct for overflow.
1061 (setq ecell (get-text-property (- (region-end) 2) 'intangible)))
1062 (setq ses--curcell (if (and bcell ecell)
1063 (cons bcell ecell)
1064 nil))))
1065 nil)
1067 (defun ses-check-curcell (&rest args)
1068 "Signal an error if `ses--curcell' is inappropriate.
1069 The end marker is appropriate if some argument is 'end.
1070 A range is appropriate if some argument is 'range.
1071 A single cell is appropriate unless some argument is 'needrange."
1072 (if (eq ses--curcell t)
1073 ;; curcell recalculation was postponed, but user typed ahead.
1074 (ses-set-curcell))
1075 (cond
1076 ((not ses--curcell)
1077 (or (memq 'end args)
1078 (error "Not at cell")))
1079 ((consp ses--curcell)
1080 (or (memq 'range args)
1081 (memq 'needrange args)
1082 (error "Can't use a range")))
1083 ((memq 'needrange args)
1084 (error "Need a range"))))
1086 (defun ses-print-cell (row col)
1087 "Format and print the value of cell (ROW,COL) to the print area.
1088 Use the cell's printer function. If the cell's new print form is too wide,
1089 it will spill over into the following cell, but will not run off the end of the
1090 row or overwrite the next non-nil field. Result is nil for normal operation,
1091 or the error signal if the printer function failed and the cell was formatted
1092 with \"%s\". If the cell's value is *skip*, nothing is printed because the
1093 preceding cell has spilled over."
1094 (catch 'ses-print-cell
1095 (let* ((cell (ses-get-cell row col))
1096 (value (ses-cell-value cell))
1097 (printer (ses-cell-printer cell))
1098 (maxcol (1+ col))
1099 text sig startpos x)
1100 ;; Create the string to print.
1101 (cond
1102 ((eq value '*skip*)
1103 ;; Don't print anything.
1104 (throw 'ses-print-cell nil))
1105 ((eq value '*error*)
1106 (setq text (make-string (ses-col-width col) ?#)))
1108 ;; Deferred safety-check on printer.
1109 (if (eq (car-safe printer) 'ses-safe-printer)
1110 (ses-set-cell row col 'printer
1111 (setq printer (ses-safe-printer (cadr printer)))))
1112 ;; Print the value.
1113 (setq text (ses-call-printer (or printer
1114 (ses-col-printer col)
1115 ses--default-printer)
1116 value))
1117 (if (consp ses-call-printer-return)
1118 ;; Printer returned an error.
1119 (setq sig ses-call-printer-return))))
1120 ;; Adjust print width to match column width.
1121 (let ((width (ses-col-width col))
1122 (len (string-width text)))
1123 (cond
1124 ((< len width)
1125 ;; Fill field to length with spaces.
1126 (setq len (make-string (- width len) ?\s)
1127 text (if (eq ses-call-printer-return t)
1128 (concat text len)
1129 (concat len text))))
1130 ((> len width)
1131 ;; Spill over into following cells, if possible.
1132 (let ((maxwidth width))
1133 (while (and (> len maxwidth)
1134 (< maxcol ses--numcols)
1135 (or (not (setq x (ses-cell-value row maxcol)))
1136 (eq x '*skip*)))
1137 (unless x
1138 ;; Set this cell to '*skip* so it won't overwrite our spillover.
1139 (ses-set-cell row maxcol 'value '*skip*))
1140 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
1141 maxcol (1+ maxcol)))
1142 (if (<= len maxwidth)
1143 ;; Fill to complete width of all the fields spanned.
1144 (setq text (concat text (make-string (- maxwidth len) ?\s)))
1145 ;; Not enough room to end of line or next non-nil field. Truncate
1146 ;; if string or decimal; otherwise fill with error indicator.
1147 (setq sig `(error "Too wide" ,text))
1148 (cond
1149 ((stringp value)
1150 (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
1151 ((and (numberp value)
1152 (string-match "\\.[0-9]+" text)
1153 (>= 0 (setq width
1154 (- len maxwidth
1155 (- (match-end 0) (match-beginning 0))))))
1156 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
1157 (setq text (concat (substring text
1159 (- (match-beginning 0) width))
1160 (substring text (match-end 0)))))
1162 (setq text (make-string maxwidth ?#)))))))))
1163 ;; Substitute question marks for tabs and newlines. Newlines are used as
1164 ;; row-separators; tabs could confuse the reimport logic.
1165 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
1166 (ses-goto-print row col)
1167 (setq startpos (point))
1168 ;; Install the printed result. This is not interruptible.
1169 (let ((inhibit-read-only t)
1170 (inhibit-quit t))
1171 (let ((inhibit-point-motion-hooks t))
1172 (delete-region (point) (progn
1173 (move-to-column (+ (current-column)
1174 (string-width text)))
1175 (1+ (point)))))
1176 ;; We use concat instead of inserting separate strings in order to
1177 ;; reduce the number of cells in the undo list.
1178 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
1179 ;; We use set-text-properties to prevent a wacky print function from
1180 ;; inserting rogue properties, and to ensure that the keymap property is
1181 ;; inherited (is it a bug that only unpropertized strings actually
1182 ;; inherit from surrounding text?)
1183 (set-text-properties 0 (length x) nil x)
1184 (insert-and-inherit x)
1185 (put-text-property startpos (point) 'intangible
1186 (ses-cell-symbol cell))
1187 (when (and (zerop row) (zerop col))
1188 ;; Reconstruct special beginning-of-buffer attributes.
1189 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
1190 (put-text-property (point-min) (point) 'read-only 'ses)
1191 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)))
1192 (if (= row (1- ses--header-row))
1193 ;; This line is part of the header --- force recalc.
1194 (ses-reset-header-string))
1195 ;; If this cell (or a preceding one on the line) previously spilled over
1196 ;; and has gotten shorter, redraw following cells on line recursively.
1197 (when (and (< maxcol ses--numcols)
1198 (eq (ses-cell-value row maxcol) '*skip*))
1199 (ses-set-cell row maxcol 'value nil)
1200 (ses-print-cell row maxcol))
1201 ;; Return to start of cell.
1202 (goto-char startpos)
1203 sig)))
1205 (defun ses-call-printer (printer &optional value)
1206 "Invoke PRINTER (a string or parenthesized string or function-symbol or
1207 lambda of one argument) on VALUE. Result is the printed cell as a string.
1208 The variable `ses-call-printer-return' is set to t if the printer used
1209 parenthesis to request left-justification, or the error-signal if the
1210 printer signaled one (and \"%s\" is used as the default printer), else nil."
1211 (setq ses-call-printer-return nil)
1212 (condition-case signal
1213 (cond
1214 ((stringp printer)
1215 (if value
1216 (format printer value)
1217 ""))
1218 ((stringp (car-safe printer))
1219 (setq ses-call-printer-return t)
1220 (if value
1221 (format (car printer) value)
1222 ""))
1224 (setq value (funcall printer (or value "")))
1225 (if (stringp value)
1226 value
1227 (or (stringp (car-safe value))
1228 (error "Printer should return \"string\" or (\"string\")"))
1229 (setq ses-call-printer-return t)
1230 (car value))))
1231 (error
1232 (setq ses-call-printer-return signal)
1233 (prin1-to-string value t))))
1235 (defun ses-adjust-print-width (col change)
1236 "Insert CHANGE spaces in front of column COL, or at end of line if
1237 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
1238 `inhibit-quit' to t."
1239 (let ((inhibit-read-only t)
1240 (blank (if (> change 0) (make-string change ?\s)))
1241 (at-end (= col ses--numcols)))
1242 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
1243 ;; ses-set-with-undo always returns t for strings.
1244 (1value (ses-set-with-undo 'ses--blank-line
1245 (concat (make-string ses--linewidth ?\s) "\n")))
1246 (dotimes (row ses--numrows)
1247 (ses-goto-print row col)
1248 (when at-end
1249 ;; Insert new columns before newline.
1250 (let ((inhibit-point-motion-hooks t))
1251 (backward-char 1)))
1252 (if blank
1253 (insert blank)
1254 (delete-char (- change))))))
1256 (defun ses-print-cell-new-width (row col)
1257 "Same as `ses-print-cell', except if the cell's value is *skip*,
1258 the preceding nonskipped cell is reprinted. This function is used
1259 when the width of cell (ROW,COL) has changed."
1260 (if (not (eq (ses-cell-value row col) '*skip*))
1261 (ses-print-cell row col)
1262 ;;Cell was skipped over - reprint previous
1263 (ses-goto-print row col)
1264 (backward-char 1)
1265 (let ((rowcol (ses-sym-rowcol (get-text-property (point) 'intangible))))
1266 (ses-print-cell (car rowcol) (cdr rowcol)))))
1269 ;;----------------------------------------------------------------------------
1270 ;; The data area
1271 ;;----------------------------------------------------------------------------
1273 (defun ses-narrowed-p () (/= (- (point-max) (point-min)) (buffer-size)))
1275 (defun ses-widen ()
1276 "Turn off narrowing, to be reenabled at end of command loop."
1277 (if (ses-narrowed-p)
1278 (setq ses--deferred-narrow t))
1279 (widen))
1281 (defun ses-goto-data (def &optional col)
1282 "Move point to data area for (DEF,COL). If DEF is a row
1283 number, COL is the column number for a data cell -- otherwise DEF
1284 is one of the symbols ses--col-widths, ses--col-printers,
1285 ses--default-printer, ses--numrows, or ses--numcols."
1286 (ses-widen)
1287 (let ((inhibit-point-motion-hooks t)) ; In case intangible attrs are wrong.
1288 (if col
1289 ;; It's a cell.
1290 (progn
1291 (goto-char ses--data-marker)
1292 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
1293 ;; Convert def-symbol to offset.
1294 (setq def (plist-get ses-paramlines-plist def))
1295 (or def (signal 'args-out-of-range nil))
1296 (goto-char ses--params-marker)
1297 (forward-line def))))
1299 (defun ses-set-parameter (def value &optional elem)
1300 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1301 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1302 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
1303 (save-excursion
1304 ;; We call ses-goto-data early, using the old values of numrows and numcols
1305 ;; in case one of them is being changed.
1306 (ses-goto-data def)
1307 (let ((inhibit-read-only t)
1308 (fmt (plist-get '(ses--col-widths "(ses-column-widths %S)"
1309 ses--col-printers "(ses-column-printers %S)"
1310 ses--default-printer "(ses-default-printer %S)"
1311 ses--header-row "(ses-header-row %S)"
1312 ses--file-format " %S ;SES file-format"
1313 ses--numrows " %S ;numrows"
1314 ses--numcols " %S ;numcols")
1315 def))
1316 oldval)
1317 (if elem
1318 (progn
1319 (setq oldval (aref (symbol-value def) elem))
1320 (aset (symbol-value def) elem value))
1321 (setq oldval (symbol-value def))
1322 (set def value))
1323 ;; Special undo since it's outside the narrowed buffer.
1324 (let (buffer-undo-list)
1325 (delete-region (point) (line-end-position))
1326 (insert (format fmt (symbol-value def))))
1327 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1330 (defun ses-write-cells ()
1331 "Write cells in `ses--deferred-write' from local variables to data area.
1332 Newlines in the data are escaped."
1333 (let* ((inhibit-read-only t)
1334 (print-escape-newlines t)
1335 rowcol row col cell sym formula printer text)
1336 (setq ses-start-time (float-time))
1337 (with-temp-message " "
1338 (save-excursion
1339 (while ses--deferred-write
1340 (ses-time-check "Writing... (%d cells left)"
1341 '(length ses--deferred-write))
1342 (setq rowcol (pop ses--deferred-write)
1343 row (car rowcol)
1344 col (cdr rowcol)
1345 cell (ses-get-cell row col)
1346 sym (ses-cell-symbol cell)
1347 formula (ses-cell-formula cell)
1348 printer (ses-cell-printer cell))
1349 (if (eq (car-safe formula) 'ses-safe-formula)
1350 (setq formula (cadr formula)))
1351 (if (eq (car-safe printer) 'ses-safe-printer)
1352 (setq printer (cadr printer)))
1353 ;; This is noticeably faster than (format "%S %S %S %S %S")
1354 (setq text (concat "(ses-cell "
1355 (symbol-name sym)
1357 (prin1-to-string (symbol-value sym))
1359 (prin1-to-string formula)
1361 (prin1-to-string printer)
1363 (if (atom (ses-cell-references cell))
1364 "nil"
1365 (concat "("
1366 (mapconcat 'symbol-name
1367 (ses-cell-references cell)
1368 " ")
1369 ")"))
1370 ")"))
1371 (ses-goto-data row col)
1372 (delete-region (point) (line-end-position))
1373 (insert text)))
1374 (message " "))))
1377 ;;----------------------------------------------------------------------------
1378 ;; Formula relocation
1379 ;;----------------------------------------------------------------------------
1381 (defun ses-formula-references (formula &optional result-so-far)
1382 "Produce a list of symbols for cells that this FORMULA's value
1383 refers to. For recursive calls, RESULT-SO-FAR is the list being
1384 constructed, or t to get a wrong-type-argument error when the
1385 first reference is found."
1386 (if (ses-sym-rowcol formula)
1387 ;;Entire formula is one symbol
1388 (add-to-list 'result-so-far formula)
1389 (if (consp formula)
1390 (cond
1391 ((eq (car formula) 'ses-range)
1392 (dolist (cur
1393 (cdr (funcall 'macroexpand
1394 (list 'ses-range (nth 1 formula)
1395 (nth 2 formula)))))
1396 (add-to-list 'result-so-far cur)))
1397 ((null (eq (car formula) 'quote))
1398 ;;Recursive call for subformulas
1399 (dolist (cur formula)
1400 (setq result-so-far (ses-formula-references cur result-so-far))))
1402 ;;Ignore other stuff
1404 ;; other type of atom are ignored
1406 result-so-far)
1408 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1409 "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
1410 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1411 by (ROWINCR,COLINCR)."
1412 (let ((row (car rowcol))
1413 (col (cdr rowcol)))
1414 (if (or (< row startrow) (< col startcol))
1416 (setq row (+ row rowincr)
1417 col (+ col colincr))
1418 (if (and (>= row startrow) (>= col startcol)
1419 (< row ses--numrows) (< col ses--numcols))
1420 ;;Relocate this variable
1421 (ses-create-cell-symbol row col)
1422 ;;Delete reference to a deleted cell
1423 nil))))
1425 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1426 "Produce a copy of FORMULA where all symbols that refer to cells in row
1427 STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
1428 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1429 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1430 => (+ A1 B2 C4)
1431 If ROWINCR or COLINCR is negative, references to cells being deleted are
1432 removed. Example:
1433 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1434 => (+ A1 C3)
1435 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1436 (let (rowcol result)
1437 (if (or (atom formula) (eq (car formula) 'quote))
1438 (if (and (setq rowcol (ses-sym-rowcol formula))
1439 (string-match "\\`[A-Z]+[0-9]+\\'" (symbol-name formula)))
1440 (ses-relocate-symbol formula rowcol
1441 startrow startcol rowincr colincr)
1442 formula) ; Pass through as-is.
1443 (dolist (cur formula)
1444 (setq rowcol (ses-sym-rowcol cur))
1445 (cond
1446 (rowcol
1447 (setq cur (ses-relocate-symbol cur rowcol
1448 startrow startcol rowincr colincr))
1449 (if cur
1450 (push cur result)
1451 ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
1452 ;; don't change the flag if it's already 'range, since range implies
1453 ;; 'delete.
1454 (unless ses-relocate-return
1455 (setq ses-relocate-return 'delete))))
1456 ((eq (car-safe cur) 'ses-range)
1457 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1458 (if cur
1459 (push cur result)))
1460 ((or (atom cur) (eq (car cur) 'quote))
1461 ;; Constants pass through unchanged.
1462 (push cur result))
1464 ;; Recursively copy and alter subformulas.
1465 (push (ses-relocate-formula cur startrow startcol
1466 rowincr colincr)
1467 result))))
1468 (nreverse result))))
1470 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1471 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1472 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1473 new range, or nil if the entire range is deleted. If new rows are being added
1474 just beyond the end of a row range, or new columns just beyond a column range,
1475 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1476 if the range was altered."
1477 (let* ((minorig (cadr range))
1478 (minrowcol (ses-sym-rowcol minorig))
1479 (min (ses-relocate-symbol minorig minrowcol
1480 startrow startcol
1481 rowincr colincr))
1482 (maxorig (nth 2 range))
1483 (maxrowcol (ses-sym-rowcol maxorig))
1484 (max (ses-relocate-symbol maxorig maxrowcol
1485 startrow startcol
1486 rowincr colincr))
1487 field)
1488 (cond
1489 ((and (not min) (not max))
1490 (setq range nil)) ; The entire range is deleted.
1491 ((zerop colincr)
1492 ;; Inserting or deleting rows.
1493 (setq field 'car)
1494 (if (not min)
1495 ;; Chopped off beginning of range.
1496 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1497 ses-relocate-return 'range))
1498 (if (not max)
1499 (if (> rowincr 0)
1500 ;; Trying to insert a nonexistent row.
1501 (setq max (ses-create-cell-symbol (1- ses--numrows)
1502 (cdr minrowcol)))
1503 ;; End of range is being deleted.
1504 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1505 ses-relocate-return 'range))
1506 (and (> rowincr 0)
1507 (= (car maxrowcol) (1- startrow))
1508 (= (cdr minrowcol) (cdr maxrowcol))
1509 ;; Insert after ending row of vertical range --- include it.
1510 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1511 (cdr maxrowcol))))))
1513 ;; Inserting or deleting columns.
1514 (setq field 'cdr)
1515 (if (not min)
1516 ;; Chopped off beginning of range.
1517 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1518 ses-relocate-return 'range))
1519 (if (not max)
1520 (if (> colincr 0)
1521 ;; Trying to insert a nonexistent column.
1522 (setq max (ses-create-cell-symbol (car maxrowcol)
1523 (1- ses--numcols)))
1524 ;; End of range is being deleted.
1525 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1526 ses-relocate-return 'range))
1527 (and (> colincr 0)
1528 (= (cdr maxrowcol) (1- startcol))
1529 (= (car minrowcol) (car maxrowcol))
1530 ;; Insert after ending column of horizontal range --- include it.
1531 (setq max (ses-create-cell-symbol (car maxrowcol)
1532 (+ startcol colincr -1)))))))
1533 (when range
1534 (if (/= (- (funcall field maxrowcol)
1535 (funcall field minrowcol))
1536 (- (funcall field (ses-sym-rowcol max))
1537 (funcall field (ses-sym-rowcol min))))
1538 ;; This range has changed size.
1539 (setq ses-relocate-return 'range))
1540 `(ses-range ,min ,max ,@(cl-cdddr range)))))
1542 (defun ses-relocate-all (minrow mincol rowincr colincr)
1543 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1544 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1545 to each symbol."
1546 (let (reform)
1547 (let (mycell newval xrow)
1548 (dotimes-with-progress-reporter
1549 (row ses--numrows) "Relocating formulas..."
1550 (dotimes (col ses--numcols)
1551 (setq ses-relocate-return nil
1552 mycell (ses-get-cell row col)
1553 newval (ses-relocate-formula (ses-cell-formula mycell)
1554 minrow mincol rowincr colincr)
1555 xrow (- row rowincr))
1556 (ses-set-cell row col 'formula newval)
1557 (if (eq ses-relocate-return 'range)
1558 ;; This cell contains a (ses-range X Y) where a cell has been
1559 ;; inserted or deleted in the middle of the range.
1560 (push (cons row col) reform))
1561 (if ses-relocate-return
1562 ;; This cell referred to a cell that's been deleted or is no
1563 ;; longer part of the range. We can't fix that now because
1564 ;; reference lists cells have been partially updated.
1565 (add-to-list 'ses--deferred-recalc
1566 (ses-create-cell-symbol row col)))
1567 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1568 minrow mincol rowincr colincr))
1569 (ses-set-cell row col 'references newval)
1570 (and (>= row minrow) (>= col mincol)
1571 (let ((sym (ses-cell-symbol row col))
1572 (xcol (- col colincr)))
1573 (if (and
1575 (>= xrow 0)
1576 (>= xcol 0)
1577 (null (eq sym
1578 (ses-create-cell-symbol xrow xcol))))
1579 ;; This is a renamed cell, do not update the cell
1580 ;; name, but just update the coordinate property.
1581 (put sym 'ses-cell (cons row col))
1582 (ses-set-cell row col 'symbol
1583 (setq sym (ses-create-cell-symbol row col)))
1584 (unless (and (boundp sym) (local-variable-p sym))
1585 (set (make-local-variable sym) nil)
1586 (put sym 'ses-cell (cons row col)))))) )))
1587 ;; Relocate the cell values.
1588 (let (oldval myrow mycol xrow xcol)
1589 (cond
1590 ((and (<= rowincr 0) (<= colincr 0))
1591 ;; Deletion of rows and/or columns.
1592 (dotimes-with-progress-reporter
1593 (row (- ses--numrows minrow)) "Relocating variables..."
1594 (setq myrow (+ row minrow))
1595 (dotimes (col (- ses--numcols mincol))
1596 (setq mycol (+ col mincol)
1597 xrow (- myrow rowincr)
1598 xcol (- mycol colincr))
1599 (let ((sym (ses-cell-symbol myrow mycol))
1600 (xsym (ses-create-cell-symbol xrow xcol)))
1601 ;; Make the value relocation only when if the cell is not
1602 ;; a renamed cell. Otherwise this is not needed.
1603 (and (eq sym xsym)
1604 (ses-set-cell myrow mycol 'value
1605 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1606 (ses-cell-value xrow xcol)
1607 ;;Cell is off the end of the array
1608 (symbol-value xsym))))))))
1610 ((and (wholenump rowincr) (wholenump colincr))
1611 ;; Insertion of rows and/or columns. Run the loop backwards.
1612 (let ((disty (1- ses--numrows))
1613 (distx (1- ses--numcols))
1614 myrow mycol)
1615 (dotimes-with-progress-reporter
1616 (row (- ses--numrows minrow)) "Relocating variables..."
1617 (setq myrow (- disty row))
1618 (dotimes (col (- ses--numcols mincol))
1619 (setq mycol (- distx col)
1620 xrow (- myrow rowincr)
1621 xcol (- mycol colincr))
1622 (if (or (< xrow minrow) (< xcol mincol))
1623 ;; Newly-inserted value.
1624 (setq oldval nil)
1625 ;; Transfer old value.
1626 (setq oldval (ses-cell-value xrow xcol)))
1627 (ses-set-cell myrow mycol 'value oldval)))
1628 t)) ; Make testcover happy by returning non-nil here.
1630 (error "ROWINCR and COLINCR must have the same sign"))))
1631 ;; Reconstruct reference lists for cells that contain ses-ranges that have
1632 ;; changed size.
1633 (when reform
1634 (message "Fixing ses-ranges...")
1635 (let (row col)
1636 (setq ses-start-time (float-time))
1637 (while reform
1638 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1639 (setq row (caar reform)
1640 col (cdar reform)
1641 reform (cdr reform))
1642 (ses-cell-set-formula row col (ses-cell-formula row col))))
1643 (message nil))))
1646 ;;----------------------------------------------------------------------------
1647 ;; Undo control
1648 ;;----------------------------------------------------------------------------
1650 (defun ses-begin-change ()
1651 "For undo, remember point before we start changing hidden stuff."
1652 (let ((inhibit-read-only t))
1653 (insert-and-inherit "X")
1654 (delete-region (1- (point)) (point))))
1656 (defun ses-set-with-undo (sym newval)
1657 "Like set, but undoable. Result is t if value has changed."
1658 ;; We try to avoid adding redundant entries to the undo list, but this is
1659 ;; unavoidable for strings because equal ignores text properties and there's
1660 ;; no easy way to get the whole property list to see if it's different!
1661 (unless (and (boundp sym)
1662 (equal (symbol-value sym) newval)
1663 (not (stringp newval)))
1664 (push (if (boundp sym)
1665 `(apply ses-set-with-undo ,sym ,(symbol-value sym))
1666 `(apply ses-unset-with-undo ,sym))
1667 buffer-undo-list)
1668 (set sym newval)
1671 (defun ses-unset-with-undo (sym)
1672 "Set SYM to be unbound. This is undoable."
1673 (when (1value (boundp sym)) ; Always bound, except after a programming error.
1674 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
1675 (makunbound sym)))
1677 (defun ses-aset-with-undo (array idx newval)
1678 "Like `aset', but undoable.
1679 Result is t if element has changed."
1680 (unless (equal (aref array idx) newval)
1681 (push `(apply ses-aset-with-undo ,array ,idx
1682 ,(aref array idx)) buffer-undo-list)
1683 (aset array idx newval)
1687 ;;----------------------------------------------------------------------------
1688 ;; Startup for major mode
1689 ;;----------------------------------------------------------------------------
1691 (defun ses-load ()
1692 "Parse the current buffer and set up buffer-local variables.
1693 Does not execute cell formulas or print functions."
1694 (widen)
1695 ;; Read our global parameters, which should be a 3-element list.
1696 (goto-char (point-max))
1697 (search-backward ";; Local Variables:\n" nil t)
1698 (backward-list 1)
1699 (setq ses--params-marker (point-marker))
1700 (let ((params (condition-case nil (read (current-buffer)) (error nil))))
1701 (or (and (= (safe-length params) 3)
1702 (numberp (car params))
1703 (numberp (cadr params))
1704 (>= (cadr params) 0)
1705 (numberp (nth 2 params))
1706 (> (nth 2 params) 0))
1707 (error "Invalid SES file"))
1708 (setq ses--file-format (car params)
1709 ses--numrows (cadr params)
1710 ses--numcols (nth 2 params))
1711 (when (= ses--file-format 1)
1712 (let (buffer-undo-list) ; This is not undoable.
1713 (ses-goto-data 'ses--header-row)
1714 (insert "(ses-header-row 0)\n")
1715 (ses-set-parameter 'ses--file-format 2)
1716 (message "Upgrading from SES-1 file format")))
1717 (or (= ses--file-format 2)
1718 (error "This file needs a newer version of the SES library code"))
1719 ;; Initialize cell array.
1720 (setq ses--cells (make-vector ses--numrows nil))
1721 (dotimes (row ses--numrows)
1722 (aset ses--cells row (make-vector ses--numcols nil))))
1723 ;; Skip over print area, which we assume is correct.
1724 (goto-char (point-min))
1725 (forward-line ses--numrows)
1726 (or (looking-at ses-print-data-boundary)
1727 (error "Missing marker between print and data areas"))
1728 (forward-char 1)
1729 (setq ses--data-marker (point-marker))
1730 (forward-char (1- (length ses-print-data-boundary)))
1731 ;; Initialize printer and symbol lists.
1732 (mapc 'ses-printer-record ses-standard-printer-functions)
1733 (setq ses--symbolic-formulas nil)
1734 ;; Load cell definitions.
1735 (dotimes (row ses--numrows)
1736 (dotimes (col ses--numcols)
1737 (let* ((x (read (current-buffer)))
1738 (sym (car-safe (cdr-safe x))))
1739 (or (and (looking-at "\n")
1740 (eq (car-safe x) 'ses-cell)
1741 (ses-create-cell-variable sym row col))
1742 (error "Cell-def error"))
1743 (eval x)))
1744 (or (looking-at "\n\n")
1745 (error "Missing blank line between rows")))
1746 ;; Load global parameters.
1747 (let ((widths (read (current-buffer)))
1748 (n1 (char-after (point)))
1749 (printers (read (current-buffer)))
1750 (n2 (char-after (point)))
1751 (def-printer (read (current-buffer)))
1752 (n3 (char-after (point)))
1753 (head-row (read (current-buffer)))
1754 (n4 (char-after (point))))
1755 (or (and (eq (car-safe widths) 'ses-column-widths)
1756 (= n1 ?\n)
1757 (eq (car-safe printers) 'ses-column-printers)
1758 (= n2 ?\n)
1759 (eq (car-safe def-printer) 'ses-default-printer)
1760 (= n3 ?\n)
1761 (eq (car-safe head-row) 'ses-header-row)
1762 (= n4 ?\n))
1763 (error "Invalid SES global parameters"))
1764 (1value (eval widths))
1765 (1value (eval def-printer))
1766 (1value (eval printers))
1767 (1value (eval head-row)))
1768 ;; Should be back at global-params.
1769 (forward-char 1)
1770 (or (looking-at (replace-regexp-in-string "1" "[0-9]+"
1771 ses-initial-global-parameters))
1772 (error "Problem with column-defs or global-params"))
1773 ;; Check for overall newline count in definitions area.
1774 (forward-line 3)
1775 (let ((start (point)))
1776 (ses-goto-data 'ses--numrows)
1777 (or (= (point) start)
1778 (error "Extraneous newlines someplace?"))))
1780 (defun ses-setup ()
1781 "Set up for display of only the printed cell values.
1783 Narrows the buffer to show only the print area. Gives it `read-only' and
1784 `intangible' properties. Sets up highlighting for current cell."
1785 (interactive)
1786 (let ((end (point-min))
1787 (inhibit-read-only t)
1788 (inhibit-point-motion-hooks t)
1789 (was-modified (buffer-modified-p))
1790 pos sym)
1791 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1792 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1793 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1794 ;; The print area is read-only (except for our special commands) and uses a
1795 ;; special keymap.
1796 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1797 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1798 ;; For the beginning of the buffer, we want the read-only and keymap
1799 ;; attributes to be inherited from the first character.
1800 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1801 ;; Create intangible properties, which also indicate which cell the text
1802 ;; came from.
1803 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1804 (dotimes (col ses--numcols)
1805 (setq pos end
1806 sym (ses-cell-symbol row col))
1807 ;; Include skipped cells following this one.
1808 (while (and (< col (1- ses--numcols))
1809 (eq (ses-cell-value row (1+ col)) '*skip*))
1810 (setq end (+ end (ses-col-width col) 1)
1811 col (1+ col)))
1812 (setq end (save-excursion
1813 (goto-char pos)
1814 (move-to-column (+ (current-column) (- end pos)
1815 (ses-col-width col)))
1816 (if (eolp)
1817 (+ end (ses-col-width col) 1)
1818 (forward-char)
1819 (point))))
1820 (put-text-property pos end 'intangible sym)))
1821 ;; Adding these properties did not actually alter the text.
1822 (unless was-modified
1823 (restore-buffer-modified-p nil)
1824 (buffer-disable-undo)
1825 (buffer-enable-undo)))
1826 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1827 ;; because column A must be at least 1 column wide.
1828 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1829 (overlay-put ses--curcell-overlay 'face 'underline))
1831 (defun ses-cleanup ()
1832 "Cleanup when changing a buffer from SES mode to something else.
1833 Delete overlays, remove special text properties."
1834 (widen)
1835 (let ((inhibit-read-only t)
1836 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1837 ;; user "the file is modified, do you really want to make modifications
1838 ;; to this buffer", where the "modifications" refer to the irrelevant
1839 ;; set-text-properties below.
1840 (buffer-file-name nil)
1841 (was-modified (buffer-modified-p)))
1842 ;; Delete read-only, keymap, and intangible properties.
1843 (set-text-properties (point-min) (point-max) nil)
1844 ;; Delete overlay.
1845 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1846 (unless was-modified
1847 (restore-buffer-modified-p nil))))
1849 ;;;###autoload
1850 (defun ses-mode ()
1851 "Major mode for Simple Emacs Spreadsheet.
1852 See \"ses-example.ses\" (in `data-directory') for more info.
1854 Key definitions:
1855 \\{ses-mode-map}
1856 These key definitions are active only in the print area (the visible part):
1857 \\{ses-mode-print-map}
1858 These are active only in the minibuffer, when entering or editing a formula:
1859 \\{ses-mode-edit-map}"
1860 (interactive)
1861 (unless (and (boundp 'ses--deferred-narrow)
1862 (eq ses--deferred-narrow 'ses-mode))
1863 (kill-all-local-variables)
1864 (ses-set-localvars)
1865 (setq major-mode 'ses-mode
1866 mode-name "SES"
1867 next-line-add-newlines nil
1868 truncate-lines t
1869 ;; SES deliberately puts lots of trailing whitespace in its buffer.
1870 show-trailing-whitespace nil
1871 ;; Cell ranges do not work reasonably without this.
1872 transient-mark-mode t
1873 ;; Not to use tab characters for safe (tabs may do bad for column
1874 ;; calculation).
1875 indent-tabs-mode nil)
1876 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1877 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1878 (setq header-line-format '(:eval (progn
1879 (when (/= (window-hscroll)
1880 ses--header-hscroll)
1881 ;; Reset ses--header-hscroll first,
1882 ;; to avoid recursion problems when
1883 ;; debugging ses-create-header-string
1884 (setq ses--header-hscroll
1885 (window-hscroll))
1886 (ses-create-header-string))
1887 ses--header-string)))
1888 (let ((was-empty (zerop (buffer-size)))
1889 (was-modified (buffer-modified-p)))
1890 (save-excursion
1891 (if was-empty
1892 ;; Initialize buffer to contain one cell, for now.
1893 (insert ses-initial-file-contents))
1894 (ses-load)
1895 (ses-setup))
1896 (when was-empty
1897 (unless (equal ses-initial-default-printer
1898 (1value ses--default-printer))
1899 (1value (ses-read-default-printer ses-initial-default-printer)))
1900 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1901 (1value (ses-set-column-width 0 ses-initial-column-width)))
1902 (ses-set-curcell)
1903 (if (> (car ses-initial-size) (1value ses--numrows))
1904 (1value (ses-insert-row (1- (car ses-initial-size)))))
1905 (if (> (cdr ses-initial-size) (1value ses--numcols))
1906 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1907 (ses-write-cells)
1908 (restore-buffer-modified-p was-modified)
1909 (buffer-disable-undo)
1910 (buffer-enable-undo)
1911 (goto-char (point-min))))
1912 (use-local-map ses-mode-map)
1913 ;; Set the deferred narrowing flag (we can't narrow until after
1914 ;; after-find-file completes). If .ses is on the auto-load alist and the
1915 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
1916 ;; special flag to detect this (will be reset by ses-command-hook). For
1917 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
1918 ;; so use an idle timer to make sure.
1919 (setq ses--deferred-narrow 'ses-mode)
1920 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1921 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1922 (run-mode-hooks 'ses-mode-hook)))
1924 (put 'ses-mode 'mode-class 'special)
1926 (defun ses-command-hook ()
1927 "Invoked from `post-command-hook'. If point has moved to a different cell,
1928 moves the underlining overlay. Performs any recalculations or cell-data
1929 writes that have been deferred. If buffer-narrowing has been deferred,
1930 narrows the buffer now."
1931 (condition-case err
1932 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
1933 (when ses--deferred-recalc
1934 ;; We reset the deferred list before starting on the recalc --- in
1935 ;; case of error, we don't want to retry the recalc after every
1936 ;; keystroke!
1937 (ses-initialize-Dijkstra-attempt)
1938 (let ((old ses--deferred-recalc))
1939 (setq ses--deferred-recalc nil)
1940 (ses-update-cells old)))
1941 (when ses--deferred-write
1942 ;; We don't reset the deferred list before starting --- the most
1943 ;; likely error is keyboard-quit, and we do want to keep trying these
1944 ;; writes after a quit.
1945 (ses-write-cells)
1946 (push '(apply ses-widen) buffer-undo-list))
1947 (when ses--deferred-narrow
1948 ;; We're not allowed to narrow the buffer until after-find-file has
1949 ;; read the local variables at the end of the file. Now it's safe to
1950 ;; do the narrowing.
1951 (narrow-to-region (point-min) ses--data-marker)
1952 (setq ses--deferred-narrow nil))
1953 ;; Update the mode line.
1954 (let ((oldcell ses--curcell))
1955 (ses-set-curcell)
1956 (unless (eq ses--curcell oldcell)
1957 (cond
1958 ((not ses--curcell)
1959 (setq mode-line-process nil))
1960 ((atom ses--curcell)
1961 (setq mode-line-process (list " cell "
1962 (symbol-name ses--curcell))))
1964 (setq mode-line-process (list " range "
1965 (symbol-name (car ses--curcell))
1967 (symbol-name (cdr ses--curcell))))))
1968 (force-mode-line-update)))
1969 ;; Use underline overlay for single-cells only, turn off otherwise.
1970 (if (listp ses--curcell)
1971 (move-overlay ses--curcell-overlay 2 2)
1972 (let ((next (next-single-property-change (point) 'intangible)))
1973 (move-overlay ses--curcell-overlay (point) (1- next))))
1974 (when (not (pos-visible-in-window-p))
1975 ;; Scrolling will happen later.
1976 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1977 (setq ses--curcell t)))
1978 ;; Prevent errors in this post-command-hook from silently erasing the hook!
1979 (error
1980 (unless executing-kbd-macro
1981 (ding))
1982 (message "%s" (error-message-string err))))
1983 nil) ; Make coverage-tester happy.
1985 (defun ses-create-header-string ()
1986 "Set up `ses--header-string' as the buffer's header line.
1987 Based on the current set of columns and `window-hscroll' position."
1988 (let ((totwidth (- (window-hscroll)))
1989 result width x)
1990 ;; Leave room for the left-side fringe and scrollbar.
1991 (push (propertize " " 'display '((space :align-to 0))) result)
1992 (dotimes (col ses--numcols)
1993 (setq width (ses-col-width col)
1994 totwidth (+ totwidth width 1))
1995 (if (= totwidth 1)
1996 ;; Scrolled so intercolumn space is leftmost.
1997 (push " " result))
1998 (when (> totwidth 1)
1999 (if (> ses--header-row 0)
2000 (save-excursion
2001 (ses-goto-print (1- ses--header-row) col)
2002 (setq x (buffer-substring-no-properties (point)
2003 (+ (point) width)))
2004 ;; Strip trailing space.
2005 (if (string-match "[ \t]+\\'" x)
2006 (setq x (substring x 0 (match-beginning 0))))
2007 ;; Cut off excess text.
2008 (if (>= (length x) totwidth)
2009 (setq x (substring x 0 (- totwidth -1)))))
2010 (setq x (ses-column-letter col)))
2011 (push (propertize x 'face ses-box-prop) result)
2012 (push (propertize "."
2013 'display `((space :align-to ,(1- totwidth)))
2014 'face ses-box-prop)
2015 result)
2016 ;; Allow the following space to be squished to make room for the 3-D box
2017 ;; Coverage test ignores properties, thinks this is always a space!
2018 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2019 result)))
2020 (if (> ses--header-row 0)
2021 (push (propertize (format " [row %d]" ses--header-row)
2022 'display '((height (- 1))))
2023 result))
2024 (setq ses--header-string (apply 'concat (nreverse result)))))
2027 ;;----------------------------------------------------------------------------
2028 ;; Redisplay and recalculation
2029 ;;----------------------------------------------------------------------------
2031 (defun ses-jump (sym)
2032 "Move point to cell SYM."
2033 (interactive "SJump to cell: ")
2034 (let ((rowcol (ses-sym-rowcol sym)))
2035 (or rowcol (error "Invalid cell name"))
2036 (if (eq (symbol-value sym) '*skip*)
2037 (error "Cell is covered by preceding cell"))
2038 (ses-goto-print (car rowcol) (cdr rowcol))))
2040 (defun ses-jump-safe (cell)
2041 "Like `ses-jump', but no error if invalid cell."
2042 (condition-case nil
2043 (ses-jump cell)
2044 (error)))
2046 (defun ses-reprint-all (&optional nonarrow)
2047 "Recreate the display area. Calls all printer functions. Narrows to
2048 print area if NONARROW is nil."
2049 (interactive "*P")
2050 (widen)
2051 (unless nonarrow
2052 (setq ses--deferred-narrow t))
2053 (let ((startcell (get-text-property (point) 'intangible))
2054 (inhibit-read-only t))
2055 (ses-begin-change)
2056 (goto-char (point-min))
2057 (search-forward ses-print-data-boundary)
2058 (backward-char (length ses-print-data-boundary))
2059 (delete-region (point-min) (point))
2060 ;; Insert all blank lines before printing anything, so ses-print-cell can
2061 ;; find the data area when inserting or deleting *skip* values for cells.
2062 (dotimes (row ses--numrows)
2063 (insert-and-inherit ses--blank-line))
2064 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2065 (if (eq (ses-cell-value row 0) '*skip*)
2066 ;; Column deletion left a dangling skip.
2067 (ses-set-cell row 0 'value nil))
2068 (dotimes (col ses--numcols)
2069 (ses-print-cell row col))
2070 (beginning-of-line 2))
2071 (ses-jump-safe startcell)))
2073 (defun ses-initialize-Dijkstra-attempt ()
2074 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2075 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2077 (defun ses-recalculate-cell ()
2078 "Recalculate and reprint the current cell or range.
2080 For an individual cell, shows the error if the formula or printer
2081 signals one, or otherwise shows the cell's complete value. For a range, the
2082 cells are recalculated in \"natural\" order, so cells that other cells refer
2083 to are recalculated first."
2084 (interactive "*")
2085 (ses-check-curcell 'range)
2086 (ses-begin-change)
2087 (ses-initialize-Dijkstra-attempt)
2088 (let (sig cur-rowcol)
2089 (setq ses-start-time (float-time))
2090 (if (atom ses--curcell)
2091 (when
2092 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2093 sig (progn
2094 (ses-cell-property-set :ses-Dijkstra-attempt
2095 (cons ses--Dijkstra-attempt-nb 0)
2096 (car cur-rowcol) (cdr cur-rowcol) )
2097 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2098 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2099 (cdr cur-rowcol)))))
2100 ;; First, recalculate all cells that don't refer to other cells and
2101 ;; produce a list of cells with references.
2102 (ses-dorange ses--curcell
2103 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
2104 (condition-case nil
2105 (progn
2106 ;; The t causes an error if the cell has references. If no
2107 ;; references, the t will be the result value.
2108 (1value (ses-formula-references (ses-cell-formula row col) t))
2109 (ses-cell-property-set :ses-Dijkstra-attempt
2110 (cons ses--Dijkstra-attempt-nb 0)
2111 row col)
2112 (when (setq sig (ses-calculate-cell row col t))
2113 (nconc sig (list (ses-cell-symbol row col)))))
2114 (wrong-type-argument
2115 ;; The formula contains a reference.
2116 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
2117 ;; Do the update now, so we can force recalculation.
2118 (let ((x ses--deferred-recalc))
2119 (setq ses--deferred-recalc nil)
2120 (condition-case hold
2121 (ses-update-cells x t)
2122 (error (setq sig hold))))
2123 (cond
2124 (sig
2125 (message "%s" (error-message-string sig)))
2126 ((consp ses--curcell)
2127 (message " "))
2129 (princ (symbol-value ses--curcell))))))
2131 (defun ses-recalculate-all ()
2132 "Recalculate and reprint all cells."
2133 (interactive "*")
2134 (let ((startcell (get-text-property (point) 'intangible))
2135 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2136 (1- ses--numcols)))))
2137 (ses-recalculate-cell)
2138 (ses-jump-safe startcell)))
2140 (defun ses-truncate-cell ()
2141 "Reprint current cell, but without spillover into any following blank cells."
2142 (interactive "*")
2143 (ses-check-curcell)
2144 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2145 (row (car rowcol))
2146 (col (cdr rowcol)))
2147 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
2148 (eq (ses-cell-value row (1+ col)) '*skip*))
2149 ;; This cell has spill-over. We'll momentarily pretend the following cell
2150 ;; has a `t' in it.
2151 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
2152 (ses-print-cell row col)))
2153 ;; Now remove the *skip*. ses-print-cell is always nil here.
2154 (ses-set-cell row (1+ col) 'value nil)
2155 (1value (ses-print-cell row (1+ col))))))
2157 (defun ses-reconstruct-all ()
2158 "Reconstruct buffer based on cell data stored in Emacs variables."
2159 (interactive "*")
2160 (ses-begin-change)
2161 ;;Reconstruct reference lists.
2162 (let (x yrow ycol)
2163 ;;Delete old reference lists
2164 (dotimes-with-progress-reporter
2165 (row ses--numrows) "Deleting references..."
2166 (dotimes (col ses--numcols)
2167 (ses-set-cell row col 'references nil)))
2168 ;;Create new reference lists
2169 (dotimes-with-progress-reporter
2170 (row ses--numrows) "Computing references..."
2171 (dotimes (col ses--numcols)
2172 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2173 (setq x (ses-sym-rowcol ref)
2174 yrow (car x)
2175 ycol (cdr x))
2176 (ses-set-cell yrow ycol 'references
2177 (cons (ses-cell-symbol row col)
2178 (ses-cell-references yrow ycol)))))))
2179 ;; Delete everything and reconstruct basic data area.
2180 (ses-widen)
2181 (let ((inhibit-read-only t))
2182 (goto-char (point-max))
2183 (if (search-backward ";; Local Variables:\n" nil t)
2184 (delete-region (point-min) (point))
2185 ;; Buffer is quite screwed up --- can't even save the user-specified
2186 ;; locals.
2187 (delete-region (point-min) (point-max))
2188 (insert ses-initial-file-trailer)
2189 (goto-char (point-min)))
2190 ;; Create a blank display area.
2191 (dotimes (row ses--numrows)
2192 (insert ses--blank-line))
2193 (insert ses-print-data-boundary)
2194 (backward-char (1- (length ses-print-data-boundary)))
2195 (setq ses--data-marker (point-marker))
2196 (forward-char (1- (length ses-print-data-boundary)))
2197 ;; Placeholders for cell data.
2198 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2199 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
2200 (insert "\n\n\n\n")
2201 (insert ses-initial-global-parameters)
2202 (backward-char (1- (length ses-initial-global-parameters)))
2203 (setq ses--params-marker (point-marker))
2204 (forward-char (1- (length ses-initial-global-parameters))))
2205 (ses-set-parameter 'ses--col-widths ses--col-widths)
2206 (ses-set-parameter 'ses--col-printers ses--col-printers)
2207 (ses-set-parameter 'ses--default-printer ses--default-printer)
2208 (ses-set-parameter 'ses--header-row ses--header-row)
2209 (ses-set-parameter 'ses--numrows ses--numrows)
2210 (ses-set-parameter 'ses--numcols ses--numcols)
2211 ;;Keep our old narrowing
2212 (ses-setup)
2213 (ses-recalculate-all)
2214 (goto-char (point-min)))
2217 ;;----------------------------------------------------------------------------
2218 ;; Input of cell formulas
2219 ;;----------------------------------------------------------------------------
2221 (defun ses-edit-cell (row col newval)
2222 "Display current cell contents in minibuffer, for editing. Returns nil if
2223 cell formula was unsafe and user declined confirmation."
2224 (interactive
2225 (progn
2226 (barf-if-buffer-read-only)
2227 (ses-check-curcell)
2228 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2229 (row (car rowcol))
2230 (col (cdr rowcol))
2231 (formula (ses-cell-formula row col))
2232 initial)
2233 (if (eq (car-safe formula) 'ses-safe-formula)
2234 (setq formula (cadr formula)))
2235 (if (eq (car-safe formula) 'quote)
2236 (setq initial (format "'%S" (cadr formula)))
2237 (setq initial (prin1-to-string formula)))
2238 (if (stringp formula)
2239 ;; Position cursor inside close-quote.
2240 (setq initial (cons initial (length initial))))
2241 (list row col
2242 (read-from-minibuffer (format "Cell %s: " ses--curcell)
2243 initial
2244 ses-mode-edit-map
2245 t ; Convert to Lisp object.
2246 'ses-read-cell-history)))))
2247 (when (ses-warn-unsafe newval 'unsafep)
2248 (ses-begin-change)
2249 (ses-cell-set-formula row col newval)
2252 (defun ses-read-cell (row col newval)
2253 "Self-insert for initial character of cell function."
2254 (interactive
2255 (let* ((initial (this-command-keys))
2256 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2257 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
2258 (barf-if-buffer-read-only)
2259 (list (car rowcol)
2260 (cdr rowcol)
2261 (read-from-minibuffer
2262 (format "Cell %s: " ses--curcell)
2263 (cons (if (equal initial "\"") "\"\""
2264 (if (equal initial "(") "()" initial)) 2)
2265 ses-mode-edit-map
2266 t ; Convert to Lisp object.
2267 'ses-read-cell-history
2268 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2269 (cadr curval)
2270 curval))))))
2271 (when (ses-edit-cell row col newval)
2272 (ses-command-hook) ; Update cell widths before movement.
2273 (dolist (x ses-after-entry-functions)
2274 (funcall x 1))))
2276 (defun ses-read-symbol (row col symb)
2277 "Self-insert for a symbol as a cell formula. The set of all symbols that
2278 have been used as formulas in this spreadsheet is available for completions."
2279 (interactive
2280 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2281 newval)
2282 (barf-if-buffer-read-only)
2283 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2284 ses--symbolic-formulas))
2285 (list (car rowcol)
2286 (cdr rowcol)
2287 (if (string= newval "")
2288 nil ; Don't create zero-length symbols!
2289 (list 'quote (intern newval))))))
2290 (when (ses-edit-cell row col symb)
2291 (ses-command-hook) ; Update cell widths before movement.
2292 (dolist (x ses-after-entry-functions)
2293 (funcall x 1))))
2295 (defun ses-clear-cell-forward (count)
2296 "Delete formula and printer for current cell and then move to next cell.
2297 With prefix, deletes several cells."
2298 (interactive "*p")
2299 (if (< count 0)
2300 (1value (ses-clear-cell-backward (- count)))
2301 (ses-check-curcell)
2302 (ses-begin-change)
2303 (dotimes (x count)
2304 (ses-set-curcell)
2305 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2306 (or rowcol (signal 'end-of-buffer nil))
2307 (ses-clear-cell (car rowcol) (cdr rowcol)))
2308 (forward-char 1))))
2310 (defun ses-clear-cell-backward (count)
2311 "Move to previous cell and then delete it. With prefix, deletes several
2312 cells."
2313 (interactive "*p")
2314 (if (< count 0)
2315 (1value (ses-clear-cell-forward (- count)))
2316 (ses-check-curcell 'end)
2317 (ses-begin-change)
2318 (dotimes (x count)
2319 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
2320 (ses-set-curcell)
2321 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2322 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2325 ;;----------------------------------------------------------------------------
2326 ;; Input of cell-printer functions
2327 ;;----------------------------------------------------------------------------
2329 (defun ses-read-printer (prompt default)
2330 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
2331 PROMPT should end with \": \". Result is t if operation was canceled."
2332 (barf-if-buffer-read-only)
2333 (if (eq default t)
2334 (setq default "")
2335 (setq prompt (format "%s [currently %S]: "
2336 (substring prompt 0 -2)
2337 default)))
2338 (let ((new (read-from-minibuffer prompt
2339 nil ; Initial contents.
2340 ses-mode-edit-map
2341 t ; Evaluate the result.
2342 'ses-read-printer-history
2343 (prin1-to-string default))))
2344 (if (equal new default)
2345 ;; User changed mind, decided not to change printer.
2346 (setq new t)
2347 (ses-printer-validate new)
2348 (or (not new)
2349 (stringp new)
2350 (stringp (car-safe new))
2351 (ses-warn-unsafe new 'unsafep-function)
2352 (setq new t)))
2353 new))
2355 (defun ses-read-cell-printer (newval)
2356 "Set the printer function for the current cell or range.
2358 A printer function is either a string (a format control-string with one
2359 %-sequence -- result from format will be right-justified), or a list of one
2360 string (result from format will be left-justified), or a lambda-expression of
2361 one argument, or a symbol that names a function of one argument. In the
2362 latter two cases, the function's result should be either a string (will be
2363 right-justified) or a list of one string (will be left-justified)."
2364 (interactive
2365 (let ((default t)
2367 (ses-check-curcell 'range)
2368 ;;Default is none if not all cells in range have same printer
2369 (catch 'ses-read-cell-printer
2370 (ses-dorange ses--curcell
2371 (setq x (ses-cell-printer row col))
2372 (if (eq (car-safe x) 'ses-safe-printer)
2373 (setq x (cadr x)))
2374 (if (eq default t)
2375 (setq default x)
2376 (unless (equal default x)
2377 ;;Range contains differing printer functions
2378 (setq default t)
2379 (throw 'ses-read-cell-printer t)))))
2380 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2381 default))))
2382 (unless (eq newval t)
2383 (ses-begin-change)
2384 (ses-dorange ses--curcell
2385 (ses-set-cell row col 'printer newval)
2386 (ses-print-cell row col))))
2388 (defun ses-read-column-printer (col newval)
2389 "Set the printer function for the current column.
2390 See `ses-read-cell-printer' for input forms."
2391 (interactive
2392 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2393 (ses-check-curcell)
2394 (list col (ses-read-printer (format "Column %s printer: "
2395 (ses-column-letter col))
2396 (ses-col-printer col)))))
2398 (unless (eq newval t)
2399 (ses-begin-change)
2400 (ses-set-parameter 'ses--col-printers newval col)
2401 (save-excursion
2402 (dotimes (row ses--numrows)
2403 (ses-print-cell row col)))))
2405 (defun ses-read-default-printer (newval)
2406 "Set the default printer function for cells that have no other.
2407 See `ses-read-cell-printer' for input forms."
2408 (interactive
2409 (list (ses-read-printer "Default printer: " ses--default-printer)))
2410 (unless (eq newval t)
2411 (ses-begin-change)
2412 (ses-set-parameter 'ses--default-printer newval)
2413 (ses-reprint-all t)))
2416 ;;----------------------------------------------------------------------------
2417 ;; Spreadsheet size adjustments
2418 ;;----------------------------------------------------------------------------
2420 (defun ses-insert-row (count)
2421 "Insert a new row before the current one.
2422 With prefix, insert COUNT rows before current one."
2423 (interactive "*p")
2424 (ses-check-curcell 'end)
2425 (or (> count 0) (signal 'args-out-of-range nil))
2426 (ses-begin-change)
2427 (let ((inhibit-quit t)
2428 (inhibit-read-only t)
2429 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2430 newrow)
2431 ;;Create a new set of cell-variables
2432 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2433 0 (1- ses--numcols))
2434 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2435 ;;Insert each row
2436 (ses-goto-print row 0)
2437 (dotimes-with-progress-reporter (x count) "Inserting row..."
2438 ;;Create a row of empty cells. The `symbol' fields will be set by
2439 ;;the call to ses-relocate-all.
2440 (setq newrow (make-vector ses--numcols nil))
2441 (dotimes (col ses--numcols)
2442 (aset newrow col (ses-make-cell)))
2443 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2444 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2445 (insert ses--blank-line))
2446 ;;Insert empty lines in cell data area (will be replaced by
2447 ;;ses-relocate-all)
2448 (ses-goto-data row 0)
2449 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2450 (ses-relocate-all row 0 count 0)
2451 ;;If any cell printers insert constant text, insert that text
2452 ;;into the line.
2453 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2454 (global (ses-call-printer ses--default-printer)))
2455 (if (or (> (length cols) 0) (> (length global) 0))
2456 (dotimes (x count)
2457 (dotimes (col ses--numcols)
2458 ;;These cells are always nil, only constant formatting printed
2459 (1value (ses-print-cell (+ x row) col))))))
2460 (when (> ses--header-row row)
2461 ;;Inserting before header
2462 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2463 (ses-reset-header-string)))
2464 ;;Reconstruct text attributes
2465 (ses-setup)
2466 ;;Prepare for undo
2467 (push '(apply ses-widen) buffer-undo-list)
2468 ;;Return to current cell
2469 (if ses--curcell
2470 (ses-jump-safe ses--curcell)
2471 (ses-goto-print (1- ses--numrows) 0)))
2473 (defun ses-delete-row (count)
2474 "Delete the current row.
2475 With prefix, deletes COUNT rows starting from the current one."
2476 (interactive "*p")
2477 (ses-check-curcell)
2478 (or (> count 0) (signal 'args-out-of-range nil))
2479 (let ((inhibit-quit t)
2480 (inhibit-read-only t)
2481 (row (car (ses-sym-rowcol ses--curcell))))
2482 (setq count (min count (- ses--numrows row)))
2483 (ses-begin-change)
2484 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2485 ;;Delete lines from print area
2486 (ses-goto-print row 0)
2487 (ses-delete-line count)
2488 ;;Delete lines from cell data area
2489 (ses-goto-data row 0)
2490 (ses-delete-line (* count (1+ ses--numcols)))
2491 ;;Relocate variables and formulas
2492 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2493 (ses-relocate-all row 0 (- count) 0)
2494 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2495 0 (1- ses--numcols))
2496 (when (> ses--header-row row)
2497 (if (<= ses--header-row (+ row count))
2498 ;;Deleting the header row
2499 (ses-set-parameter 'ses--header-row 0)
2500 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2501 (ses-reset-header-string)))
2502 ;;Reconstruct attributes
2503 (ses-setup)
2504 ;;Prepare for undo
2505 (push '(apply ses-widen) buffer-undo-list)
2506 (ses-jump-safe ses--curcell))
2508 (defun ses-insert-column (count &optional col width printer)
2509 "Insert a new column before COL (default is the current one).
2510 With prefix, insert COUNT columns before current one.
2511 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2512 \(otherwise they're taken from the current column)."
2513 (interactive "*p")
2514 (ses-check-curcell)
2515 (or (> count 0) (signal 'args-out-of-range nil))
2516 (or col
2517 (setq col (cdr (ses-sym-rowcol ses--curcell))
2518 width (ses-col-width col)
2519 printer (ses-col-printer col)))
2520 (ses-begin-change)
2521 (let ((inhibit-quit t)
2522 (inhibit-read-only t)
2523 (widths ses--col-widths)
2524 (printers ses--col-printers)
2525 has-skip)
2526 ;;Create a new set of cell-variables
2527 (ses-create-cell-variable-range 0 (1- ses--numrows)
2528 ses--numcols (+ ses--numcols count -1))
2529 ;;Insert each column.
2530 (dotimes-with-progress-reporter (x count) "Inserting column..."
2531 ;;Create a column of empty cells. The `symbol' fields will be set by
2532 ;;the call to ses-relocate-all.
2533 (ses-adjust-print-width col (1+ width))
2534 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2535 (dotimes (row ses--numrows)
2536 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2537 ;;Inserting in the middle of a spill-over
2538 (setq has-skip t))
2539 (ses-aset-with-undo ses--cells row
2540 (ses-vector-insert (aref ses--cells row)
2541 col (ses-make-cell)))
2542 ;;Insert empty lines in cell data area (will be replaced by
2543 ;;ses-relocate-all)
2544 (ses-goto-data row col)
2545 (insert ?\n))
2546 ;; Insert column width and printer.
2547 (setq widths (ses-vector-insert widths col width)
2548 printers (ses-vector-insert printers col printer)))
2549 (ses-set-parameter 'ses--col-widths widths)
2550 (ses-set-parameter 'ses--col-printers printers)
2551 (ses-reset-header-string)
2552 (ses-relocate-all 0 col 0 count)
2553 (if has-skip
2554 (ses-reprint-all t)
2555 (when (or (> (length (ses-call-printer printer)) 0)
2556 (> (length (ses-call-printer ses--default-printer)) 0))
2557 ;; Either column printer or global printer inserts some constant text.
2558 ;; Reprint the new columns to insert that text.
2559 (dotimes (x ses--numrows)
2560 (dotimes (y count)
2561 ;; Always nil here --- this is a blank column.
2562 (1value (ses-print-cell-new-width x (+ y col))))))
2563 (ses-setup)))
2564 (ses-jump-safe ses--curcell))
2566 (defun ses-delete-column (count)
2567 "Delete the current column.
2568 With prefix, deletes COUNT columns starting from the current one."
2569 (interactive "*p")
2570 (ses-check-curcell)
2571 (or (> count 0) (signal 'args-out-of-range nil))
2572 (let ((inhibit-quit t)
2573 (inhibit-read-only t)
2574 (rowcol (ses-sym-rowcol ses--curcell))
2575 (width 0)
2576 col origrow has-skip)
2577 (setq origrow (car rowcol)
2578 col (cdr rowcol)
2579 count (min count (- ses--numcols col)))
2580 (if (= count ses--numcols)
2581 (error "Can't delete all columns!"))
2582 ;;Determine width of column(s) being deleted
2583 (dotimes (x count)
2584 (setq width (+ width (ses-col-width (+ col x)) 1)))
2585 (ses-begin-change)
2586 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2587 (ses-adjust-print-width col (- width))
2588 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2589 ;;Delete lines from cell data area
2590 (ses-goto-data row col)
2591 (ses-delete-line count)
2592 ;;Delete cells. Check if deletion area begins or ends with a skip.
2593 (if (or (eq (ses-cell-value row col) '*skip*)
2594 (and (< col ses--numcols)
2595 (eq (ses-cell-value row (+ col count)) '*skip*)))
2596 (setq has-skip t))
2597 (ses-aset-with-undo ses--cells row
2598 (ses-vector-delete (aref ses--cells row) col count)))
2599 ;;Update globals
2600 (ses-set-parameter 'ses--col-widths
2601 (ses-vector-delete ses--col-widths col count))
2602 (ses-set-parameter 'ses--col-printers
2603 (ses-vector-delete ses--col-printers col count))
2604 (ses-reset-header-string)
2605 ;;Relocate variables and formulas
2606 (ses-relocate-all 0 col 0 (- count))
2607 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2608 ses--numcols (+ ses--numcols count -1))
2609 (if has-skip
2610 (ses-reprint-all t)
2611 (ses-setup))
2612 (if (>= col ses--numcols)
2613 (setq col (1- col)))
2614 (ses-goto-print origrow col)))
2616 (defun ses-forward-or-insert (&optional count)
2617 "Move to next cell in row, or inserts a new cell if already in last one, or
2618 inserts a new row if at bottom of print area. Repeat COUNT times."
2619 (interactive "p")
2620 (ses-check-curcell 'end)
2621 (setq deactivate-mark t) ; Doesn't combine well with ranges.
2622 (dotimes (x count)
2623 (ses-set-curcell)
2624 (if (not ses--curcell)
2625 (progn ; At bottom of print area.
2626 (barf-if-buffer-read-only)
2627 (ses-insert-row 1))
2628 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2629 (when (/= 32
2630 (char-before (next-single-property-change (point)
2631 'intangible)))
2632 ;; We're already in last nonskipped cell on line. Need to create a
2633 ;; new column.
2634 (barf-if-buffer-read-only)
2635 (ses-insert-column (- count x)
2636 ses--numcols
2637 (ses-col-width col)
2638 (ses-col-printer col)))))
2639 (forward-char)))
2641 (defun ses-append-row-jump-first-column ()
2642 "Insert a new row after current one and jump to its first column."
2643 (interactive "*")
2644 (ses-check-curcell)
2645 (ses-begin-change)
2646 (beginning-of-line 2)
2647 (ses-set-curcell)
2648 (ses-insert-row 1))
2650 (defun ses-set-column-width (col newwidth)
2651 "Set the width of the current column."
2652 (interactive
2653 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2654 (barf-if-buffer-read-only)
2655 (list col
2656 (if current-prefix-arg
2657 (prefix-numeric-value current-prefix-arg)
2658 (read-from-minibuffer (format "Column %s width [currently %d]: "
2659 (ses-column-letter col)
2660 (ses-col-width col))
2661 nil ; No initial contents.
2662 nil ; No override keymap.
2663 t ; Convert to Lisp object.
2664 nil ; No history.
2665 (number-to-string
2666 (ses-col-width col))))))) ; Default value.
2667 (if (< newwidth 1)
2668 (error "Invalid column width"))
2669 (ses-begin-change)
2670 (ses-reset-header-string)
2671 (save-excursion
2672 (let ((inhibit-quit t))
2673 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2674 (ses-set-parameter 'ses--col-widths newwidth col))
2675 (dotimes (row ses--numrows)
2676 (ses-print-cell-new-width row col))))
2679 ;;----------------------------------------------------------------------------
2680 ;; Cut and paste, import and export
2681 ;;----------------------------------------------------------------------------
2683 (defadvice copy-region-as-kill (around ses-copy-region-as-kill
2684 activate preactivate)
2685 "It doesn't make sense to copy read-only or intangible attributes into the
2686 kill ring. It probably doesn't make sense to copy keymap properties.
2687 We'll assume copying front-sticky properties doesn't make sense, either.
2689 This advice also includes some SES-specific code because otherwise it's too
2690 hard to override how mouse-1 works."
2691 (when (> beg end)
2692 (let ((temp beg))
2693 (setq beg end
2694 end temp)))
2695 (if (not (and (eq major-mode 'ses-mode)
2696 (eq (get-text-property beg 'read-only) 'ses)
2697 (eq (get-text-property (1- end) 'read-only) 'ses)))
2698 ad-do-it ; Normal copy-region-as-kill.
2699 (kill-new (ses-copy-region beg end))
2700 (if transient-mark-mode
2701 (setq deactivate-mark t))
2702 nil))
2704 (defun ses-copy-region (beg end)
2705 "Treat the region as rectangular. Convert the intangible attributes to
2706 SES attributes recording the contents of the cell as of the time of copying."
2707 (when (= end ses--data-marker)
2708 ;;Avoid overflow situation
2709 (setq end (1- ses--data-marker)))
2710 (let* ((inhibit-point-motion-hooks t)
2711 (x (mapconcat 'ses-copy-region-helper
2712 (extract-rectangle beg (1- end)) "\n")))
2713 (remove-text-properties 0 (length x)
2714 '(read-only t
2715 intangible t
2716 keymap t
2717 front-sticky t)
2721 (defun ses-copy-region-helper (line)
2722 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2723 external form by attaching to each print cell a 'ses attribute that records
2724 the corresponding data cell."
2725 (or (> (length line) 1)
2726 (error "Empty range"))
2727 (let ((inhibit-read-only t)
2728 (pos 0)
2729 mycell next sym rowcol)
2730 (while pos
2731 (setq sym (get-text-property pos 'intangible line)
2732 next (next-single-property-change pos 'intangible line)
2733 rowcol (ses-sym-rowcol sym)
2734 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2735 (put-text-property pos (or next (length line))
2736 'ses
2737 (list (ses-cell-symbol mycell)
2738 (ses-cell-formula mycell)
2739 (ses-cell-printer mycell))
2740 line)
2741 (setq pos next)))
2742 line)
2744 (defun ses-kill-override (beg end)
2745 "Generic override for any commands that kill text.
2746 We clear the killed cells instead of deleting them."
2747 (interactive "r")
2748 (ses-check-curcell 'needrange)
2749 ;; For some reason, the text-read-only error is not caught by `delete-region',
2750 ;; so we have to use subterfuge.
2751 (let ((buffer-read-only t))
2752 (1value (condition-case x
2753 (noreturn (funcall (lookup-key (current-global-map)
2754 (this-command-keys))
2755 beg end))
2756 (buffer-read-only nil)))) ; The expected error.
2757 ;; Because the buffer was marked read-only, the kill command turned itself
2758 ;; into a copy. Now we clear the cells or signal the error. First we check
2759 ;; whether the buffer really is read-only.
2760 (barf-if-buffer-read-only)
2761 (ses-begin-change)
2762 (ses-dorange ses--curcell
2763 (ses-clear-cell row col))
2764 (ses-jump (car ses--curcell)))
2766 (defadvice yank (around ses-yank activate preactivate)
2767 "In SES mode, the yanked text is inserted as cells.
2769 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2770 SES buffer), the formulas and print functions are restored for the cells. If
2771 the text contains tabs, this is an insertion of tab-separated formulas.
2772 Otherwise the text is inserted as the formula for the current cell.
2774 When inserting cells, the formulas are usually relocated to keep the same
2775 relative references to neighboring cells. This is best if the formulas
2776 generally refer to other cells within the yanked text. You can use the C-u
2777 prefix to specify insertion without relocation, which is best when the
2778 formulas refer to cells outside the yanked text.
2780 When inserting formulas, the text is treated as a string constant if it doesn't
2781 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2782 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2783 as symbols."
2784 (if (not (and (eq major-mode 'ses-mode)
2785 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2786 ad-do-it ; Normal non-SES yank.
2787 (ses-check-curcell 'end)
2788 (push-mark (point))
2789 (let ((text (current-kill (cond
2790 ((listp arg) 0)
2791 ((eq arg '-) -1)
2792 (t (1- arg))))))
2793 (or (ses-yank-cells text arg)
2794 (ses-yank-tsf text arg)
2795 (ses-yank-one (ses-yank-resize 1 1)
2796 text
2798 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2799 ;; Just one cell --- delete final tab or newline.
2800 (1- (length text)))
2801 arg)))
2802 (if (consp arg)
2803 (exchange-point-and-mark))))
2805 (defun ses-yank-pop (arg)
2806 "Replace just-yanked stretch of killed text with a different stretch.
2807 This command is allowed only immediately after a `yank' or a `yank-pop',
2808 when the region contains a stretch of reinserted previously-killed text.
2809 We replace it with a different stretch of killed text.
2810 Unlike standard `yank-pop', this function uses `undo' to delete the
2811 previous insertion."
2812 (interactive "*p")
2813 (or (eq last-command 'yank)
2814 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2815 ;;macro definition.
2816 (noreturn (error "Previous command was not a yank")))
2817 (undo)
2818 (ses-set-curcell)
2819 (yank (1+ (or arg 1)))
2820 (setq this-command 'yank))
2822 (defun ses-yank-cells (text arg)
2823 "If the TEXT has a proper set of 'ses attributes, insert the text as
2824 cells, else return nil. The cells are reprinted--the supplied text is
2825 ignored because the column widths, default printer, etc. at yank time might
2826 be different from those at kill-time. ARG is a list to indicate that
2827 formulas are to be inserted without relocation."
2828 (let ((first (get-text-property 0 'ses text))
2829 (last (get-text-property (1- (length text)) 'ses text)))
2830 (when (and first last) ;;Otherwise not proper set of attributes
2831 (setq first (ses-sym-rowcol (car first))
2832 last (ses-sym-rowcol (car last)))
2833 (let* ((needrows (- (car last) (car first) -1))
2834 (needcols (- (cdr last) (cdr first) -1))
2835 (rowcol (ses-yank-resize needrows needcols))
2836 (rowincr (- (car rowcol) (car first)))
2837 (colincr (- (cdr rowcol) (cdr first)))
2838 (pos 0)
2839 myrow mycol x)
2840 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2841 (setq myrow (+ row (car rowcol)))
2842 (dotimes (col needcols)
2843 (setq mycol (+ col (cdr rowcol))
2844 last (get-text-property pos 'ses text)
2845 pos (next-single-property-change pos 'ses text)
2846 x (ses-sym-rowcol (car last)))
2847 (if (not last)
2848 ;; Newline --- all remaining cells on row are skipped.
2849 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2850 last (list nil nil nil)
2851 pos (1- pos)))
2852 (if (/= (car x) (- myrow rowincr))
2853 (error "Cell row error"))
2854 (if (< (- mycol colincr) (cdr x))
2855 ;; Some columns were skipped.
2856 (let ((oldcol mycol))
2857 (while (< (- mycol colincr) (cdr x))
2858 (ses-clear-cell myrow mycol)
2859 (setq col (1+ col)
2860 mycol (1+ mycol)))
2861 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
2862 (when (car last) ; Skip this for *skip* cells.
2863 (setq x (nth 2 last))
2864 (unless (equal x (ses-cell-printer myrow mycol))
2865 (or (not x)
2866 (stringp x)
2867 (eq (car-safe x) 'ses-safe-printer)
2868 (setq x `(ses-safe-printer ,x)))
2869 (ses-set-cell myrow mycol 'printer x))
2870 (setq x (cadr last))
2871 (if (atom arg)
2872 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2873 (or (atom x)
2874 (eq (car-safe x) 'ses-safe-formula)
2875 (setq x `(ses-safe-formula ,x)))
2876 (ses-cell-set-formula myrow mycol x)))
2877 (when pos
2878 (if (get-text-property pos 'ses text)
2879 (error "Missing newline between rows"))
2880 (setq pos (next-single-property-change pos 'ses text))))
2881 t))))
2883 (defun ses-yank-one (rowcol text from to arg)
2884 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2885 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2886 (let ((val (condition-case nil
2887 (read-from-string text from to)
2888 (error (cons nil from)))))
2889 (cond
2890 ((< (cdr val) (or to (length text)))
2891 ;; Invalid sexp --- leave it as a string.
2892 (setq val (substring text from to)))
2893 ((and (car val) (symbolp (car val)))
2894 (if (consp arg)
2895 (setq val (list 'quote (car val))) ; Keep symbol.
2896 (setq val (substring text from to)))) ; Treat symbol as text.
2898 (setq val (car val))))
2899 (let ((row (car rowcol))
2900 (col (cdr rowcol)))
2901 (or (atom val)
2902 (setq val `(ses-safe-formula ,val)))
2903 (ses-cell-set-formula row col val))))
2905 (defun ses-yank-tsf (text arg)
2906 "If TEXT contains tabs and/or newlines, treat the tabs as
2907 column-separators and the newlines as row-separators and insert the text as
2908 cell formulas--else return nil. Treat plain symbols as strings unless ARG
2909 is a list. Ignore a final newline."
2910 (if (or (not (string-match "[\t\n]" text))
2911 (= (match-end 0) (length text)))
2912 ;;Not TSF format
2914 (if (/= (aref text (1- (length text))) ?\n)
2915 (setq text (concat text "\n")))
2916 (let ((pos -1)
2917 (spots (list -1))
2918 (cols 0)
2919 (needrows 0)
2920 needcols rowcol)
2921 ;;Find all the tabs and newlines
2922 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
2923 (push pos spots)
2924 (setq cols (1+ cols))
2925 (when (eq (aref text pos) ?\n)
2926 (if (not needcols)
2927 (setq needcols cols)
2928 (or (= needcols cols)
2929 (error "Inconsistent row lengths")))
2930 (setq cols 0
2931 needrows (1+ needrows))))
2932 ;;Insert the formulas
2933 (setq rowcol (ses-yank-resize needrows needcols))
2934 (dotimes (row needrows)
2935 (dotimes (col needcols)
2936 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
2937 (+ (cdr rowcol) needcols (- col) -1))
2938 text (1+ (cadr spots)) (car spots) arg)
2939 (setq spots (cdr spots))))
2940 (ses-goto-print (+ (car rowcol) needrows -1)
2941 (+ (cdr rowcol) needcols -1))
2942 t)))
2944 (defun ses-yank-resize (needrows needcols)
2945 "If this yank will require inserting rows and/or columns, ask for
2946 confirmation and then insert them. Result is (row,col) for top left of yank
2947 spot, or error signal if user requests cancel."
2948 (ses-begin-change)
2949 (let ((rowcol (if ses--curcell
2950 (ses-sym-rowcol ses--curcell)
2951 (cons ses--numrows 0)))
2952 rowbool colbool)
2953 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
2954 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
2955 rowbool (> needrows 0)
2956 colbool (> needcols 0))
2957 (when (or rowbool colbool)
2958 ;;Need to insert. Get confirm
2959 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
2960 (if rowbool (format "%d rows" needrows) "")
2961 (if (and rowbool colbool) " and " "")
2962 (if colbool (format "%d columns" needcols) "")))
2963 (error "Cancelled"))
2964 (when rowbool
2965 (let (ses--curcell)
2966 (save-excursion
2967 (ses-goto-print ses--numrows 0)
2968 (ses-insert-row needrows))))
2969 (when colbool
2970 (ses-insert-column needcols
2971 ses--numcols
2972 (ses-col-width (1- ses--numcols))
2973 (ses-col-printer (1- ses--numcols)))))
2974 rowcol))
2976 (defun ses-export-tsv (beg end)
2977 "Export values from the current range, with tabs between columns and
2978 newlines between rows. Result is placed in kill ring."
2979 (interactive "r")
2980 (ses-export-tab nil))
2982 (defun ses-export-tsf (beg end)
2983 "Export formulas from the current range, with tabs between columns and
2984 newlines between rows. Result is placed in kill ring."
2985 (interactive "r")
2986 (ses-export-tab t))
2988 (defun ses-export-tab (want-formulas)
2989 "Export the current range with tabs between columns and newlines between rows.
2990 Result is placed in kill ring. The export is values unless WANT-FORMULAS
2991 is non-nil. Newlines and tabs in the export text are escaped."
2992 (ses-check-curcell 'needrange)
2993 (let ((print-escape-newlines t)
2994 result item)
2995 (ses-dorange ses--curcell
2996 (setq item (if want-formulas
2997 (ses-cell-formula row col)
2998 (ses-cell-value row col)))
2999 (if (eq (car-safe item) 'ses-safe-formula)
3000 ;;Hide our deferred safety-check marker
3001 (setq item (cadr item)))
3002 (if (or (not item) (eq item '*skip*))
3003 (setq item ""))
3004 (when (eq (car-safe item) 'quote)
3005 (push "'" result)
3006 (setq item (cadr item)))
3007 (setq item (prin1-to-string item t))
3008 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
3009 (push item result)
3010 (cond
3011 ((< col maxcol)
3012 (push "\t" result))
3013 ((< row maxrow)
3014 (push "\n" result))))
3015 (setq result (apply 'concat (nreverse result)))
3016 (kill-new result)))
3019 ;;----------------------------------------------------------------------------
3020 ;; Other user commands
3021 ;;----------------------------------------------------------------------------
3023 (defun ses-unset-header-row ()
3024 "Select the default header row."
3025 (interactive)
3026 (ses-set-header-row 0))
3028 (defun ses-set-header-row (row)
3029 "Set the ROW to display in the header-line.
3030 With a numerical prefix arg, use that row.
3031 With no prefix arg, use the current row.
3032 With a \\[universal-argument] prefix arg, prompt the user.
3033 The top row is row 1. Selecting row 0 displays the default header row."
3034 (interactive
3035 (list (if (numberp current-prefix-arg) current-prefix-arg
3036 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3037 (if current-prefix-arg
3038 (read-number "Header row: " currow)
3039 currow)))))
3040 (if (or (< row 0) (> row ses--numrows))
3041 (error "Invalid header-row"))
3042 (ses-begin-change)
3043 (let ((oldval ses--header-row))
3044 (let (buffer-undo-list)
3045 (ses-set-parameter 'ses--header-row row))
3046 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
3047 (ses-reset-header-string))
3049 (defun ses-mark-row ()
3050 "Mark the entirety of current row as a range."
3051 (interactive)
3052 (ses-check-curcell 'range)
3053 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
3054 (push-mark (point))
3055 (ses-goto-print (1+ row) 0)
3056 (push-mark (point) nil t)
3057 (ses-goto-print row 0)))
3059 (defun ses-mark-column ()
3060 "Mark the entirety of current column as a range."
3061 (interactive)
3062 (ses-check-curcell 'range)
3063 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
3064 (row 0))
3065 (push-mark (point))
3066 (ses-goto-print (1- ses--numrows) col)
3067 (forward-char 1)
3068 (push-mark (point) nil t)
3069 (while (eq '*skip* (ses-cell-value row col))
3070 ;;Skip over initial cells in column that can't be selected
3071 (setq row (1+ row)))
3072 (ses-goto-print row col)))
3074 (defun ses-end-of-line ()
3075 "Move point to last cell on line."
3076 (interactive)
3077 (ses-check-curcell 'end 'range)
3078 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3079 ; anyway.
3080 (let ((col (1- ses--numcols))
3081 row rowcol)
3082 (if (symbolp ses--curcell)
3083 ;; Single cell.
3084 (setq row (car (ses-sym-rowcol ses--curcell)))
3085 ;; Range --- use whichever end of the range the point is at.
3086 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
3087 (car ses--curcell)
3088 (cdr ses--curcell))))
3089 ;; If range already includes the last cell in a row, point is actually
3090 ;; in the following row.
3091 (if (<= (cdr rowcol) (1- col))
3092 (setq row (car rowcol))
3093 (setq row (1+ (car rowcol)))
3094 (if (= row ses--numrows)
3095 ;;Already at end - can't go anywhere
3096 (setq col 0))))
3097 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
3098 (while (eq (ses-cell-value row col) '*skip*)
3099 ;; Back to beginning of multi-column cell.
3100 (setq col (1- col)))
3101 (ses-goto-print row col)))))
3103 (defun ses-renarrow-buffer ()
3104 "Narrow the buffer so only the print area is visible.
3105 Use after \\[widen]."
3106 (interactive)
3107 (setq ses--deferred-narrow t))
3109 (defun ses-sort-column (sorter &optional reverse)
3110 "Sort the range by a specified column.
3111 With prefix, sorts in REVERSE order."
3112 (interactive "*sSort column: \nP")
3113 (ses-check-curcell 'needrange)
3114 (let ((min (ses-sym-rowcol (car ses--curcell)))
3115 (max (ses-sym-rowcol (cdr ses--curcell))))
3116 (let ((minrow (car min))
3117 (mincol (cdr min))
3118 (maxrow (car max))
3119 (maxcol (cdr max))
3120 keys extracts end)
3121 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3122 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3123 (error "Invalid sort column"))
3124 ;;Get key columns and sort them
3125 (dotimes (x (- maxrow minrow -1))
3126 (ses-goto-print (+ minrow x) sorter)
3127 (setq end (next-single-property-change (point) 'intangible))
3128 (push (cons (buffer-substring-no-properties (point) end)
3129 (+ minrow x))
3130 keys))
3131 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3132 ;;Extract the lines in reverse sorted order
3133 (or reverse
3134 (setq keys (nreverse keys)))
3135 (dolist (x keys)
3136 (ses-goto-print (cdr x) (1+ maxcol))
3137 (setq end (point))
3138 (ses-goto-print (cdr x) mincol)
3139 (push (ses-copy-region (point) end) extracts))
3140 (deactivate-mark)
3141 ;;Paste the lines sequentially
3142 (dotimes (x (- maxrow minrow -1))
3143 (ses-goto-print (+ minrow x) mincol)
3144 (ses-set-curcell)
3145 (ses-yank-cells (pop extracts) nil)))))
3147 (defun ses-sort-column-click (event reverse)
3148 "Mouse version of `ses-sort-column'."
3149 (interactive "*e\nP")
3150 (setq event (event-end event))
3151 (select-window (posn-window event))
3152 (setq event (car (posn-col-row event))) ; Click column.
3153 (let ((col 0))
3154 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3155 (setq event (- event (ses-col-width col) 1)
3156 col (1+ col)))
3157 (if (>= col ses--numcols)
3158 (ding)
3159 (ses-sort-column (ses-column-letter col) reverse))))
3161 (defun ses-insert-range ()
3162 "Insert into minibuffer the list of cells currently highlighted in the
3163 spreadsheet."
3164 (interactive "*")
3165 (let (x)
3166 (with-current-buffer (window-buffer minibuffer-scroll-window)
3167 (ses-command-hook) ; For ses-coverage.
3168 (ses-check-curcell 'needrange)
3169 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3170 ,(cdr ses--curcell))))))
3171 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3173 (defun ses-insert-ses-range ()
3174 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
3175 highlighted range in the spreadsheet."
3176 (interactive "*")
3177 (let (x)
3178 (with-current-buffer (window-buffer minibuffer-scroll-window)
3179 (ses-command-hook) ; For ses-coverage.
3180 (ses-check-curcell 'needrange)
3181 (setq x (format "(ses-range %S %S)"
3182 (car ses--curcell)
3183 (cdr ses--curcell))))
3184 (insert x)))
3186 (defun ses-insert-range-click (event)
3187 "Mouse version of `ses-insert-range'."
3188 (interactive "*e")
3189 (mouse-set-point event)
3190 (ses-insert-range))
3192 (defun ses-insert-ses-range-click (event)
3193 "Mouse version of `ses-insert-ses-range'."
3194 (interactive "*e")
3195 (mouse-set-point event)
3196 (ses-insert-ses-range))
3198 (defun ses-replace-name-in-formula (formula old-name new-name)
3199 (let ((new-formula formula))
3200 (unless (and (consp formula)
3201 (eq (car-safe formula) 'quote))
3202 (while formula
3203 (let ((elt (car-safe formula)))
3204 (cond
3205 ((consp elt)
3206 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3207 ((and (symbolp elt)
3208 (eq (car-safe formula) old-name))
3209 (setcar formula new-name))))
3210 (setq formula (cdr formula))))
3211 new-formula))
3213 (defun ses-rename-cell (new-name &optional cell)
3214 "Rename current cell."
3215 (interactive "*SEnter new name: ")
3216 (and (local-variable-p new-name)
3217 (ses-sym-rowcol new-name)
3218 ;; this test is needed because ses-cell property of deleted cells
3219 ;; is not deleted in case of subsequent undo
3220 (memq new-name ses--renamed-cell-symb-list)
3221 (error "Already a cell name"))
3222 (and (boundp new-name)
3223 (null (yes-or-no-p (format "`%S' is already bound outside this buffer, continue? "
3224 new-name)))
3225 (error "Already a bound cell name"))
3226 (let* ((sym (if (ses-cell-p cell)
3227 (ses-cell-symbol cell)
3228 (setq cell nil)
3229 (ses-check-curcell)
3230 ses--curcell))
3231 (rowcol (ses-sym-rowcol sym))
3232 (row (car rowcol))
3233 (col (cdr rowcol)))
3234 (setq cell (or cell (ses-get-cell row col)))
3235 (push `(ses-rename-cell ,(ses-cell-symbol cell) ,cell) buffer-undo-list)
3236 (put new-name 'ses-cell rowcol)
3237 ;; replace name by new name in formula of cells refering to renamed cell
3238 (dolist (ref (ses-cell-references cell))
3239 (let* ((x (ses-sym-rowcol ref))
3240 (xcell (ses-get-cell (car x) (cdr x))))
3241 (ses-cell-formula-aset xcell
3242 (ses-replace-name-in-formula
3243 (ses-cell-formula xcell)
3245 new-name))))
3246 ;; replace name by new name in reference list of cells to which renamed cell refers to
3247 (dolist (ref (ses-formula-references (ses-cell-formula cell)))
3248 (let* ((x (ses-sym-rowcol ref))
3249 (xcell (ses-get-cell (car x) (cdr x))))
3250 (ses-cell-references-aset xcell
3251 (cons new-name (delq sym
3252 (ses-cell-references xcell))))))
3253 (push new-name ses--renamed-cell-symb-list)
3254 (set new-name (symbol-value sym))
3255 (aset cell 0 new-name)
3256 (put sym 'ses-cell nil)
3257 (makunbound sym)
3258 (setq sym new-name)
3259 (let* ((pos (point))
3260 (inhibit-read-only t)
3261 (col (current-column))
3262 (end (save-excursion
3263 (move-to-column (1+ col))
3264 (if (eolp)
3265 (+ pos (ses-col-width col) 1)
3266 (point)))))
3267 (put-text-property pos end 'intangible new-name))
3268 ;; update mode line
3269 (setq mode-line-process (list " cell "
3270 (symbol-name sym)))
3271 (force-mode-line-update)))
3273 ;;----------------------------------------------------------------------------
3274 ;; Checking formulas for safety
3275 ;;----------------------------------------------------------------------------
3277 (defun ses-safe-printer (printer)
3278 "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
3279 (if (or (stringp printer)
3280 (stringp (car-safe printer))
3281 (not printer)
3282 (ses-warn-unsafe printer 'unsafep-function))
3283 printer
3284 'ses-unsafe))
3286 (defun ses-safe-formula (formula)
3287 "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
3288 (if (ses-warn-unsafe formula 'unsafep)
3289 formula
3290 `(ses-unsafe ',formula)))
3292 (defun ses-warn-unsafe (formula checker)
3293 "Apply CHECKER to FORMULA.
3294 If result is non-nil, asks user for confirmation about FORMULA,
3295 which might be unsafe. Returns t if formula is safe or user allows
3296 execution anyway. Always returns t if `safe-functions' is t."
3297 (if (eq safe-functions t)
3299 (setq checker (funcall checker formula))
3300 (if (not checker)
3302 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3303 formula checker)))))
3306 ;;----------------------------------------------------------------------------
3307 ;; Standard formulas
3308 ;;----------------------------------------------------------------------------
3310 (defun ses--clean-! (&rest x)
3311 "Clean by `delq' list X from any occurrence of `nil' or `*skip*'."
3312 (delq nil (delq '*skip* x)))
3314 (defun ses--clean-_ (x y)
3315 "Clean list X by replacing by Y any occurrence of `nil' or `*skip*'.
3317 This will change X by making `setcar' on its cons cells."
3318 (let ((ret x) ret-elt)
3319 (while ret
3320 (setq ret-elt (car ret))
3321 (when (memq ret-elt '(nil *skip*))
3322 (setcar ret y))
3323 (setq ret (cdr ret))))
3326 (defmacro ses-range (from to &rest rest)
3327 "Expand to a list of cell-symbols for the range going from
3328 FROM up to TO. The range automatically expands to include any
3329 new row or column inserted into its middle. The SES library code
3330 specifically looks for the symbol `ses-range', so don't create an
3331 alias for this macro!
3333 By passing in REST some flags one can configure the way the range
3334 is read and how it is formatted.
3336 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3337 1 2 3 and 4.
3339 Readout direction is specified by a `>v', '`>^', `<v', `<^',
3340 `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3341 of such a flag, a default direction of `^<' is assumed. This
3342 way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3343 while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3345 If the range is one row, then `>' can be used as a shorthand to
3346 `>v' or `>^', and `<' to `<v' or `<^'.
3348 If the range is one column, then `v' can be used as a shorthand to
3349 `v>' or `v<', and `^' to `^>' or `v<'.
3351 A `!' flag will remove all cells whose value is nil or `*skip*'.
3353 A `_' flag will replace nil or `*skip*' by the value following
3354 the `_' flag. If the `_' flag is the last argument, then they are
3355 replaced by integer 0.
3357 A `*', `*1' or `*2' flag will vectorize the range in the sense of
3358 Calc. See info node `(Calc) Top'. Flag `*' will output either a
3359 vector or a matrix depending on the number of rows, `*1' will
3360 flatten the result to a one row vector, and `*2' will make a
3361 matrix whatever the number of rows.
3363 Warning: interaction with Calc is experimental and may produce
3364 confusing results if you are not aware of Calc data format.
3365 Use `math-format-value' as a printer for Calc objects."
3366 (let (result-row
3367 result
3368 (prev-row -1)
3369 (reorient-x nil)
3370 (reorient-y nil)
3371 transpose vectorize
3372 (clean 'list))
3373 (ses-dorange (cons from to)
3374 (when (/= prev-row row)
3375 (push result-row result)
3376 (setq result-row nil))
3377 (push (ses-cell-symbol row col) result-row)
3378 (setq prev-row row))
3379 (push result-row result)
3380 (while rest
3381 (let ((x (pop rest)))
3382 (pcase x
3383 (`>v (setq transpose nil reorient-x nil reorient-y nil))
3384 (`>^ (setq transpose nil reorient-x nil reorient-y t))
3385 (`<^ (setq transpose nil reorient-x t reorient-y t))
3386 (`<v (setq transpose nil reorient-x t reorient-y nil))
3387 (`v> (setq transpose t reorient-x nil reorient-y t))
3388 (`^> (setq transpose t reorient-x nil reorient-y nil))
3389 (`^< (setq transpose t reorient-x t reorient-y nil))
3390 (`v< (setq transpose t reorient-x t reorient-y t))
3391 ((or `* `*2 `*1) (setq vectorize x))
3392 (`! (setq clean 'ses--clean-!))
3393 (`_ (setq clean `(lambda (&rest x)
3394 (ses--clean-_ x ,(if rest (pop rest) 0)))))
3396 (cond
3397 ; shorthands one row
3398 ((and (null (cddr result)) (memq x '(> <)))
3399 (push (intern (concat (symbol-name x) "v")) rest))
3400 ; shorthands one col
3401 ((and (null (cdar result)) (memq x '(v ^)))
3402 (push (intern (concat (symbol-name x) ">")) rest))
3403 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3404 (if reorient-y
3405 (setcdr (last result 2) nil)
3406 (setq result (cdr (nreverse result))))
3407 (unless reorient-x
3408 (setq result (mapcar 'nreverse result)))
3409 (when transpose
3410 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3411 (while result
3412 (setq iter ret)
3413 (dolist (elt (pop result))
3414 (setcar iter (cons elt (car iter)))
3415 (setq iter (cdr iter))))
3416 (setq result ret)))
3418 (cl-flet ((vectorize-*1
3419 (clean result)
3420 (cons clean (cons (quote 'vec) (apply 'append result))))
3421 (vectorize-*2
3422 (clean result)
3423 (cons clean (cons (quote 'vec)
3424 (mapcar (lambda (x)
3425 (cons clean (cons (quote 'vec) x)))
3426 result)))))
3427 (pcase vectorize
3428 (`nil (cons clean (apply 'append result)))
3429 (`*1 (vectorize-*1 clean result))
3430 (`*2 (vectorize-*2 clean result))
3431 (`* (funcall (if (cdr result)
3432 #'vectorize-*2
3433 #'vectorize-*1)
3434 clean result))))))
3436 (defun ses-delete-blanks (&rest args)
3437 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3438 (let (result)
3439 (dolist (cur args)
3440 (unless (memq cur '(nil *skip*))
3441 (push cur result)))
3442 result))
3444 (defun ses+ (&rest args)
3445 "Compute the sum of the arguments, ignoring blanks."
3446 (apply '+ (apply 'ses-delete-blanks args)))
3448 (defun ses-average (list)
3449 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3450 are ignored. Result is always floating-point, even if all args are integers."
3451 (setq list (apply 'ses-delete-blanks list))
3452 (/ (float (apply '+ list)) (length list)))
3454 (defmacro ses-select (fromrange test torange)
3455 "Select cells in FROMRANGE that are `equal' to TEST.
3456 For each match, return the corresponding cell from TORANGE.
3457 The ranges are macroexpanded but not evaluated so they should be
3458 either (ses-range BEG END) or (list ...). The TEST is evaluated."
3459 (setq fromrange (cdr (macroexpand fromrange))
3460 torange (cdr (macroexpand torange))
3461 test (eval test))
3462 (or (= (length fromrange) (length torange))
3463 (error "ses-select: Ranges not same length"))
3464 (let (result)
3465 (dolist (x fromrange)
3466 (if (equal test (symbol-value x))
3467 (push (car torange) result))
3468 (setq torange (cdr torange)))
3469 (cons 'list result)))
3471 ;;All standard formulas are safe
3472 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3473 ses-select))
3474 (put x 'side-effect-free t))
3477 ;;----------------------------------------------------------------------------
3478 ;; Standard print functions
3479 ;;----------------------------------------------------------------------------
3481 ;; These functions use the variables 'row' and 'col' that are dynamically bound
3482 ;; by ses-print-cell. We define these variables at compile-time to make the
3483 ;; compiler happy.
3484 (defvar row)
3485 (defvar col)
3487 (defun ses-center (value &optional span fill)
3488 "Print VALUE, centered within column.
3489 FILL is the fill character for centering (default = space).
3490 SPAN indicates how many additional rightward columns to include
3491 in width (default = 0)."
3492 (let ((printer (or (ses-col-printer col) ses--default-printer))
3493 (width (ses-col-width col))
3494 half)
3495 (or fill (setq fill ?\s))
3496 (or span (setq span 0))
3497 (setq value (ses-call-printer printer value))
3498 (dotimes (x span)
3499 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
3500 ;; Set column width.
3501 (setq width (- width (string-width value)))
3502 (if (<= width 0)
3503 value ; Too large for field, anyway.
3504 (setq half (make-string (/ width 2) fill))
3505 (concat half value half
3506 (if (> (% width 2) 0) (char-to-string fill))))))
3508 (defun ses-center-span (value &optional fill)
3509 "Print VALUE, centered within the span that starts in the current column
3510 and continues until the next nonblank column.
3511 FILL specifies the fill character (default = space)."
3512 (let ((end (1+ col)))
3513 (while (and (< end ses--numcols)
3514 (memq (ses-cell-value row end) '(nil *skip*)))
3515 (setq end (1+ end)))
3516 (ses-center value (- end col 1) fill)))
3518 (defun ses-dashfill (value &optional span)
3519 "Print VALUE centered using dashes.
3520 SPAN indicates how many rightward columns to include in width (default = 0)."
3521 (ses-center value span ?-))
3523 (defun ses-dashfill-span (value)
3524 "Print VALUE, centered using dashes within the span that starts in the
3525 current column and continues until the next nonblank column."
3526 (ses-center-span value ?-))
3528 (defun ses-tildefill-span (value)
3529 "Print VALUE, centered using tildes within the span that starts in the
3530 current column and continues until the next nonblank column."
3531 (ses-center-span value ?~))
3533 (defun ses-unsafe (value)
3534 "Substitute for an unsafe formula or printer."
3535 (error "Unsafe formula or printer"))
3537 ;;All standard printers are safe, including ses-unsafe!
3538 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3539 (put x 'side-effect-free t))
3541 (defun ses-unload-function ()
3542 "Unload the Simple Emacs Spreadsheet."
3543 (dolist (fun '(copy-region-as-kill yank))
3544 (ad-remove-advice fun 'around (intern (concat "ses-" (symbol-name fun))))
3545 (ad-update fun))
3546 ;; continue standard unloading
3547 nil)
3549 (provide 'ses)
3551 ;;; ses.el ends here