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