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