* doc/emacs/custom.texi (Directory Variables): Fix paren typo.
[emacs.git] / lisp / ses.el
blob552c09bb47eb0c8b33216a4fb755294e94ce8a69
1 ;;; ses.el -- Simple Emacs Spreadsheet -*- coding: utf-8 -*-
3 ;; Copyright (C) 2002-2013 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-widen ()
1274 "Turn off narrowing, to be reenabled at end of command loop."
1275 (if (buffer-narrowed-p)
1276 (setq ses--deferred-narrow t))
1277 (widen))
1279 (defun ses-goto-data (def &optional col)
1280 "Move point to data area for (DEF,COL). If DEF is a row
1281 number, COL is the column number for a data cell -- otherwise DEF
1282 is one of the symbols ses--col-widths, ses--col-printers,
1283 ses--default-printer, ses--numrows, or ses--numcols."
1284 (ses-widen)
1285 (let ((inhibit-point-motion-hooks t)) ; In case intangible attrs are wrong.
1286 (if col
1287 ;; It's a cell.
1288 (progn
1289 (goto-char ses--data-marker)
1290 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
1291 ;; Convert def-symbol to offset.
1292 (setq def (plist-get ses-paramlines-plist def))
1293 (or def (signal 'args-out-of-range nil))
1294 (goto-char ses--params-marker)
1295 (forward-line def))))
1297 (defun ses-set-parameter (def value &optional elem)
1298 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1299 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1300 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
1301 (save-excursion
1302 ;; We call ses-goto-data early, using the old values of numrows and numcols
1303 ;; in case one of them is being changed.
1304 (ses-goto-data def)
1305 (let ((inhibit-read-only t)
1306 (fmt (plist-get '(ses--col-widths "(ses-column-widths %S)"
1307 ses--col-printers "(ses-column-printers %S)"
1308 ses--default-printer "(ses-default-printer %S)"
1309 ses--header-row "(ses-header-row %S)"
1310 ses--file-format " %S ;SES file-format"
1311 ses--numrows " %S ;numrows"
1312 ses--numcols " %S ;numcols")
1313 def))
1314 oldval)
1315 (if elem
1316 (progn
1317 (setq oldval (aref (symbol-value def) elem))
1318 (aset (symbol-value def) elem value))
1319 (setq oldval (symbol-value def))
1320 (set def value))
1321 ;; Special undo since it's outside the narrowed buffer.
1322 (let (buffer-undo-list)
1323 (delete-region (point) (line-end-position))
1324 (insert (format fmt (symbol-value def))))
1325 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1328 (defun ses-write-cells ()
1329 "Write cells in `ses--deferred-write' from local variables to data area.
1330 Newlines in the data are escaped."
1331 (let* ((inhibit-read-only t)
1332 (print-escape-newlines t)
1333 rowcol row col cell sym formula printer text)
1334 (setq ses-start-time (float-time))
1335 (with-temp-message " "
1336 (save-excursion
1337 (while ses--deferred-write
1338 (ses-time-check "Writing... (%d cells left)"
1339 '(length ses--deferred-write))
1340 (setq rowcol (pop ses--deferred-write)
1341 row (car rowcol)
1342 col (cdr rowcol)
1343 cell (ses-get-cell row col)
1344 sym (ses-cell-symbol cell)
1345 formula (ses-cell-formula cell)
1346 printer (ses-cell-printer cell))
1347 (if (eq (car-safe formula) 'ses-safe-formula)
1348 (setq formula (cadr formula)))
1349 (if (eq (car-safe printer) 'ses-safe-printer)
1350 (setq printer (cadr printer)))
1351 ;; This is noticeably faster than (format "%S %S %S %S %S")
1352 (setq text (concat "(ses-cell "
1353 (symbol-name sym)
1355 (prin1-to-string (symbol-value sym))
1357 (prin1-to-string formula)
1359 (prin1-to-string printer)
1361 (if (atom (ses-cell-references cell))
1362 "nil"
1363 (concat "("
1364 (mapconcat 'symbol-name
1365 (ses-cell-references cell)
1366 " ")
1367 ")"))
1368 ")"))
1369 (ses-goto-data row col)
1370 (delete-region (point) (line-end-position))
1371 (insert text)))
1372 (message " "))))
1375 ;;----------------------------------------------------------------------------
1376 ;; Formula relocation
1377 ;;----------------------------------------------------------------------------
1379 (defun ses-formula-references (formula &optional result-so-far)
1380 "Produce a list of symbols for cells that this FORMULA's value
1381 refers to. For recursive calls, RESULT-SO-FAR is the list being
1382 constructed, or t to get a wrong-type-argument error when the
1383 first reference is found."
1384 (if (ses-sym-rowcol formula)
1385 ;;Entire formula is one symbol
1386 (add-to-list 'result-so-far formula)
1387 (if (consp formula)
1388 (cond
1389 ((eq (car formula) 'ses-range)
1390 (dolist (cur
1391 (cdr (funcall 'macroexpand
1392 (list 'ses-range (nth 1 formula)
1393 (nth 2 formula)))))
1394 (add-to-list 'result-so-far cur)))
1395 ((null (eq (car formula) 'quote))
1396 ;;Recursive call for subformulas
1397 (dolist (cur formula)
1398 (setq result-so-far (ses-formula-references cur result-so-far))))
1400 ;;Ignore other stuff
1402 ;; other type of atom are ignored
1404 result-so-far)
1406 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1407 "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
1408 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1409 by (ROWINCR,COLINCR)."
1410 (let ((row (car rowcol))
1411 (col (cdr rowcol)))
1412 (if (or (< row startrow) (< col startcol))
1414 (setq row (+ row rowincr)
1415 col (+ col colincr))
1416 (if (and (>= row startrow) (>= col startcol)
1417 (< row ses--numrows) (< col ses--numcols))
1418 ;;Relocate this variable
1419 (ses-create-cell-symbol row col)
1420 ;;Delete reference to a deleted cell
1421 nil))))
1423 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1424 "Produce a copy of FORMULA where all symbols that refer to cells in row
1425 STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
1426 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1427 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1428 => (+ A1 B2 C4)
1429 If ROWINCR or COLINCR is negative, references to cells being deleted are
1430 removed. Example:
1431 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1432 => (+ A1 C3)
1433 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1434 (let (rowcol result)
1435 (if (or (atom formula) (eq (car formula) 'quote))
1436 (if (and (setq rowcol (ses-sym-rowcol formula))
1437 (string-match "\\`[A-Z]+[0-9]+\\'" (symbol-name formula)))
1438 (ses-relocate-symbol formula rowcol
1439 startrow startcol rowincr colincr)
1440 formula) ; Pass through as-is.
1441 (dolist (cur formula)
1442 (setq rowcol (ses-sym-rowcol cur))
1443 (cond
1444 (rowcol
1445 (setq cur (ses-relocate-symbol cur rowcol
1446 startrow startcol rowincr colincr))
1447 (if cur
1448 (push cur result)
1449 ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
1450 ;; don't change the flag if it's already 'range, since range implies
1451 ;; 'delete.
1452 (unless ses-relocate-return
1453 (setq ses-relocate-return 'delete))))
1454 ((eq (car-safe cur) 'ses-range)
1455 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1456 (if cur
1457 (push cur result)))
1458 ((or (atom cur) (eq (car cur) 'quote))
1459 ;; Constants pass through unchanged.
1460 (push cur result))
1462 ;; Recursively copy and alter subformulas.
1463 (push (ses-relocate-formula cur startrow startcol
1464 rowincr colincr)
1465 result))))
1466 (nreverse result))))
1468 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1469 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1470 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1471 new range, or nil if the entire range is deleted. If new rows are being added
1472 just beyond the end of a row range, or new columns just beyond a column range,
1473 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1474 if the range was altered."
1475 (let* ((minorig (cadr range))
1476 (minrowcol (ses-sym-rowcol minorig))
1477 (min (ses-relocate-symbol minorig minrowcol
1478 startrow startcol
1479 rowincr colincr))
1480 (maxorig (nth 2 range))
1481 (maxrowcol (ses-sym-rowcol maxorig))
1482 (max (ses-relocate-symbol maxorig maxrowcol
1483 startrow startcol
1484 rowincr colincr))
1485 field)
1486 (cond
1487 ((and (not min) (not max))
1488 (setq range nil)) ; The entire range is deleted.
1489 ((zerop colincr)
1490 ;; Inserting or deleting rows.
1491 (setq field 'car)
1492 (if (not min)
1493 ;; Chopped off beginning of range.
1494 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1495 ses-relocate-return 'range))
1496 (if (not max)
1497 (if (> rowincr 0)
1498 ;; Trying to insert a nonexistent row.
1499 (setq max (ses-create-cell-symbol (1- ses--numrows)
1500 (cdr minrowcol)))
1501 ;; End of range is being deleted.
1502 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1503 ses-relocate-return 'range))
1504 (and (> rowincr 0)
1505 (= (car maxrowcol) (1- startrow))
1506 (= (cdr minrowcol) (cdr maxrowcol))
1507 ;; Insert after ending row of vertical range --- include it.
1508 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1509 (cdr maxrowcol))))))
1511 ;; Inserting or deleting columns.
1512 (setq field 'cdr)
1513 (if (not min)
1514 ;; Chopped off beginning of range.
1515 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1516 ses-relocate-return 'range))
1517 (if (not max)
1518 (if (> colincr 0)
1519 ;; Trying to insert a nonexistent column.
1520 (setq max (ses-create-cell-symbol (car maxrowcol)
1521 (1- ses--numcols)))
1522 ;; End of range is being deleted.
1523 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1524 ses-relocate-return 'range))
1525 (and (> colincr 0)
1526 (= (cdr maxrowcol) (1- startcol))
1527 (= (car minrowcol) (car maxrowcol))
1528 ;; Insert after ending column of horizontal range --- include it.
1529 (setq max (ses-create-cell-symbol (car maxrowcol)
1530 (+ startcol colincr -1)))))))
1531 (when range
1532 (if (/= (- (funcall field maxrowcol)
1533 (funcall field minrowcol))
1534 (- (funcall field (ses-sym-rowcol max))
1535 (funcall field (ses-sym-rowcol min))))
1536 ;; This range has changed size.
1537 (setq ses-relocate-return 'range))
1538 `(ses-range ,min ,max ,@(cl-cdddr range)))))
1540 (defun ses-relocate-all (minrow mincol rowincr colincr)
1541 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1542 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1543 to each symbol."
1544 (let (reform)
1545 (let (mycell newval xrow)
1546 (dotimes-with-progress-reporter
1547 (row ses--numrows) "Relocating formulas..."
1548 (dotimes (col ses--numcols)
1549 (setq ses-relocate-return nil
1550 mycell (ses-get-cell row col)
1551 newval (ses-relocate-formula (ses-cell-formula mycell)
1552 minrow mincol rowincr colincr)
1553 xrow (- row rowincr))
1554 (ses-set-cell row col 'formula newval)
1555 (if (eq ses-relocate-return 'range)
1556 ;; This cell contains a (ses-range X Y) where a cell has been
1557 ;; inserted or deleted in the middle of the range.
1558 (push (cons row col) reform))
1559 (if ses-relocate-return
1560 ;; This cell referred to a cell that's been deleted or is no
1561 ;; longer part of the range. We can't fix that now because
1562 ;; reference lists cells have been partially updated.
1563 (add-to-list 'ses--deferred-recalc
1564 (ses-create-cell-symbol row col)))
1565 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1566 minrow mincol rowincr colincr))
1567 (ses-set-cell row col 'references newval)
1568 (and (>= row minrow) (>= col mincol)
1569 (let ((sym (ses-cell-symbol row col))
1570 (xcol (- col colincr)))
1571 (if (and
1573 (>= xrow 0)
1574 (>= xcol 0)
1575 (null (eq sym
1576 (ses-create-cell-symbol xrow xcol))))
1577 ;; This is a renamed cell, do not update the cell
1578 ;; name, but just update the coordinate property.
1579 (put sym 'ses-cell (cons row col))
1580 (ses-set-cell row col 'symbol
1581 (setq sym (ses-create-cell-symbol row col)))
1582 (unless (and (boundp sym) (local-variable-p sym))
1583 (set (make-local-variable sym) nil)
1584 (put sym 'ses-cell (cons row col)))))) )))
1585 ;; Relocate the cell values.
1586 (let (oldval myrow mycol xrow xcol)
1587 (cond
1588 ((and (<= rowincr 0) (<= colincr 0))
1589 ;; Deletion of rows and/or columns.
1590 (dotimes-with-progress-reporter
1591 (row (- ses--numrows minrow)) "Relocating variables..."
1592 (setq myrow (+ row minrow))
1593 (dotimes (col (- ses--numcols mincol))
1594 (setq mycol (+ col mincol)
1595 xrow (- myrow rowincr)
1596 xcol (- mycol colincr))
1597 (let ((sym (ses-cell-symbol myrow mycol))
1598 (xsym (ses-create-cell-symbol xrow xcol)))
1599 ;; Make the value relocation only when if the cell is not
1600 ;; a renamed cell. Otherwise this is not needed.
1601 (and (eq sym xsym)
1602 (ses-set-cell myrow mycol 'value
1603 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1604 (ses-cell-value xrow xcol)
1605 ;;Cell is off the end of the array
1606 (symbol-value xsym))))))))
1608 ((and (wholenump rowincr) (wholenump colincr))
1609 ;; Insertion of rows and/or columns. Run the loop backwards.
1610 (let ((disty (1- ses--numrows))
1611 (distx (1- ses--numcols))
1612 myrow mycol)
1613 (dotimes-with-progress-reporter
1614 (row (- ses--numrows minrow)) "Relocating variables..."
1615 (setq myrow (- disty row))
1616 (dotimes (col (- ses--numcols mincol))
1617 (setq mycol (- distx col)
1618 xrow (- myrow rowincr)
1619 xcol (- mycol colincr))
1620 (if (or (< xrow minrow) (< xcol mincol))
1621 ;; Newly-inserted value.
1622 (setq oldval nil)
1623 ;; Transfer old value.
1624 (setq oldval (ses-cell-value xrow xcol)))
1625 (ses-set-cell myrow mycol 'value oldval)))
1626 t)) ; Make testcover happy by returning non-nil here.
1628 (error "ROWINCR and COLINCR must have the same sign"))))
1629 ;; Reconstruct reference lists for cells that contain ses-ranges that have
1630 ;; changed size.
1631 (when reform
1632 (message "Fixing ses-ranges...")
1633 (let (row col)
1634 (setq ses-start-time (float-time))
1635 (while reform
1636 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1637 (setq row (caar reform)
1638 col (cdar reform)
1639 reform (cdr reform))
1640 (ses-cell-set-formula row col (ses-cell-formula row col))))
1641 (message nil))))
1644 ;;----------------------------------------------------------------------------
1645 ;; Undo control
1646 ;;----------------------------------------------------------------------------
1648 (defun ses-begin-change ()
1649 "For undo, remember point before we start changing hidden stuff."
1650 (let ((inhibit-read-only t))
1651 (insert-and-inherit "X")
1652 (delete-region (1- (point)) (point))))
1654 (defun ses-set-with-undo (sym newval)
1655 "Like set, but undoable. Result is t if value has changed."
1656 ;; We try to avoid adding redundant entries to the undo list, but this is
1657 ;; unavoidable for strings because equal ignores text properties and there's
1658 ;; no easy way to get the whole property list to see if it's different!
1659 (unless (and (boundp sym)
1660 (equal (symbol-value sym) newval)
1661 (not (stringp newval)))
1662 (push (if (boundp sym)
1663 `(apply ses-set-with-undo ,sym ,(symbol-value sym))
1664 `(apply ses-unset-with-undo ,sym))
1665 buffer-undo-list)
1666 (set sym newval)
1669 (defun ses-unset-with-undo (sym)
1670 "Set SYM to be unbound. This is undoable."
1671 (when (1value (boundp sym)) ; Always bound, except after a programming error.
1672 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym)) buffer-undo-list)
1673 (makunbound sym)))
1675 (defun ses-aset-with-undo (array idx newval)
1676 "Like `aset', but undoable.
1677 Result is t if element has changed."
1678 (unless (equal (aref array idx) newval)
1679 (push `(apply ses-aset-with-undo ,array ,idx
1680 ,(aref array idx)) buffer-undo-list)
1681 (aset array idx newval)
1685 ;;----------------------------------------------------------------------------
1686 ;; Startup for major mode
1687 ;;----------------------------------------------------------------------------
1689 (defun ses-load ()
1690 "Parse the current buffer and set up buffer-local variables.
1691 Does not execute cell formulas or print functions."
1692 (widen)
1693 ;; Read our global parameters, which should be a 3-element list.
1694 (goto-char (point-max))
1695 (search-backward ";; Local Variables:\n" nil t)
1696 (backward-list 1)
1697 (setq ses--params-marker (point-marker))
1698 (let ((params (condition-case nil (read (current-buffer)) (error nil))))
1699 (or (and (= (safe-length params) 3)
1700 (numberp (car params))
1701 (numberp (cadr params))
1702 (>= (cadr params) 0)
1703 (numberp (nth 2 params))
1704 (> (nth 2 params) 0))
1705 (error "Invalid SES file"))
1706 (setq ses--file-format (car params)
1707 ses--numrows (cadr params)
1708 ses--numcols (nth 2 params))
1709 (when (= ses--file-format 1)
1710 (let (buffer-undo-list) ; This is not undoable.
1711 (ses-goto-data 'ses--header-row)
1712 (insert "(ses-header-row 0)\n")
1713 (ses-set-parameter 'ses--file-format 2)
1714 (message "Upgrading from SES-1 file format")))
1715 (or (= ses--file-format 2)
1716 (error "This file needs a newer version of the SES library code"))
1717 ;; Initialize cell array.
1718 (setq ses--cells (make-vector ses--numrows nil))
1719 (dotimes (row ses--numrows)
1720 (aset ses--cells row (make-vector ses--numcols nil))))
1721 ;; Skip over print area, which we assume is correct.
1722 (goto-char (point-min))
1723 (forward-line ses--numrows)
1724 (or (looking-at ses-print-data-boundary)
1725 (error "Missing marker between print and data areas"))
1726 (forward-char 1)
1727 (setq ses--data-marker (point-marker))
1728 (forward-char (1- (length ses-print-data-boundary)))
1729 ;; Initialize printer and symbol lists.
1730 (mapc 'ses-printer-record ses-standard-printer-functions)
1731 (setq ses--symbolic-formulas nil)
1732 ;; Load cell definitions.
1733 (dotimes (row ses--numrows)
1734 (dotimes (col ses--numcols)
1735 (let* ((x (read (current-buffer)))
1736 (sym (car-safe (cdr-safe x))))
1737 (or (and (looking-at "\n")
1738 (eq (car-safe x) 'ses-cell)
1739 (ses-create-cell-variable sym row col))
1740 (error "Cell-def error"))
1741 (eval x)))
1742 (or (looking-at "\n\n")
1743 (error "Missing blank line between rows")))
1744 ;; Load global parameters.
1745 (let ((widths (read (current-buffer)))
1746 (n1 (char-after (point)))
1747 (printers (read (current-buffer)))
1748 (n2 (char-after (point)))
1749 (def-printer (read (current-buffer)))
1750 (n3 (char-after (point)))
1751 (head-row (read (current-buffer)))
1752 (n4 (char-after (point))))
1753 (or (and (eq (car-safe widths) 'ses-column-widths)
1754 (= n1 ?\n)
1755 (eq (car-safe printers) 'ses-column-printers)
1756 (= n2 ?\n)
1757 (eq (car-safe def-printer) 'ses-default-printer)
1758 (= n3 ?\n)
1759 (eq (car-safe head-row) 'ses-header-row)
1760 (= n4 ?\n))
1761 (error "Invalid SES global parameters"))
1762 (1value (eval widths))
1763 (1value (eval def-printer))
1764 (1value (eval printers))
1765 (1value (eval head-row)))
1766 ;; Should be back at global-params.
1767 (forward-char 1)
1768 (or (looking-at (replace-regexp-in-string "1" "[0-9]+"
1769 ses-initial-global-parameters))
1770 (error "Problem with column-defs or global-params"))
1771 ;; Check for overall newline count in definitions area.
1772 (forward-line 3)
1773 (let ((start (point)))
1774 (ses-goto-data 'ses--numrows)
1775 (or (= (point) start)
1776 (error "Extraneous newlines someplace?"))))
1778 (defun ses-setup ()
1779 "Set up for display of only the printed cell values.
1781 Narrows the buffer to show only the print area. Gives it `read-only' and
1782 `intangible' properties. Sets up highlighting for current cell."
1783 (interactive)
1784 (let ((end (point-min))
1785 (inhibit-read-only t)
1786 (inhibit-point-motion-hooks t)
1787 (was-modified (buffer-modified-p))
1788 pos sym)
1789 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1790 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1791 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1792 ;; The print area is read-only (except for our special commands) and uses a
1793 ;; special keymap.
1794 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1795 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1796 ;; For the beginning of the buffer, we want the read-only and keymap
1797 ;; attributes to be inherited from the first character.
1798 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1799 ;; Create intangible properties, which also indicate which cell the text
1800 ;; came from.
1801 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1802 (dotimes (col ses--numcols)
1803 (setq pos end
1804 sym (ses-cell-symbol row col))
1805 ;; Include skipped cells following this one.
1806 (while (and (< col (1- ses--numcols))
1807 (eq (ses-cell-value row (1+ col)) '*skip*))
1808 (setq end (+ end (ses-col-width col) 1)
1809 col (1+ col)))
1810 (setq end (save-excursion
1811 (goto-char pos)
1812 (move-to-column (+ (current-column) (- end pos)
1813 (ses-col-width col)))
1814 (if (eolp)
1815 (+ end (ses-col-width col) 1)
1816 (forward-char)
1817 (point))))
1818 (put-text-property pos end 'intangible sym)))
1819 ;; Adding these properties did not actually alter the text.
1820 (unless was-modified
1821 (restore-buffer-modified-p nil)
1822 (buffer-disable-undo)
1823 (buffer-enable-undo)))
1824 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1825 ;; because column A must be at least 1 column wide.
1826 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1827 (overlay-put ses--curcell-overlay 'face 'underline))
1829 (defun ses-cleanup ()
1830 "Cleanup when changing a buffer from SES mode to something else.
1831 Delete overlays, remove special text properties."
1832 (widen)
1833 (let ((inhibit-read-only t)
1834 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1835 ;; user "the file is modified, do you really want to make modifications
1836 ;; to this buffer", where the "modifications" refer to the irrelevant
1837 ;; set-text-properties below.
1838 (buffer-file-name nil)
1839 (was-modified (buffer-modified-p)))
1840 ;; Delete read-only, keymap, and intangible properties.
1841 (set-text-properties (point-min) (point-max) nil)
1842 ;; Delete overlay.
1843 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1844 (unless was-modified
1845 (restore-buffer-modified-p nil))))
1847 ;;;###autoload
1848 (defun ses-mode ()
1849 "Major mode for Simple Emacs Spreadsheet.
1850 See \"ses-example.ses\" (in `data-directory') for more info.
1852 Key definitions:
1853 \\{ses-mode-map}
1854 These key definitions are active only in the print area (the visible part):
1855 \\{ses-mode-print-map}
1856 These are active only in the minibuffer, when entering or editing a formula:
1857 \\{ses-mode-edit-map}"
1858 (interactive)
1859 (unless (and (boundp 'ses--deferred-narrow)
1860 (eq ses--deferred-narrow 'ses-mode))
1861 (kill-all-local-variables)
1862 (ses-set-localvars)
1863 (setq major-mode 'ses-mode
1864 mode-name "SES"
1865 next-line-add-newlines nil
1866 truncate-lines t
1867 ;; SES deliberately puts lots of trailing whitespace in its buffer.
1868 show-trailing-whitespace nil
1869 ;; Cell ranges do not work reasonably without this.
1870 transient-mark-mode t
1871 ;; Not to use tab characters for safe (tabs may do bad for column
1872 ;; calculation).
1873 indent-tabs-mode nil)
1874 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1875 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1876 (setq header-line-format '(:eval (progn
1877 (when (/= (window-hscroll)
1878 ses--header-hscroll)
1879 ;; Reset ses--header-hscroll first,
1880 ;; to avoid recursion problems when
1881 ;; debugging ses-create-header-string
1882 (setq ses--header-hscroll
1883 (window-hscroll))
1884 (ses-create-header-string))
1885 ses--header-string)))
1886 (let ((was-empty (zerop (buffer-size)))
1887 (was-modified (buffer-modified-p)))
1888 (save-excursion
1889 (if was-empty
1890 ;; Initialize buffer to contain one cell, for now.
1891 (insert ses-initial-file-contents))
1892 (ses-load)
1893 (ses-setup))
1894 (when was-empty
1895 (unless (equal ses-initial-default-printer
1896 (1value ses--default-printer))
1897 (1value (ses-read-default-printer ses-initial-default-printer)))
1898 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1899 (1value (ses-set-column-width 0 ses-initial-column-width)))
1900 (ses-set-curcell)
1901 (if (> (car ses-initial-size) (1value ses--numrows))
1902 (1value (ses-insert-row (1- (car ses-initial-size)))))
1903 (if (> (cdr ses-initial-size) (1value ses--numcols))
1904 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1905 (ses-write-cells)
1906 (restore-buffer-modified-p was-modified)
1907 (buffer-disable-undo)
1908 (buffer-enable-undo)
1909 (goto-char (point-min))))
1910 (use-local-map ses-mode-map)
1911 ;; Set the deferred narrowing flag (we can't narrow until after
1912 ;; after-find-file completes). If .ses is on the auto-load alist and the
1913 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
1914 ;; special flag to detect this (will be reset by ses-command-hook). For
1915 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
1916 ;; so use an idle timer to make sure.
1917 (setq ses--deferred-narrow 'ses-mode)
1918 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1919 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1920 (run-mode-hooks 'ses-mode-hook)))
1922 (put 'ses-mode 'mode-class 'special)
1924 (defun ses-command-hook ()
1925 "Invoked from `post-command-hook'. If point has moved to a different cell,
1926 moves the underlining overlay. Performs any recalculations or cell-data
1927 writes that have been deferred. If buffer-narrowing has been deferred,
1928 narrows the buffer now."
1929 (condition-case err
1930 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
1931 (when ses--deferred-recalc
1932 ;; We reset the deferred list before starting on the recalc --- in
1933 ;; case of error, we don't want to retry the recalc after every
1934 ;; keystroke!
1935 (ses-initialize-Dijkstra-attempt)
1936 (let ((old ses--deferred-recalc))
1937 (setq ses--deferred-recalc nil)
1938 (ses-update-cells old)))
1939 (when ses--deferred-write
1940 ;; We don't reset the deferred list before starting --- the most
1941 ;; likely error is keyboard-quit, and we do want to keep trying these
1942 ;; writes after a quit.
1943 (ses-write-cells)
1944 (push '(apply ses-widen) buffer-undo-list))
1945 (when ses--deferred-narrow
1946 ;; We're not allowed to narrow the buffer until after-find-file has
1947 ;; read the local variables at the end of the file. Now it's safe to
1948 ;; do the narrowing.
1949 (narrow-to-region (point-min) ses--data-marker)
1950 (setq ses--deferred-narrow nil))
1951 ;; Update the mode line.
1952 (let ((oldcell ses--curcell))
1953 (ses-set-curcell)
1954 (unless (eq ses--curcell oldcell)
1955 (cond
1956 ((not ses--curcell)
1957 (setq mode-line-process nil))
1958 ((atom ses--curcell)
1959 (setq mode-line-process (list " cell "
1960 (symbol-name ses--curcell))))
1962 (setq mode-line-process (list " range "
1963 (symbol-name (car ses--curcell))
1965 (symbol-name (cdr ses--curcell))))))
1966 (force-mode-line-update)))
1967 ;; Use underline overlay for single-cells only, turn off otherwise.
1968 (if (listp ses--curcell)
1969 (move-overlay ses--curcell-overlay 2 2)
1970 (let ((next (next-single-property-change (point) 'intangible)))
1971 (move-overlay ses--curcell-overlay (point) (1- next))))
1972 (when (not (pos-visible-in-window-p))
1973 ;; Scrolling will happen later.
1974 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1975 (setq ses--curcell t)))
1976 ;; Prevent errors in this post-command-hook from silently erasing the hook!
1977 (error
1978 (unless executing-kbd-macro
1979 (ding))
1980 (message "%s" (error-message-string err))))
1981 nil) ; Make coverage-tester happy.
1983 (defun ses-create-header-string ()
1984 "Set up `ses--header-string' as the buffer's header line.
1985 Based on the current set of columns and `window-hscroll' position."
1986 (let ((totwidth (- (window-hscroll)))
1987 result width x)
1988 ;; Leave room for the left-side fringe and scrollbar.
1989 (push (propertize " " 'display '((space :align-to 0))) result)
1990 (dotimes (col ses--numcols)
1991 (setq width (ses-col-width col)
1992 totwidth (+ totwidth width 1))
1993 (if (= totwidth 1)
1994 ;; Scrolled so intercolumn space is leftmost.
1995 (push " " result))
1996 (when (> totwidth 1)
1997 (if (> ses--header-row 0)
1998 (save-excursion
1999 (ses-goto-print (1- ses--header-row) col)
2000 (setq x (buffer-substring-no-properties (point)
2001 (+ (point) width)))
2002 ;; Strip trailing space.
2003 (if (string-match "[ \t]+\\'" x)
2004 (setq x (substring x 0 (match-beginning 0))))
2005 ;; Cut off excess text.
2006 (if (>= (length x) totwidth)
2007 (setq x (substring x 0 (- totwidth -1)))))
2008 (setq x (ses-column-letter col)))
2009 (push (propertize x 'face ses-box-prop) result)
2010 (push (propertize "."
2011 'display `((space :align-to ,(1- totwidth)))
2012 'face ses-box-prop)
2013 result)
2014 ;; Allow the following space to be squished to make room for the 3-D box
2015 ;; Coverage test ignores properties, thinks this is always a space!
2016 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2017 result)))
2018 (if (> ses--header-row 0)
2019 (push (propertize (format " [row %d]" ses--header-row)
2020 'display '((height (- 1))))
2021 result))
2022 (setq ses--header-string (apply 'concat (nreverse result)))))
2025 ;;----------------------------------------------------------------------------
2026 ;; Redisplay and recalculation
2027 ;;----------------------------------------------------------------------------
2029 (defun ses-jump (sym)
2030 "Move point to cell SYM."
2031 (interactive "SJump to cell: ")
2032 (let ((rowcol (ses-sym-rowcol sym)))
2033 (or rowcol (error "Invalid cell name"))
2034 (if (eq (symbol-value sym) '*skip*)
2035 (error "Cell is covered by preceding cell"))
2036 (ses-goto-print (car rowcol) (cdr rowcol))))
2038 (defun ses-jump-safe (cell)
2039 "Like `ses-jump', but no error if invalid cell."
2040 (condition-case nil
2041 (ses-jump cell)
2042 (error)))
2044 (defun ses-reprint-all (&optional nonarrow)
2045 "Recreate the display area. Calls all printer functions. Narrows to
2046 print area if NONARROW is nil."
2047 (interactive "*P")
2048 (widen)
2049 (unless nonarrow
2050 (setq ses--deferred-narrow t))
2051 (let ((startcell (get-text-property (point) 'intangible))
2052 (inhibit-read-only t))
2053 (ses-begin-change)
2054 (goto-char (point-min))
2055 (search-forward ses-print-data-boundary)
2056 (backward-char (length ses-print-data-boundary))
2057 (delete-region (point-min) (point))
2058 ;; Insert all blank lines before printing anything, so ses-print-cell can
2059 ;; find the data area when inserting or deleting *skip* values for cells.
2060 (dotimes (row ses--numrows)
2061 (insert-and-inherit ses--blank-line))
2062 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2063 (if (eq (ses-cell-value row 0) '*skip*)
2064 ;; Column deletion left a dangling skip.
2065 (ses-set-cell row 0 'value nil))
2066 (dotimes (col ses--numcols)
2067 (ses-print-cell row col))
2068 (beginning-of-line 2))
2069 (ses-jump-safe startcell)))
2071 (defun ses-initialize-Dijkstra-attempt ()
2072 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2073 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2075 (defun ses-recalculate-cell ()
2076 "Recalculate and reprint the current cell or range.
2078 For an individual cell, shows the error if the formula or printer
2079 signals one, or otherwise shows the cell's complete value. For a range, the
2080 cells are recalculated in \"natural\" order, so cells that other cells refer
2081 to are recalculated first."
2082 (interactive "*")
2083 (ses-check-curcell 'range)
2084 (ses-begin-change)
2085 (ses-initialize-Dijkstra-attempt)
2086 (let (sig cur-rowcol)
2087 (setq ses-start-time (float-time))
2088 (if (atom ses--curcell)
2089 (when
2090 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2091 sig (progn
2092 (ses-cell-property-set :ses-Dijkstra-attempt
2093 (cons ses--Dijkstra-attempt-nb 0)
2094 (car cur-rowcol) (cdr cur-rowcol) )
2095 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2096 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2097 (cdr cur-rowcol)))))
2098 ;; First, recalculate all cells that don't refer to other cells and
2099 ;; produce a list of cells with references.
2100 (ses-dorange ses--curcell
2101 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
2102 (condition-case nil
2103 (progn
2104 ;; The t causes an error if the cell has references. If no
2105 ;; references, the t will be the result value.
2106 (1value (ses-formula-references (ses-cell-formula row col) t))
2107 (ses-cell-property-set :ses-Dijkstra-attempt
2108 (cons ses--Dijkstra-attempt-nb 0)
2109 row col)
2110 (when (setq sig (ses-calculate-cell row col t))
2111 (nconc sig (list (ses-cell-symbol row col)))))
2112 (wrong-type-argument
2113 ;; The formula contains a reference.
2114 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
2115 ;; Do the update now, so we can force recalculation.
2116 (let ((x ses--deferred-recalc))
2117 (setq ses--deferred-recalc nil)
2118 (condition-case hold
2119 (ses-update-cells x t)
2120 (error (setq sig hold))))
2121 (cond
2122 (sig
2123 (message "%s" (error-message-string sig)))
2124 ((consp ses--curcell)
2125 (message " "))
2127 (princ (symbol-value ses--curcell))))))
2129 (defun ses-recalculate-all ()
2130 "Recalculate and reprint all cells."
2131 (interactive "*")
2132 (let ((startcell (get-text-property (point) 'intangible))
2133 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2134 (1- ses--numcols)))))
2135 (ses-recalculate-cell)
2136 (ses-jump-safe startcell)))
2138 (defun ses-truncate-cell ()
2139 "Reprint current cell, but without spillover into any following blank cells."
2140 (interactive "*")
2141 (ses-check-curcell)
2142 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2143 (row (car rowcol))
2144 (col (cdr rowcol)))
2145 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
2146 (eq (ses-cell-value row (1+ col)) '*skip*))
2147 ;; This cell has spill-over. We'll momentarily pretend the following cell
2148 ;; has a `t' in it.
2149 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
2150 (ses-print-cell row col)))
2151 ;; Now remove the *skip*. ses-print-cell is always nil here.
2152 (ses-set-cell row (1+ col) 'value nil)
2153 (1value (ses-print-cell row (1+ col))))))
2155 (defun ses-reconstruct-all ()
2156 "Reconstruct buffer based on cell data stored in Emacs variables."
2157 (interactive "*")
2158 (ses-begin-change)
2159 ;;Reconstruct reference lists.
2160 (let (x yrow ycol)
2161 ;;Delete old reference lists
2162 (dotimes-with-progress-reporter
2163 (row ses--numrows) "Deleting references..."
2164 (dotimes (col ses--numcols)
2165 (ses-set-cell row col 'references nil)))
2166 ;;Create new reference lists
2167 (dotimes-with-progress-reporter
2168 (row ses--numrows) "Computing references..."
2169 (dotimes (col ses--numcols)
2170 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2171 (setq x (ses-sym-rowcol ref)
2172 yrow (car x)
2173 ycol (cdr x))
2174 (ses-set-cell yrow ycol 'references
2175 (cons (ses-cell-symbol row col)
2176 (ses-cell-references yrow ycol)))))))
2177 ;; Delete everything and reconstruct basic data area.
2178 (ses-widen)
2179 (let ((inhibit-read-only t))
2180 (goto-char (point-max))
2181 (if (search-backward ";; Local Variables:\n" nil t)
2182 (delete-region (point-min) (point))
2183 ;; Buffer is quite screwed up --- can't even save the user-specified
2184 ;; locals.
2185 (delete-region (point-min) (point-max))
2186 (insert ses-initial-file-trailer)
2187 (goto-char (point-min)))
2188 ;; Create a blank display area.
2189 (dotimes (row ses--numrows)
2190 (insert ses--blank-line))
2191 (insert ses-print-data-boundary)
2192 (backward-char (1- (length ses-print-data-boundary)))
2193 (setq ses--data-marker (point-marker))
2194 (forward-char (1- (length ses-print-data-boundary)))
2195 ;; Placeholders for cell data.
2196 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2197 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
2198 (insert "\n\n\n\n")
2199 (insert ses-initial-global-parameters)
2200 (backward-char (1- (length ses-initial-global-parameters)))
2201 (setq ses--params-marker (point-marker))
2202 (forward-char (1- (length ses-initial-global-parameters))))
2203 (ses-set-parameter 'ses--col-widths ses--col-widths)
2204 (ses-set-parameter 'ses--col-printers ses--col-printers)
2205 (ses-set-parameter 'ses--default-printer ses--default-printer)
2206 (ses-set-parameter 'ses--header-row ses--header-row)
2207 (ses-set-parameter 'ses--numrows ses--numrows)
2208 (ses-set-parameter 'ses--numcols ses--numcols)
2209 ;;Keep our old narrowing
2210 (ses-setup)
2211 (ses-recalculate-all)
2212 (goto-char (point-min)))
2215 ;;----------------------------------------------------------------------------
2216 ;; Input of cell formulas
2217 ;;----------------------------------------------------------------------------
2219 (defun ses-edit-cell (row col newval)
2220 "Display current cell contents in minibuffer, for editing. Returns nil if
2221 cell formula was unsafe and user declined confirmation."
2222 (interactive
2223 (progn
2224 (barf-if-buffer-read-only)
2225 (ses-check-curcell)
2226 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2227 (row (car rowcol))
2228 (col (cdr rowcol))
2229 (formula (ses-cell-formula row col))
2230 initial)
2231 (if (eq (car-safe formula) 'ses-safe-formula)
2232 (setq formula (cadr formula)))
2233 (if (eq (car-safe formula) 'quote)
2234 (setq initial (format "'%S" (cadr formula)))
2235 (setq initial (prin1-to-string formula)))
2236 (if (stringp formula)
2237 ;; Position cursor inside close-quote.
2238 (setq initial (cons initial (length initial))))
2239 (list row col
2240 (read-from-minibuffer (format "Cell %s: " ses--curcell)
2241 initial
2242 ses-mode-edit-map
2243 t ; Convert to Lisp object.
2244 'ses-read-cell-history)))))
2245 (when (ses-warn-unsafe newval 'unsafep)
2246 (ses-begin-change)
2247 (ses-cell-set-formula row col newval)
2250 (defun ses-read-cell (row col newval)
2251 "Self-insert for initial character of cell function."
2252 (interactive
2253 (let* ((initial (this-command-keys))
2254 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2255 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
2256 (barf-if-buffer-read-only)
2257 (list (car rowcol)
2258 (cdr rowcol)
2259 (read-from-minibuffer
2260 (format "Cell %s: " ses--curcell)
2261 (cons (if (equal initial "\"") "\"\""
2262 (if (equal initial "(") "()" initial)) 2)
2263 ses-mode-edit-map
2264 t ; Convert to Lisp object.
2265 'ses-read-cell-history
2266 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2267 (cadr curval)
2268 curval))))))
2269 (when (ses-edit-cell row col newval)
2270 (ses-command-hook) ; Update cell widths before movement.
2271 (dolist (x ses-after-entry-functions)
2272 (funcall x 1))))
2274 (defun ses-read-symbol (row col symb)
2275 "Self-insert for a symbol as a cell formula. The set of all symbols that
2276 have been used as formulas in this spreadsheet is available for completions."
2277 (interactive
2278 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2279 newval)
2280 (barf-if-buffer-read-only)
2281 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2282 ses--symbolic-formulas))
2283 (list (car rowcol)
2284 (cdr rowcol)
2285 (if (string= newval "")
2286 nil ; Don't create zero-length symbols!
2287 (list 'quote (intern newval))))))
2288 (when (ses-edit-cell row col symb)
2289 (ses-command-hook) ; Update cell widths before movement.
2290 (dolist (x ses-after-entry-functions)
2291 (funcall x 1))))
2293 (defun ses-clear-cell-forward (count)
2294 "Delete formula and printer for current cell and then move to next cell.
2295 With prefix, deletes several cells."
2296 (interactive "*p")
2297 (if (< count 0)
2298 (1value (ses-clear-cell-backward (- count)))
2299 (ses-check-curcell)
2300 (ses-begin-change)
2301 (dotimes (x count)
2302 (ses-set-curcell)
2303 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2304 (or rowcol (signal 'end-of-buffer nil))
2305 (ses-clear-cell (car rowcol) (cdr rowcol)))
2306 (forward-char 1))))
2308 (defun ses-clear-cell-backward (count)
2309 "Move to previous cell and then delete it. With prefix, deletes several
2310 cells."
2311 (interactive "*p")
2312 (if (< count 0)
2313 (1value (ses-clear-cell-forward (- count)))
2314 (ses-check-curcell 'end)
2315 (ses-begin-change)
2316 (dotimes (x count)
2317 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
2318 (ses-set-curcell)
2319 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2320 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2323 ;;----------------------------------------------------------------------------
2324 ;; Input of cell-printer functions
2325 ;;----------------------------------------------------------------------------
2327 (defun ses-read-printer (prompt default)
2328 "Common code for `ses-read-cell-printer', `ses-read-column-printer', and `ses-read-default-printer'.
2329 PROMPT should end with \": \". Result is t if operation was canceled."
2330 (barf-if-buffer-read-only)
2331 (if (eq default t)
2332 (setq default "")
2333 (setq prompt (format "%s [currently %S]: "
2334 (substring prompt 0 -2)
2335 default)))
2336 (let ((new (read-from-minibuffer prompt
2337 nil ; Initial contents.
2338 ses-mode-edit-map
2339 t ; Evaluate the result.
2340 'ses-read-printer-history
2341 (prin1-to-string default))))
2342 (if (equal new default)
2343 ;; User changed mind, decided not to change printer.
2344 (setq new t)
2345 (ses-printer-validate new)
2346 (or (not new)
2347 (stringp new)
2348 (stringp (car-safe new))
2349 (ses-warn-unsafe new 'unsafep-function)
2350 (setq new t)))
2351 new))
2353 (defun ses-read-cell-printer (newval)
2354 "Set the printer function for the current cell or range.
2356 A printer function is either a string (a format control-string with one
2357 %-sequence -- result from format will be right-justified), or a list of one
2358 string (result from format will be left-justified), or a lambda-expression of
2359 one argument, or a symbol that names a function of one argument. In the
2360 latter two cases, the function's result should be either a string (will be
2361 right-justified) or a list of one string (will be left-justified)."
2362 (interactive
2363 (let ((default t)
2365 (ses-check-curcell 'range)
2366 ;;Default is none if not all cells in range have same printer
2367 (catch 'ses-read-cell-printer
2368 (ses-dorange ses--curcell
2369 (setq x (ses-cell-printer row col))
2370 (if (eq (car-safe x) 'ses-safe-printer)
2371 (setq x (cadr x)))
2372 (if (eq default t)
2373 (setq default x)
2374 (unless (equal default x)
2375 ;;Range contains differing printer functions
2376 (setq default t)
2377 (throw 'ses-read-cell-printer t)))))
2378 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2379 default))))
2380 (unless (eq newval t)
2381 (ses-begin-change)
2382 (ses-dorange ses--curcell
2383 (ses-set-cell row col 'printer newval)
2384 (ses-print-cell row col))))
2386 (defun ses-read-column-printer (col newval)
2387 "Set the printer function for the current column.
2388 See `ses-read-cell-printer' for input forms."
2389 (interactive
2390 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2391 (ses-check-curcell)
2392 (list col (ses-read-printer (format "Column %s printer: "
2393 (ses-column-letter col))
2394 (ses-col-printer col)))))
2396 (unless (eq newval t)
2397 (ses-begin-change)
2398 (ses-set-parameter 'ses--col-printers newval col)
2399 (save-excursion
2400 (dotimes (row ses--numrows)
2401 (ses-print-cell row col)))))
2403 (defun ses-read-default-printer (newval)
2404 "Set the default printer function for cells that have no other.
2405 See `ses-read-cell-printer' for input forms."
2406 (interactive
2407 (list (ses-read-printer "Default printer: " ses--default-printer)))
2408 (unless (eq newval t)
2409 (ses-begin-change)
2410 (ses-set-parameter 'ses--default-printer newval)
2411 (ses-reprint-all t)))
2414 ;;----------------------------------------------------------------------------
2415 ;; Spreadsheet size adjustments
2416 ;;----------------------------------------------------------------------------
2418 (defun ses-insert-row (count)
2419 "Insert a new row before the current one.
2420 With prefix, insert COUNT rows before current one."
2421 (interactive "*p")
2422 (ses-check-curcell 'end)
2423 (or (> count 0) (signal 'args-out-of-range nil))
2424 (ses-begin-change)
2425 (let ((inhibit-quit t)
2426 (inhibit-read-only t)
2427 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2428 newrow)
2429 ;;Create a new set of cell-variables
2430 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2431 0 (1- ses--numcols))
2432 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2433 ;;Insert each row
2434 (ses-goto-print row 0)
2435 (dotimes-with-progress-reporter (x count) "Inserting row..."
2436 ;;Create a row of empty cells. The `symbol' fields will be set by
2437 ;;the call to ses-relocate-all.
2438 (setq newrow (make-vector ses--numcols nil))
2439 (dotimes (col ses--numcols)
2440 (aset newrow col (ses-make-cell)))
2441 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2442 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2443 (insert ses--blank-line))
2444 ;;Insert empty lines in cell data area (will be replaced by
2445 ;;ses-relocate-all)
2446 (ses-goto-data row 0)
2447 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2448 (ses-relocate-all row 0 count 0)
2449 ;;If any cell printers insert constant text, insert that text
2450 ;;into the line.
2451 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2452 (global (ses-call-printer ses--default-printer)))
2453 (if (or (> (length cols) 0) (> (length global) 0))
2454 (dotimes (x count)
2455 (dotimes (col ses--numcols)
2456 ;;These cells are always nil, only constant formatting printed
2457 (1value (ses-print-cell (+ x row) col))))))
2458 (when (> ses--header-row row)
2459 ;;Inserting before header
2460 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2461 (ses-reset-header-string)))
2462 ;;Reconstruct text attributes
2463 (ses-setup)
2464 ;;Prepare for undo
2465 (push '(apply ses-widen) buffer-undo-list)
2466 ;;Return to current cell
2467 (if ses--curcell
2468 (ses-jump-safe ses--curcell)
2469 (ses-goto-print (1- ses--numrows) 0)))
2471 (defun ses-delete-row (count)
2472 "Delete the current row.
2473 With prefix, deletes COUNT rows starting from the current one."
2474 (interactive "*p")
2475 (ses-check-curcell)
2476 (or (> count 0) (signal 'args-out-of-range nil))
2477 (let ((inhibit-quit t)
2478 (inhibit-read-only t)
2479 (row (car (ses-sym-rowcol ses--curcell))))
2480 (setq count (min count (- ses--numrows row)))
2481 (ses-begin-change)
2482 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2483 ;;Delete lines from print area
2484 (ses-goto-print row 0)
2485 (ses-delete-line count)
2486 ;;Delete lines from cell data area
2487 (ses-goto-data row 0)
2488 (ses-delete-line (* count (1+ ses--numcols)))
2489 ;;Relocate variables and formulas
2490 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2491 (ses-relocate-all row 0 (- count) 0)
2492 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2493 0 (1- ses--numcols))
2494 (when (> ses--header-row row)
2495 (if (<= ses--header-row (+ row count))
2496 ;;Deleting the header row
2497 (ses-set-parameter 'ses--header-row 0)
2498 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2499 (ses-reset-header-string)))
2500 ;;Reconstruct attributes
2501 (ses-setup)
2502 ;;Prepare for undo
2503 (push '(apply ses-widen) buffer-undo-list)
2504 (ses-jump-safe ses--curcell))
2506 (defun ses-insert-column (count &optional col width printer)
2507 "Insert a new column before COL (default is the current one).
2508 With prefix, insert COUNT columns before current one.
2509 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2510 \(otherwise they're taken from the current column)."
2511 (interactive "*p")
2512 (ses-check-curcell)
2513 (or (> count 0) (signal 'args-out-of-range nil))
2514 (or col
2515 (setq col (cdr (ses-sym-rowcol ses--curcell))
2516 width (ses-col-width col)
2517 printer (ses-col-printer col)))
2518 (ses-begin-change)
2519 (let ((inhibit-quit t)
2520 (inhibit-read-only t)
2521 (widths ses--col-widths)
2522 (printers ses--col-printers)
2523 has-skip)
2524 ;;Create a new set of cell-variables
2525 (ses-create-cell-variable-range 0 (1- ses--numrows)
2526 ses--numcols (+ ses--numcols count -1))
2527 ;;Insert each column.
2528 (dotimes-with-progress-reporter (x count) "Inserting column..."
2529 ;;Create a column of empty cells. The `symbol' fields will be set by
2530 ;;the call to ses-relocate-all.
2531 (ses-adjust-print-width col (1+ width))
2532 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2533 (dotimes (row ses--numrows)
2534 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2535 ;;Inserting in the middle of a spill-over
2536 (setq has-skip t))
2537 (ses-aset-with-undo ses--cells row
2538 (ses-vector-insert (aref ses--cells row)
2539 col (ses-make-cell)))
2540 ;;Insert empty lines in cell data area (will be replaced by
2541 ;;ses-relocate-all)
2542 (ses-goto-data row col)
2543 (insert ?\n))
2544 ;; Insert column width and printer.
2545 (setq widths (ses-vector-insert widths col width)
2546 printers (ses-vector-insert printers col printer)))
2547 (ses-set-parameter 'ses--col-widths widths)
2548 (ses-set-parameter 'ses--col-printers printers)
2549 (ses-reset-header-string)
2550 (ses-relocate-all 0 col 0 count)
2551 (if has-skip
2552 (ses-reprint-all t)
2553 (when (or (> (length (ses-call-printer printer)) 0)
2554 (> (length (ses-call-printer ses--default-printer)) 0))
2555 ;; Either column printer or global printer inserts some constant text.
2556 ;; Reprint the new columns to insert that text.
2557 (dotimes (x ses--numrows)
2558 (dotimes (y count)
2559 ;; Always nil here --- this is a blank column.
2560 (1value (ses-print-cell-new-width x (+ y col))))))
2561 (ses-setup)))
2562 (ses-jump-safe ses--curcell))
2564 (defun ses-delete-column (count)
2565 "Delete the current column.
2566 With prefix, deletes COUNT columns starting from the current one."
2567 (interactive "*p")
2568 (ses-check-curcell)
2569 (or (> count 0) (signal 'args-out-of-range nil))
2570 (let ((inhibit-quit t)
2571 (inhibit-read-only t)
2572 (rowcol (ses-sym-rowcol ses--curcell))
2573 (width 0)
2574 col origrow has-skip)
2575 (setq origrow (car rowcol)
2576 col (cdr rowcol)
2577 count (min count (- ses--numcols col)))
2578 (if (= count ses--numcols)
2579 (error "Can't delete all columns!"))
2580 ;;Determine width of column(s) being deleted
2581 (dotimes (x count)
2582 (setq width (+ width (ses-col-width (+ col x)) 1)))
2583 (ses-begin-change)
2584 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2585 (ses-adjust-print-width col (- width))
2586 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2587 ;;Delete lines from cell data area
2588 (ses-goto-data row col)
2589 (ses-delete-line count)
2590 ;;Delete cells. Check if deletion area begins or ends with a skip.
2591 (if (or (eq (ses-cell-value row col) '*skip*)
2592 (and (< col ses--numcols)
2593 (eq (ses-cell-value row (+ col count)) '*skip*)))
2594 (setq has-skip t))
2595 (ses-aset-with-undo ses--cells row
2596 (ses-vector-delete (aref ses--cells row) col count)))
2597 ;;Update globals
2598 (ses-set-parameter 'ses--col-widths
2599 (ses-vector-delete ses--col-widths col count))
2600 (ses-set-parameter 'ses--col-printers
2601 (ses-vector-delete ses--col-printers col count))
2602 (ses-reset-header-string)
2603 ;;Relocate variables and formulas
2604 (ses-relocate-all 0 col 0 (- count))
2605 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2606 ses--numcols (+ ses--numcols count -1))
2607 (if has-skip
2608 (ses-reprint-all t)
2609 (ses-setup))
2610 (if (>= col ses--numcols)
2611 (setq col (1- col)))
2612 (ses-goto-print origrow col)))
2614 (defun ses-forward-or-insert (&optional count)
2615 "Move to next cell in row, or inserts a new cell if already in last one, or
2616 inserts a new row if at bottom of print area. Repeat COUNT times."
2617 (interactive "p")
2618 (ses-check-curcell 'end)
2619 (setq deactivate-mark t) ; Doesn't combine well with ranges.
2620 (dotimes (x count)
2621 (ses-set-curcell)
2622 (if (not ses--curcell)
2623 (progn ; At bottom of print area.
2624 (barf-if-buffer-read-only)
2625 (ses-insert-row 1))
2626 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2627 (when (/= 32
2628 (char-before (next-single-property-change (point)
2629 'intangible)))
2630 ;; We're already in last nonskipped cell on line. Need to create a
2631 ;; new column.
2632 (barf-if-buffer-read-only)
2633 (ses-insert-column (- count x)
2634 ses--numcols
2635 (ses-col-width col)
2636 (ses-col-printer col)))))
2637 (forward-char)))
2639 (defun ses-append-row-jump-first-column ()
2640 "Insert a new row after current one and jump to its first column."
2641 (interactive "*")
2642 (ses-check-curcell)
2643 (ses-begin-change)
2644 (beginning-of-line 2)
2645 (ses-set-curcell)
2646 (ses-insert-row 1))
2648 (defun ses-set-column-width (col newwidth)
2649 "Set the width of the current column."
2650 (interactive
2651 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2652 (barf-if-buffer-read-only)
2653 (list col
2654 (if current-prefix-arg
2655 (prefix-numeric-value current-prefix-arg)
2656 (read-from-minibuffer (format "Column %s width [currently %d]: "
2657 (ses-column-letter col)
2658 (ses-col-width col))
2659 nil ; No initial contents.
2660 nil ; No override keymap.
2661 t ; Convert to Lisp object.
2662 nil ; No history.
2663 (number-to-string
2664 (ses-col-width col))))))) ; Default value.
2665 (if (< newwidth 1)
2666 (error "Invalid column width"))
2667 (ses-begin-change)
2668 (ses-reset-header-string)
2669 (save-excursion
2670 (let ((inhibit-quit t))
2671 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2672 (ses-set-parameter 'ses--col-widths newwidth col))
2673 (dotimes (row ses--numrows)
2674 (ses-print-cell-new-width row col))))
2677 ;;----------------------------------------------------------------------------
2678 ;; Cut and paste, import and export
2679 ;;----------------------------------------------------------------------------
2681 (defadvice copy-region-as-kill (around ses-copy-region-as-kill
2682 activate preactivate)
2683 "It doesn't make sense to copy read-only or intangible attributes into the
2684 kill ring. It probably doesn't make sense to copy keymap properties.
2685 We'll assume copying front-sticky properties doesn't make sense, either.
2687 This advice also includes some SES-specific code because otherwise it's too
2688 hard to override how mouse-1 works."
2689 (when (> beg end)
2690 (let ((temp beg))
2691 (setq beg end
2692 end temp)))
2693 (if (not (and (eq major-mode 'ses-mode)
2694 (eq (get-text-property beg 'read-only) 'ses)
2695 (eq (get-text-property (1- end) 'read-only) 'ses)))
2696 ad-do-it ; Normal copy-region-as-kill.
2697 (kill-new (ses-copy-region beg end))
2698 (if transient-mark-mode
2699 (setq deactivate-mark t))
2700 nil))
2702 (defun ses-copy-region (beg end)
2703 "Treat the region as rectangular. Convert the intangible attributes to
2704 SES attributes recording the contents of the cell as of the time of copying."
2705 (when (= end ses--data-marker)
2706 ;;Avoid overflow situation
2707 (setq end (1- ses--data-marker)))
2708 (let* ((inhibit-point-motion-hooks t)
2709 (x (mapconcat 'ses-copy-region-helper
2710 (extract-rectangle beg (1- end)) "\n")))
2711 (remove-text-properties 0 (length x)
2712 '(read-only t
2713 intangible t
2714 keymap t
2715 front-sticky t)
2719 (defun ses-copy-region-helper (line)
2720 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2721 external form by attaching to each print cell a 'ses attribute that records
2722 the corresponding data cell."
2723 (or (> (length line) 1)
2724 (error "Empty range"))
2725 (let ((inhibit-read-only t)
2726 (pos 0)
2727 mycell next sym rowcol)
2728 (while pos
2729 (setq sym (get-text-property pos 'intangible line)
2730 next (next-single-property-change pos 'intangible line)
2731 rowcol (ses-sym-rowcol sym)
2732 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2733 (put-text-property pos (or next (length line))
2734 'ses
2735 (list (ses-cell-symbol mycell)
2736 (ses-cell-formula mycell)
2737 (ses-cell-printer mycell))
2738 line)
2739 (setq pos next)))
2740 line)
2742 (defun ses-kill-override (beg end)
2743 "Generic override for any commands that kill text.
2744 We clear the killed cells instead of deleting them."
2745 (interactive "r")
2746 (ses-check-curcell 'needrange)
2747 ;; For some reason, the text-read-only error is not caught by `delete-region',
2748 ;; so we have to use subterfuge.
2749 (let ((buffer-read-only t))
2750 (1value (condition-case x
2751 (noreturn (funcall (lookup-key (current-global-map)
2752 (this-command-keys))
2753 beg end))
2754 (buffer-read-only nil)))) ; The expected error.
2755 ;; Because the buffer was marked read-only, the kill command turned itself
2756 ;; into a copy. Now we clear the cells or signal the error. First we check
2757 ;; whether the buffer really is read-only.
2758 (barf-if-buffer-read-only)
2759 (ses-begin-change)
2760 (ses-dorange ses--curcell
2761 (ses-clear-cell row col))
2762 (ses-jump (car ses--curcell)))
2764 (defadvice yank (around ses-yank activate preactivate)
2765 "In SES mode, the yanked text is inserted as cells.
2767 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2768 SES buffer), the formulas and print functions are restored for the cells. If
2769 the text contains tabs, this is an insertion of tab-separated formulas.
2770 Otherwise the text is inserted as the formula for the current cell.
2772 When inserting cells, the formulas are usually relocated to keep the same
2773 relative references to neighboring cells. This is best if the formulas
2774 generally refer to other cells within the yanked text. You can use the C-u
2775 prefix to specify insertion without relocation, which is best when the
2776 formulas refer to cells outside the yanked text.
2778 When inserting formulas, the text is treated as a string constant if it doesn't
2779 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2780 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2781 as symbols."
2782 (if (not (and (eq major-mode 'ses-mode)
2783 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2784 ad-do-it ; Normal non-SES yank.
2785 (ses-check-curcell 'end)
2786 (push-mark (point))
2787 (let ((text (current-kill (cond
2788 ((listp arg) 0)
2789 ((eq arg '-) -1)
2790 (t (1- arg))))))
2791 (or (ses-yank-cells text arg)
2792 (ses-yank-tsf text arg)
2793 (ses-yank-one (ses-yank-resize 1 1)
2794 text
2796 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2797 ;; Just one cell --- delete final tab or newline.
2798 (1- (length text)))
2799 arg)))
2800 (if (consp arg)
2801 (exchange-point-and-mark))))
2803 (defun ses-yank-pop (arg)
2804 "Replace just-yanked stretch of killed text with a different stretch.
2805 This command is allowed only immediately after a `yank' or a `yank-pop',
2806 when the region contains a stretch of reinserted previously-killed text.
2807 We replace it with a different stretch of killed text.
2808 Unlike standard `yank-pop', this function uses `undo' to delete the
2809 previous insertion."
2810 (interactive "*p")
2811 (or (eq last-command 'yank)
2812 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2813 ;;macro definition.
2814 (noreturn (error "Previous command was not a yank")))
2815 (undo)
2816 (ses-set-curcell)
2817 (yank (1+ (or arg 1)))
2818 (setq this-command 'yank))
2820 (defun ses-yank-cells (text arg)
2821 "If the TEXT has a proper set of 'ses attributes, insert the text as
2822 cells, else return nil. The cells are reprinted--the supplied text is
2823 ignored because the column widths, default printer, etc. at yank time might
2824 be different from those at kill-time. ARG is a list to indicate that
2825 formulas are to be inserted without relocation."
2826 (let ((first (get-text-property 0 'ses text))
2827 (last (get-text-property (1- (length text)) 'ses text)))
2828 (when (and first last) ;;Otherwise not proper set of attributes
2829 (setq first (ses-sym-rowcol (car first))
2830 last (ses-sym-rowcol (car last)))
2831 (let* ((needrows (- (car last) (car first) -1))
2832 (needcols (- (cdr last) (cdr first) -1))
2833 (rowcol (ses-yank-resize needrows needcols))
2834 (rowincr (- (car rowcol) (car first)))
2835 (colincr (- (cdr rowcol) (cdr first)))
2836 (pos 0)
2837 myrow mycol x)
2838 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2839 (setq myrow (+ row (car rowcol)))
2840 (dotimes (col needcols)
2841 (setq mycol (+ col (cdr rowcol))
2842 last (get-text-property pos 'ses text)
2843 pos (next-single-property-change pos 'ses text)
2844 x (ses-sym-rowcol (car last)))
2845 (if (not last)
2846 ;; Newline --- all remaining cells on row are skipped.
2847 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2848 last (list nil nil nil)
2849 pos (1- pos)))
2850 (if (/= (car x) (- myrow rowincr))
2851 (error "Cell row error"))
2852 (if (< (- mycol colincr) (cdr x))
2853 ;; Some columns were skipped.
2854 (let ((oldcol mycol))
2855 (while (< (- mycol colincr) (cdr x))
2856 (ses-clear-cell myrow mycol)
2857 (setq col (1+ col)
2858 mycol (1+ mycol)))
2859 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
2860 (when (car last) ; Skip this for *skip* cells.
2861 (setq x (nth 2 last))
2862 (unless (equal x (ses-cell-printer myrow mycol))
2863 (or (not x)
2864 (stringp x)
2865 (eq (car-safe x) 'ses-safe-printer)
2866 (setq x `(ses-safe-printer ,x)))
2867 (ses-set-cell myrow mycol 'printer x))
2868 (setq x (cadr last))
2869 (if (atom arg)
2870 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2871 (or (atom x)
2872 (eq (car-safe x) 'ses-safe-formula)
2873 (setq x `(ses-safe-formula ,x)))
2874 (ses-cell-set-formula myrow mycol x)))
2875 (when pos
2876 (if (get-text-property pos 'ses text)
2877 (error "Missing newline between rows"))
2878 (setq pos (next-single-property-change pos 'ses text))))
2879 t))))
2881 (defun ses-yank-one (rowcol text from to arg)
2882 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
2883 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
2884 (let ((val (condition-case nil
2885 (read-from-string text from to)
2886 (error (cons nil from)))))
2887 (cond
2888 ((< (cdr val) (or to (length text)))
2889 ;; Invalid sexp --- leave it as a string.
2890 (setq val (substring text from to)))
2891 ((and (car val) (symbolp (car val)))
2892 (if (consp arg)
2893 (setq val (list 'quote (car val))) ; Keep symbol.
2894 (setq val (substring text from to)))) ; Treat symbol as text.
2896 (setq val (car val))))
2897 (let ((row (car rowcol))
2898 (col (cdr rowcol)))
2899 (or (atom val)
2900 (setq val `(ses-safe-formula ,val)))
2901 (ses-cell-set-formula row col val))))
2903 (defun ses-yank-tsf (text arg)
2904 "If TEXT contains tabs and/or newlines, treat the tabs as
2905 column-separators and the newlines as row-separators and insert the text as
2906 cell formulas--else return nil. Treat plain symbols as strings unless ARG
2907 is a list. Ignore a final newline."
2908 (if (or (not (string-match "[\t\n]" text))
2909 (= (match-end 0) (length text)))
2910 ;;Not TSF format
2912 (if (/= (aref text (1- (length text))) ?\n)
2913 (setq text (concat text "\n")))
2914 (let ((pos -1)
2915 (spots (list -1))
2916 (cols 0)
2917 (needrows 0)
2918 needcols rowcol)
2919 ;;Find all the tabs and newlines
2920 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
2921 (push pos spots)
2922 (setq cols (1+ cols))
2923 (when (eq (aref text pos) ?\n)
2924 (if (not needcols)
2925 (setq needcols cols)
2926 (or (= needcols cols)
2927 (error "Inconsistent row lengths")))
2928 (setq cols 0
2929 needrows (1+ needrows))))
2930 ;;Insert the formulas
2931 (setq rowcol (ses-yank-resize needrows needcols))
2932 (dotimes (row needrows)
2933 (dotimes (col needcols)
2934 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
2935 (+ (cdr rowcol) needcols (- col) -1))
2936 text (1+ (cadr spots)) (car spots) arg)
2937 (setq spots (cdr spots))))
2938 (ses-goto-print (+ (car rowcol) needrows -1)
2939 (+ (cdr rowcol) needcols -1))
2940 t)))
2942 (defun ses-yank-resize (needrows needcols)
2943 "If this yank will require inserting rows and/or columns, ask for
2944 confirmation and then insert them. Result is (row,col) for top left of yank
2945 spot, or error signal if user requests cancel."
2946 (ses-begin-change)
2947 (let ((rowcol (if ses--curcell
2948 (ses-sym-rowcol ses--curcell)
2949 (cons ses--numrows 0)))
2950 rowbool colbool)
2951 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
2952 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
2953 rowbool (> needrows 0)
2954 colbool (> needcols 0))
2955 (when (or rowbool colbool)
2956 ;;Need to insert. Get confirm
2957 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
2958 (if rowbool (format "%d rows" needrows) "")
2959 (if (and rowbool colbool) " and " "")
2960 (if colbool (format "%d columns" needcols) "")))
2961 (error "Cancelled"))
2962 (when rowbool
2963 (let (ses--curcell)
2964 (save-excursion
2965 (ses-goto-print ses--numrows 0)
2966 (ses-insert-row needrows))))
2967 (when colbool
2968 (ses-insert-column needcols
2969 ses--numcols
2970 (ses-col-width (1- ses--numcols))
2971 (ses-col-printer (1- ses--numcols)))))
2972 rowcol))
2974 (defun ses-export-tsv (beg end)
2975 "Export values from the current range, with tabs between columns and
2976 newlines between rows. Result is placed in kill ring."
2977 (interactive "r")
2978 (ses-export-tab nil))
2980 (defun ses-export-tsf (beg end)
2981 "Export formulas from the current range, with tabs between columns and
2982 newlines between rows. Result is placed in kill ring."
2983 (interactive "r")
2984 (ses-export-tab t))
2986 (defun ses-export-tab (want-formulas)
2987 "Export the current range with tabs between columns and newlines between rows.
2988 Result is placed in kill ring. The export is values unless WANT-FORMULAS
2989 is non-nil. Newlines and tabs in the export text are escaped."
2990 (ses-check-curcell 'needrange)
2991 (let ((print-escape-newlines t)
2992 result item)
2993 (ses-dorange ses--curcell
2994 (setq item (if want-formulas
2995 (ses-cell-formula row col)
2996 (ses-cell-value row col)))
2997 (if (eq (car-safe item) 'ses-safe-formula)
2998 ;;Hide our deferred safety-check marker
2999 (setq item (cadr item)))
3000 (if (or (not item) (eq item '*skip*))
3001 (setq item ""))
3002 (when (eq (car-safe item) 'quote)
3003 (push "'" result)
3004 (setq item (cadr item)))
3005 (setq item (prin1-to-string item t))
3006 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
3007 (push item result)
3008 (cond
3009 ((< col maxcol)
3010 (push "\t" result))
3011 ((< row maxrow)
3012 (push "\n" result))))
3013 (setq result (apply 'concat (nreverse result)))
3014 (kill-new result)))
3017 ;;----------------------------------------------------------------------------
3018 ;; Other user commands
3019 ;;----------------------------------------------------------------------------
3021 (defun ses-unset-header-row ()
3022 "Select the default header row."
3023 (interactive)
3024 (ses-set-header-row 0))
3026 (defun ses-set-header-row (row)
3027 "Set the ROW to display in the header-line.
3028 With a numerical prefix arg, use that row.
3029 With no prefix arg, use the current row.
3030 With a \\[universal-argument] prefix arg, prompt the user.
3031 The top row is row 1. Selecting row 0 displays the default header row."
3032 (interactive
3033 (list (if (numberp current-prefix-arg) current-prefix-arg
3034 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3035 (if current-prefix-arg
3036 (read-number "Header row: " currow)
3037 currow)))))
3038 (if (or (< row 0) (> row ses--numrows))
3039 (error "Invalid header-row"))
3040 (ses-begin-change)
3041 (let ((oldval ses--header-row))
3042 (let (buffer-undo-list)
3043 (ses-set-parameter 'ses--header-row row))
3044 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
3045 (ses-reset-header-string))
3047 (defun ses-mark-row ()
3048 "Mark the entirety of current row as a range."
3049 (interactive)
3050 (ses-check-curcell 'range)
3051 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
3052 (push-mark (point))
3053 (ses-goto-print (1+ row) 0)
3054 (push-mark (point) nil t)
3055 (ses-goto-print row 0)))
3057 (defun ses-mark-column ()
3058 "Mark the entirety of current column as a range."
3059 (interactive)
3060 (ses-check-curcell 'range)
3061 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
3062 (row 0))
3063 (push-mark (point))
3064 (ses-goto-print (1- ses--numrows) col)
3065 (forward-char 1)
3066 (push-mark (point) nil t)
3067 (while (eq '*skip* (ses-cell-value row col))
3068 ;;Skip over initial cells in column that can't be selected
3069 (setq row (1+ row)))
3070 (ses-goto-print row col)))
3072 (defun ses-end-of-line ()
3073 "Move point to last cell on line."
3074 (interactive)
3075 (ses-check-curcell 'end 'range)
3076 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3077 ; anyway.
3078 (let ((col (1- ses--numcols))
3079 row rowcol)
3080 (if (symbolp ses--curcell)
3081 ;; Single cell.
3082 (setq row (car (ses-sym-rowcol ses--curcell)))
3083 ;; Range --- use whichever end of the range the point is at.
3084 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
3085 (car ses--curcell)
3086 (cdr ses--curcell))))
3087 ;; If range already includes the last cell in a row, point is actually
3088 ;; in the following row.
3089 (if (<= (cdr rowcol) (1- col))
3090 (setq row (car rowcol))
3091 (setq row (1+ (car rowcol)))
3092 (if (= row ses--numrows)
3093 ;;Already at end - can't go anywhere
3094 (setq col 0))))
3095 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
3096 (while (eq (ses-cell-value row col) '*skip*)
3097 ;; Back to beginning of multi-column cell.
3098 (setq col (1- col)))
3099 (ses-goto-print row col)))))
3101 (defun ses-renarrow-buffer ()
3102 "Narrow the buffer so only the print area is visible.
3103 Use after \\[widen]."
3104 (interactive)
3105 (setq ses--deferred-narrow t))
3107 (defun ses-sort-column (sorter &optional reverse)
3108 "Sort the range by a specified column.
3109 With prefix, sorts in REVERSE order."
3110 (interactive "*sSort column: \nP")
3111 (ses-check-curcell 'needrange)
3112 (let ((min (ses-sym-rowcol (car ses--curcell)))
3113 (max (ses-sym-rowcol (cdr ses--curcell))))
3114 (let ((minrow (car min))
3115 (mincol (cdr min))
3116 (maxrow (car max))
3117 (maxcol (cdr max))
3118 keys extracts end)
3119 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3120 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3121 (error "Invalid sort column"))
3122 ;;Get key columns and sort them
3123 (dotimes (x (- maxrow minrow -1))
3124 (ses-goto-print (+ minrow x) sorter)
3125 (setq end (next-single-property-change (point) 'intangible))
3126 (push (cons (buffer-substring-no-properties (point) end)
3127 (+ minrow x))
3128 keys))
3129 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3130 ;;Extract the lines in reverse sorted order
3131 (or reverse
3132 (setq keys (nreverse keys)))
3133 (dolist (x keys)
3134 (ses-goto-print (cdr x) (1+ maxcol))
3135 (setq end (point))
3136 (ses-goto-print (cdr x) mincol)
3137 (push (ses-copy-region (point) end) extracts))
3138 (deactivate-mark)
3139 ;;Paste the lines sequentially
3140 (dotimes (x (- maxrow minrow -1))
3141 (ses-goto-print (+ minrow x) mincol)
3142 (ses-set-curcell)
3143 (ses-yank-cells (pop extracts) nil)))))
3145 (defun ses-sort-column-click (event reverse)
3146 "Mouse version of `ses-sort-column'."
3147 (interactive "*e\nP")
3148 (setq event (event-end event))
3149 (select-window (posn-window event))
3150 (setq event (car (posn-col-row event))) ; Click column.
3151 (let ((col 0))
3152 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3153 (setq event (- event (ses-col-width col) 1)
3154 col (1+ col)))
3155 (if (>= col ses--numcols)
3156 (ding)
3157 (ses-sort-column (ses-column-letter col) reverse))))
3159 (defun ses-insert-range ()
3160 "Insert into minibuffer the list of cells currently highlighted in the
3161 spreadsheet."
3162 (interactive "*")
3163 (let (x)
3164 (with-current-buffer (window-buffer minibuffer-scroll-window)
3165 (ses-command-hook) ; For ses-coverage.
3166 (ses-check-curcell 'needrange)
3167 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3168 ,(cdr ses--curcell))))))
3169 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3171 (defun ses-insert-ses-range ()
3172 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
3173 highlighted range in the spreadsheet."
3174 (interactive "*")
3175 (let (x)
3176 (with-current-buffer (window-buffer minibuffer-scroll-window)
3177 (ses-command-hook) ; For ses-coverage.
3178 (ses-check-curcell 'needrange)
3179 (setq x (format "(ses-range %S %S)"
3180 (car ses--curcell)
3181 (cdr ses--curcell))))
3182 (insert x)))
3184 (defun ses-insert-range-click (event)
3185 "Mouse version of `ses-insert-range'."
3186 (interactive "*e")
3187 (mouse-set-point event)
3188 (ses-insert-range))
3190 (defun ses-insert-ses-range-click (event)
3191 "Mouse version of `ses-insert-ses-range'."
3192 (interactive "*e")
3193 (mouse-set-point event)
3194 (ses-insert-ses-range))
3196 (defun ses-replace-name-in-formula (formula old-name new-name)
3197 (let ((new-formula formula))
3198 (unless (and (consp formula)
3199 (eq (car-safe formula) 'quote))
3200 (while formula
3201 (let ((elt (car-safe formula)))
3202 (cond
3203 ((consp elt)
3204 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3205 ((and (symbolp elt)
3206 (eq (car-safe formula) old-name))
3207 (setcar formula new-name))))
3208 (setq formula (cdr formula))))
3209 new-formula))
3211 (defun ses-rename-cell (new-name &optional cell)
3212 "Rename current cell."
3213 (interactive "*SEnter new name: ")
3214 (and (local-variable-p new-name)
3215 (ses-sym-rowcol new-name)
3216 ;; this test is needed because ses-cell property of deleted cells
3217 ;; is not deleted in case of subsequent undo
3218 (memq new-name ses--renamed-cell-symb-list)
3219 (error "Already a cell name"))
3220 (and (boundp new-name)
3221 (null (yes-or-no-p (format "`%S' is already bound outside this buffer, continue? "
3222 new-name)))
3223 (error "Already a bound cell name"))
3224 (let* ((sym (if (ses-cell-p cell)
3225 (ses-cell-symbol cell)
3226 (setq cell nil)
3227 (ses-check-curcell)
3228 ses--curcell))
3229 (rowcol (ses-sym-rowcol sym))
3230 (row (car rowcol))
3231 (col (cdr rowcol)))
3232 (setq cell (or cell (ses-get-cell row col)))
3233 (push `(ses-rename-cell ,(ses-cell-symbol cell) ,cell) buffer-undo-list)
3234 (put new-name 'ses-cell rowcol)
3235 ;; replace name by new name in formula of cells refering to renamed cell
3236 (dolist (ref (ses-cell-references cell))
3237 (let* ((x (ses-sym-rowcol ref))
3238 (xcell (ses-get-cell (car x) (cdr x))))
3239 (ses-cell-formula-aset xcell
3240 (ses-replace-name-in-formula
3241 (ses-cell-formula xcell)
3243 new-name))))
3244 ;; replace name by new name in reference list of cells to which renamed cell refers to
3245 (dolist (ref (ses-formula-references (ses-cell-formula cell)))
3246 (let* ((x (ses-sym-rowcol ref))
3247 (xcell (ses-get-cell (car x) (cdr x))))
3248 (ses-cell-references-aset xcell
3249 (cons new-name (delq sym
3250 (ses-cell-references xcell))))))
3251 (push new-name ses--renamed-cell-symb-list)
3252 (set new-name (symbol-value sym))
3253 (aset cell 0 new-name)
3254 (put sym 'ses-cell nil)
3255 (makunbound sym)
3256 (setq sym new-name)
3257 (let* ((pos (point))
3258 (inhibit-read-only t)
3259 (col (current-column))
3260 (end (save-excursion
3261 (move-to-column (1+ col))
3262 (if (eolp)
3263 (+ pos (ses-col-width col) 1)
3264 (point)))))
3265 (put-text-property pos end 'intangible new-name))
3266 ;; update mode line
3267 (setq mode-line-process (list " cell "
3268 (symbol-name sym)))
3269 (force-mode-line-update)))
3271 ;;----------------------------------------------------------------------------
3272 ;; Checking formulas for safety
3273 ;;----------------------------------------------------------------------------
3275 (defun ses-safe-printer (printer)
3276 "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
3277 (if (or (stringp printer)
3278 (stringp (car-safe printer))
3279 (not printer)
3280 (ses-warn-unsafe printer 'unsafep-function))
3281 printer
3282 'ses-unsafe))
3284 (defun ses-safe-formula (formula)
3285 "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
3286 (if (ses-warn-unsafe formula 'unsafep)
3287 formula
3288 `(ses-unsafe ',formula)))
3290 (defun ses-warn-unsafe (formula checker)
3291 "Apply CHECKER to FORMULA.
3292 If result is non-nil, asks user for confirmation about FORMULA,
3293 which might be unsafe. Returns t if formula is safe or user allows
3294 execution anyway. Always returns t if `safe-functions' is t."
3295 (if (eq safe-functions t)
3297 (setq checker (funcall checker formula))
3298 (if (not checker)
3300 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3301 formula checker)))))
3304 ;;----------------------------------------------------------------------------
3305 ;; Standard formulas
3306 ;;----------------------------------------------------------------------------
3308 (defun ses--clean-! (&rest x)
3309 "Clean by `delq' list X from any occurrence of `nil' or `*skip*'."
3310 (delq nil (delq '*skip* x)))
3312 (defun ses--clean-_ (x y)
3313 "Clean list X by replacing by Y any occurrence of `nil' or `*skip*'.
3315 This will change X by making `setcar' on its cons cells."
3316 (let ((ret x) ret-elt)
3317 (while ret
3318 (setq ret-elt (car ret))
3319 (when (memq ret-elt '(nil *skip*))
3320 (setcar ret y))
3321 (setq ret (cdr ret))))
3324 (defmacro ses-range (from to &rest rest)
3325 "Expand to a list of cell-symbols for the range going from
3326 FROM up to TO. The range automatically expands to include any
3327 new row or column inserted into its middle. The SES library code
3328 specifically looks for the symbol `ses-range', so don't create an
3329 alias for this macro!
3331 By passing in REST some flags one can configure the way the range
3332 is read and how it is formatted.
3334 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3335 1 2 3 and 4.
3337 Readout direction is specified by a `>v', '`>^', `<v', `<^',
3338 `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3339 of such a flag, a default direction of `^<' is assumed. This
3340 way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3341 while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3343 If the range is one row, then `>' can be used as a shorthand to
3344 `>v' or `>^', and `<' to `<v' or `<^'.
3346 If the range is one column, then `v' can be used as a shorthand to
3347 `v>' or `v<', and `^' to `^>' or `v<'.
3349 A `!' flag will remove all cells whose value is nil or `*skip*'.
3351 A `_' flag will replace nil or `*skip*' by the value following
3352 the `_' flag. If the `_' flag is the last argument, then they are
3353 replaced by integer 0.
3355 A `*', `*1' or `*2' flag will vectorize the range in the sense of
3356 Calc. See info node `(Calc) Top'. Flag `*' will output either a
3357 vector or a matrix depending on the number of rows, `*1' will
3358 flatten the result to a one row vector, and `*2' will make a
3359 matrix whatever the number of rows.
3361 Warning: interaction with Calc is experimental and may produce
3362 confusing results if you are not aware of Calc data format.
3363 Use `math-format-value' as a printer for Calc objects."
3364 (let (result-row
3365 result
3366 (prev-row -1)
3367 (reorient-x nil)
3368 (reorient-y nil)
3369 transpose vectorize
3370 (clean 'list))
3371 (ses-dorange (cons from to)
3372 (when (/= prev-row row)
3373 (push result-row result)
3374 (setq result-row nil))
3375 (push (ses-cell-symbol row col) result-row)
3376 (setq prev-row row))
3377 (push result-row result)
3378 (while rest
3379 (let ((x (pop rest)))
3380 (pcase x
3381 (`>v (setq transpose nil reorient-x nil reorient-y nil))
3382 (`>^ (setq transpose nil reorient-x nil reorient-y t))
3383 (`<^ (setq transpose nil reorient-x t reorient-y t))
3384 (`<v (setq transpose nil reorient-x t reorient-y nil))
3385 (`v> (setq transpose t reorient-x nil reorient-y t))
3386 (`^> (setq transpose t reorient-x nil reorient-y nil))
3387 (`^< (setq transpose t reorient-x t reorient-y nil))
3388 (`v< (setq transpose t reorient-x t reorient-y t))
3389 ((or `* `*2 `*1) (setq vectorize x))
3390 (`! (setq clean 'ses--clean-!))
3391 (`_ (setq clean `(lambda (&rest x)
3392 (ses--clean-_ x ,(if rest (pop rest) 0)))))
3394 (cond
3395 ; shorthands one row
3396 ((and (null (cddr result)) (memq x '(> <)))
3397 (push (intern (concat (symbol-name x) "v")) rest))
3398 ; shorthands one col
3399 ((and (null (cdar result)) (memq x '(v ^)))
3400 (push (intern (concat (symbol-name x) ">")) rest))
3401 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3402 (if reorient-y
3403 (setcdr (last result 2) nil)
3404 (setq result (cdr (nreverse result))))
3405 (unless reorient-x
3406 (setq result (mapcar 'nreverse result)))
3407 (when transpose
3408 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3409 (while result
3410 (setq iter ret)
3411 (dolist (elt (pop result))
3412 (setcar iter (cons elt (car iter)))
3413 (setq iter (cdr iter))))
3414 (setq result ret)))
3416 (cl-flet ((vectorize-*1
3417 (clean result)
3418 (cons clean (cons (quote 'vec) (apply 'append result))))
3419 (vectorize-*2
3420 (clean result)
3421 (cons clean (cons (quote 'vec)
3422 (mapcar (lambda (x)
3423 (cons clean (cons (quote 'vec) x)))
3424 result)))))
3425 (pcase vectorize
3426 (`nil (cons clean (apply 'append result)))
3427 (`*1 (vectorize-*1 clean result))
3428 (`*2 (vectorize-*2 clean result))
3429 (`* (funcall (if (cdr result)
3430 #'vectorize-*2
3431 #'vectorize-*1)
3432 clean result))))))
3434 (defun ses-delete-blanks (&rest args)
3435 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3436 (let (result)
3437 (dolist (cur args)
3438 (unless (memq cur '(nil *skip*))
3439 (push cur result)))
3440 result))
3442 (defun ses+ (&rest args)
3443 "Compute the sum of the arguments, ignoring blanks."
3444 (apply '+ (apply 'ses-delete-blanks args)))
3446 (defun ses-average (list)
3447 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3448 are ignored. Result is always floating-point, even if all args are integers."
3449 (setq list (apply 'ses-delete-blanks list))
3450 (/ (float (apply '+ list)) (length list)))
3452 (defmacro ses-select (fromrange test torange)
3453 "Select cells in FROMRANGE that are `equal' to TEST.
3454 For each match, return the corresponding cell from TORANGE.
3455 The ranges are macroexpanded but not evaluated so they should be
3456 either (ses-range BEG END) or (list ...). The TEST is evaluated."
3457 (setq fromrange (cdr (macroexpand fromrange))
3458 torange (cdr (macroexpand torange))
3459 test (eval test))
3460 (or (= (length fromrange) (length torange))
3461 (error "ses-select: Ranges not same length"))
3462 (let (result)
3463 (dolist (x fromrange)
3464 (if (equal test (symbol-value x))
3465 (push (car torange) result))
3466 (setq torange (cdr torange)))
3467 (cons 'list result)))
3469 ;;All standard formulas are safe
3470 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3471 ses-select))
3472 (put x 'side-effect-free t))
3475 ;;----------------------------------------------------------------------------
3476 ;; Standard print functions
3477 ;;----------------------------------------------------------------------------
3479 ;; These functions use the variables 'row' and 'col' that are dynamically bound
3480 ;; by ses-print-cell. We define these variables at compile-time to make the
3481 ;; compiler happy.
3482 (defvar row)
3483 (defvar col)
3485 (defun ses-center (value &optional span fill)
3486 "Print VALUE, centered within column.
3487 FILL is the fill character for centering (default = space).
3488 SPAN indicates how many additional rightward columns to include
3489 in width (default = 0)."
3490 (let ((printer (or (ses-col-printer col) ses--default-printer))
3491 (width (ses-col-width col))
3492 half)
3493 (or fill (setq fill ?\s))
3494 (or span (setq span 0))
3495 (setq value (ses-call-printer printer value))
3496 (dotimes (x span)
3497 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
3498 ;; Set column width.
3499 (setq width (- width (string-width value)))
3500 (if (<= width 0)
3501 value ; Too large for field, anyway.
3502 (setq half (make-string (/ width 2) fill))
3503 (concat half value half
3504 (if (> (% width 2) 0) (char-to-string fill))))))
3506 (defun ses-center-span (value &optional fill)
3507 "Print VALUE, centered within the span that starts in the current column
3508 and continues until the next nonblank column.
3509 FILL specifies the fill character (default = space)."
3510 (let ((end (1+ col)))
3511 (while (and (< end ses--numcols)
3512 (memq (ses-cell-value row end) '(nil *skip*)))
3513 (setq end (1+ end)))
3514 (ses-center value (- end col 1) fill)))
3516 (defun ses-dashfill (value &optional span)
3517 "Print VALUE centered using dashes.
3518 SPAN indicates how many rightward columns to include in width (default = 0)."
3519 (ses-center value span ?-))
3521 (defun ses-dashfill-span (value)
3522 "Print VALUE, centered using dashes within the span that starts in the
3523 current column and continues until the next nonblank column."
3524 (ses-center-span value ?-))
3526 (defun ses-tildefill-span (value)
3527 "Print VALUE, centered using tildes within the span that starts in the
3528 current column and continues until the next nonblank column."
3529 (ses-center-span value ?~))
3531 (defun ses-unsafe (value)
3532 "Substitute for an unsafe formula or printer."
3533 (error "Unsafe formula or printer"))
3535 ;;All standard printers are safe, including ses-unsafe!
3536 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3537 (put x 'side-effect-free t))
3539 (defun ses-unload-function ()
3540 "Unload the Simple Emacs Spreadsheet."
3541 (dolist (fun '(copy-region-as-kill yank))
3542 (ad-remove-advice fun 'around (intern (concat "ses-" (symbol-name fun))))
3543 (ad-update fun))
3544 ;; continue standard unloading
3545 nil)
3547 (provide 'ses)
3549 ;;; ses.el ends here