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