Fix bug #9221 with memory leak in bidi display.
[emacs.git] / lisp / ses.el
blob9b2048eae836778b260c46de7b47e08bd7e47af1
1 ;;; ses.el -- Simple Emacs Spreadsheet -*- coding: utf-8 -*-
3 ;; Copyright (C) 2002-2011 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 Dijksta 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). Result
494 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 "Signals 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, adds 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 "Flags 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 enqueues 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 reference where corrupted.
817 The following is a list of 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
926 themselves."
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-excusion's marker will move past the cell.
984 (goto-char pos)))
987 ;;----------------------------------------------------------------------------
988 ;; The print area
989 ;;----------------------------------------------------------------------------
991 (defun ses-in-print-area ()
992 "Returns 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 "Sets `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. The end marker is
1034 appropriate if some argument is 'end. A range is appropriate if some
1035 argument is 'range. A single cell is appropriate unless some argument is
1036 '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 unpropertied 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 "Invokes 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*, the preceding
1223 nonskipped cell is reprinted. This function is used when the width of
1224 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 noticably 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, whichs 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. Result is t if element has changed"
1622 (unless (equal (aref array idx) newval)
1623 (push `(apply ses-aset-with-undo ,array ,idx
1624 ,(aref array idx)) buffer-undo-list)
1625 (aset array idx newval)
1629 ;;----------------------------------------------------------------------------
1630 ;; Startup for major mode
1631 ;;----------------------------------------------------------------------------
1633 (defun ses-load ()
1634 "Parse the current buffer and sets up buffer-local variables. Does not
1635 execute cell formulas or print functions."
1636 (widen)
1637 ;; Read our global parameters, which should be a 3-element list.
1638 (goto-char (point-max))
1639 (search-backward ";; Local Variables:\n" nil t)
1640 (backward-list 1)
1641 (setq ses--params-marker (point-marker))
1642 (let ((params (condition-case nil (read (current-buffer)) (error nil))))
1643 (or (and (= (safe-length params) 3)
1644 (numberp (car params))
1645 (numberp (cadr params))
1646 (>= (cadr params) 0)
1647 (numberp (nth 2 params))
1648 (> (nth 2 params) 0))
1649 (error "Invalid SES file"))
1650 (setq ses--file-format (car params)
1651 ses--numrows (cadr params)
1652 ses--numcols (nth 2 params))
1653 (when (= ses--file-format 1)
1654 (let (buffer-undo-list) ; This is not undoable.
1655 (ses-goto-data 'ses--header-row)
1656 (insert "(ses-header-row 0)\n")
1657 (ses-set-parameter 'ses--file-format 2)
1658 (message "Upgrading from SES-1 file format")))
1659 (or (= ses--file-format 2)
1660 (error "This file needs a newer version of the SES library code"))
1661 (ses-create-cell-variable-range 0 (1- ses--numrows) 0 (1- ses--numcols))
1662 ;; Initialize cell array.
1663 (setq ses--cells (make-vector ses--numrows nil))
1664 (dotimes (row ses--numrows)
1665 (aset ses--cells row (make-vector ses--numcols nil))))
1666 ;; Skip over print area, which we assume is correct.
1667 (goto-char (point-min))
1668 (forward-line ses--numrows)
1669 (or (looking-at ses-print-data-boundary)
1670 (error "Missing marker between print and data areas"))
1671 (forward-char 1)
1672 (setq ses--data-marker (point-marker))
1673 (forward-char (1- (length ses-print-data-boundary)))
1674 ;; Initialize printer and symbol lists.
1675 (mapc 'ses-printer-record ses-standard-printer-functions)
1676 (setq ses--symbolic-formulas nil)
1677 ;; Load cell definitions.
1678 (dotimes (row ses--numrows)
1679 (dotimes (col ses--numcols)
1680 (let* ((x (read (current-buffer)))
1681 (rowcol (ses-sym-rowcol (car-safe (cdr-safe x)))))
1682 (or (and (looking-at "\n")
1683 (eq (car-safe x) 'ses-cell)
1684 (eq row (car rowcol))
1685 (eq col (cdr rowcol)))
1686 (error "Cell-def error"))
1687 (eval x)))
1688 (or (looking-at "\n\n")
1689 (error "Missing blank line between rows")))
1690 ;; Load global parameters.
1691 (let ((widths (read (current-buffer)))
1692 (n1 (char-after (point)))
1693 (printers (read (current-buffer)))
1694 (n2 (char-after (point)))
1695 (def-printer (read (current-buffer)))
1696 (n3 (char-after (point)))
1697 (head-row (read (current-buffer)))
1698 (n4 (char-after (point))))
1699 (or (and (eq (car-safe widths) 'ses-column-widths)
1700 (= n1 ?\n)
1701 (eq (car-safe printers) 'ses-column-printers)
1702 (= n2 ?\n)
1703 (eq (car-safe def-printer) 'ses-default-printer)
1704 (= n3 ?\n)
1705 (eq (car-safe head-row) 'ses-header-row)
1706 (= n4 ?\n))
1707 (error "Invalid SES global parameters"))
1708 (1value (eval widths))
1709 (1value (eval def-printer))
1710 (1value (eval printers))
1711 (1value (eval head-row)))
1712 ;; Should be back at global-params.
1713 (forward-char 1)
1714 (or (looking-at (replace-regexp-in-string "1" "[0-9]+"
1715 ses-initial-global-parameters))
1716 (error "Problem with column-defs or global-params"))
1717 ;; Check for overall newline count in definitions area.
1718 (forward-line 3)
1719 (let ((start (point)))
1720 (ses-goto-data 'ses--numrows)
1721 (or (= (point) start)
1722 (error "Extraneous newlines someplace?"))))
1724 (defun ses-setup ()
1725 "Set up for display of only the printed cell values.
1727 Narrows the buffer to show only the print area. Gives it `read-only' and
1728 `intangible' properties. Sets up highlighting for current cell."
1729 (interactive)
1730 (let ((end (point-min))
1731 (inhibit-read-only t)
1732 (inhibit-point-motion-hooks t)
1733 (was-modified (buffer-modified-p))
1734 pos sym)
1735 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1736 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1737 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1738 ;; The print area is read-only (except for our special commands) and uses a
1739 ;; special keymap.
1740 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1741 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1742 ;; For the beginning of the buffer, we want the read-only and keymap
1743 ;; attributes to be inherited from the first character.
1744 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1745 ;; Create intangible properties, which also indicate which cell the text
1746 ;; came from.
1747 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1748 (dotimes (col ses--numcols)
1749 (setq pos end
1750 sym (ses-cell-symbol row col))
1751 ;; Include skipped cells following this one.
1752 (while (and (< col (1- ses--numcols))
1753 (eq (ses-cell-value row (1+ col)) '*skip*))
1754 (setq end (+ end (ses-col-width col) 1)
1755 col (1+ col)))
1756 (setq end (save-excursion
1757 (goto-char pos)
1758 (move-to-column (+ (current-column) (- end pos)
1759 (ses-col-width col)))
1760 (if (eolp)
1761 (+ end (ses-col-width col) 1)
1762 (forward-char)
1763 (point))))
1764 (put-text-property pos end 'intangible sym)))
1765 ;; Adding these properties did not actually alter the text.
1766 (unless was-modified
1767 (restore-buffer-modified-p nil)
1768 (buffer-disable-undo)
1769 (buffer-enable-undo)))
1770 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1771 ;; because column A must be at least 1 column wide.
1772 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1773 (overlay-put ses--curcell-overlay 'face 'underline))
1775 (defun ses-cleanup ()
1776 "Cleanup when changing a buffer from SES mode to something else.
1777 Delete overlays, remove special text properties."
1778 (widen)
1779 (let ((inhibit-read-only t)
1780 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1781 ;; user "the file is modified, do you really want to make modifications
1782 ;; to this buffer", where the "modifications" refer to the irrelevant
1783 ;; set-text-properties below.
1784 (buffer-file-name nil)
1785 (was-modified (buffer-modified-p)))
1786 ;; Delete read-only, keymap, and intangible properties.
1787 (set-text-properties (point-min) (point-max) nil)
1788 ;; Delete overlay.
1789 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1790 (unless was-modified
1791 (restore-buffer-modified-p nil))))
1793 ;;;###autoload
1794 (defun ses-mode ()
1795 "Major mode for Simple Emacs Spreadsheet.
1796 See \"ses-example.ses\" (in `data-directory') for more info.
1798 Key definitions:
1799 \\{ses-mode-map}
1800 These key definitions are active only in the print area (the visible part):
1801 \\{ses-mode-print-map}
1802 These are active only in the minibuffer, when entering or editing a formula:
1803 \\{ses-mode-edit-map}"
1804 (interactive)
1805 (unless (and (boundp 'ses--deferred-narrow)
1806 (eq ses--deferred-narrow 'ses-mode))
1807 (kill-all-local-variables)
1808 (ses-set-localvars)
1809 (setq major-mode 'ses-mode
1810 mode-name "SES"
1811 next-line-add-newlines nil
1812 truncate-lines t
1813 ;; SES deliberately puts lots of trailing whitespace in its buffer.
1814 show-trailing-whitespace nil
1815 ;; Cell ranges do not work reasonably without this.
1816 transient-mark-mode t
1817 ;; Not to use tab characters for safe (tabs may do bad for column
1818 ;; calculation).
1819 indent-tabs-mode nil)
1820 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1821 (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1822 (setq header-line-format '(:eval (progn
1823 (when (/= (window-hscroll)
1824 ses--header-hscroll)
1825 ;; Reset ses--header-hscroll first,
1826 ;; to avoid recursion problems when
1827 ;; debugging ses-create-header-string
1828 (setq ses--header-hscroll
1829 (window-hscroll))
1830 (ses-create-header-string))
1831 ses--header-string)))
1832 (let ((was-empty (zerop (buffer-size)))
1833 (was-modified (buffer-modified-p)))
1834 (save-excursion
1835 (if was-empty
1836 ;; Initialize buffer to contain one cell, for now.
1837 (insert ses-initial-file-contents))
1838 (ses-load)
1839 (ses-setup))
1840 (when was-empty
1841 (unless (equal ses-initial-default-printer
1842 (1value ses--default-printer))
1843 (1value (ses-read-default-printer ses-initial-default-printer)))
1844 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
1845 (1value (ses-set-column-width 0 ses-initial-column-width)))
1846 (ses-set-curcell)
1847 (if (> (car ses-initial-size) (1value ses--numrows))
1848 (1value (ses-insert-row (1- (car ses-initial-size)))))
1849 (if (> (cdr ses-initial-size) (1value ses--numcols))
1850 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
1851 (ses-write-cells)
1852 (restore-buffer-modified-p was-modified)
1853 (buffer-disable-undo)
1854 (buffer-enable-undo)
1855 (goto-char (point-min))))
1856 (use-local-map ses-mode-map)
1857 ;; Set the deferred narrowing flag (we can't narrow until after
1858 ;; after-find-file completes). If .ses is on the auto-load alist and the
1859 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
1860 ;; special flag to detect this (will be reset by ses-command-hook). For
1861 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
1862 ;; so use an idle timer to make sure.
1863 (setq ses--deferred-narrow 'ses-mode)
1864 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
1865 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1866 (run-mode-hooks 'ses-mode-hook)))
1868 (put 'ses-mode 'mode-class 'special)
1870 (defun ses-command-hook ()
1871 "Invoked from `post-command-hook'. If point has moved to a different cell,
1872 moves the underlining overlay. Performs any recalculations or cell-data
1873 writes that have been deferred. If buffer-narrowing has been deferred,
1874 narrows the buffer now."
1875 (condition-case err
1876 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
1877 (when ses--deferred-recalc
1878 ;; We reset the deferred list before starting on the recalc --- in
1879 ;; case of error, we don't want to retry the recalc after every
1880 ;; keystroke!
1881 (ses-initialize-Dijkstra-attempt)
1882 (let ((old ses--deferred-recalc))
1883 (setq ses--deferred-recalc nil)
1884 (ses-update-cells old)))
1885 (when ses--deferred-write
1886 ;; We don't reset the deferred list before starting --- the most
1887 ;; likely error is keyboard-quit, and we do want to keep trying these
1888 ;; writes after a quit.
1889 (ses-write-cells)
1890 (push '(apply ses-widen) buffer-undo-list))
1891 (when ses--deferred-narrow
1892 ;; We're not allowed to narrow the buffer until after-find-file has
1893 ;; read the local variables at the end of the file. Now it's safe to
1894 ;; do the narrowing.
1895 (narrow-to-region (point-min) ses--data-marker)
1896 (setq ses--deferred-narrow nil))
1897 ;; Update the modeline.
1898 (let ((oldcell ses--curcell))
1899 (ses-set-curcell)
1900 (unless (eq ses--curcell oldcell)
1901 (cond
1902 ((not ses--curcell)
1903 (setq mode-line-process nil))
1904 ((atom ses--curcell)
1905 (setq mode-line-process (list " cell "
1906 (symbol-name ses--curcell))))
1908 (setq mode-line-process (list " range "
1909 (symbol-name (car ses--curcell))
1911 (symbol-name (cdr ses--curcell))))))
1912 (force-mode-line-update)))
1913 ;; Use underline overlay for single-cells only, turn off otherwise.
1914 (if (listp ses--curcell)
1915 (move-overlay ses--curcell-overlay 2 2)
1916 (let ((next (next-single-property-change (point) 'intangible)))
1917 (move-overlay ses--curcell-overlay (point) (1- next))))
1918 (when (not (pos-visible-in-window-p))
1919 ;; Scrolling will happen later.
1920 (run-with-idle-timer 0.01 nil 'ses-command-hook)
1921 (setq ses--curcell t)))
1922 ;; Prevent errors in this post-command-hook from silently erasing the hook!
1923 (error
1924 (unless executing-kbd-macro
1925 (ding))
1926 (message "%s" (error-message-string err))))
1927 nil) ; Make coverage-tester happy.
1929 (defun ses-create-header-string ()
1930 "Set up `ses--header-string' as the buffer's header line.
1931 Based on the current set of columns and `window-hscroll' position."
1932 (let ((totwidth (- (window-hscroll)))
1933 result width x)
1934 ;; Leave room for the left-side fringe and scrollbar.
1935 (push (propertize " " 'display '((space :align-to 0))) result)
1936 (dotimes (col ses--numcols)
1937 (setq width (ses-col-width col)
1938 totwidth (+ totwidth width 1))
1939 (if (= totwidth 1)
1940 ;; Scrolled so intercolumn space is leftmost.
1941 (push " " result))
1942 (when (> totwidth 1)
1943 (if (> ses--header-row 0)
1944 (save-excursion
1945 (ses-goto-print (1- ses--header-row) col)
1946 (setq x (buffer-substring-no-properties (point)
1947 (+ (point) width)))
1948 ;; Strip trailing space.
1949 (if (string-match "[ \t]+\\'" x)
1950 (setq x (substring x 0 (match-beginning 0))))
1951 ;; Cut off excess text.
1952 (if (>= (length x) totwidth)
1953 (setq x (substring x 0 (- totwidth -1)))))
1954 (setq x (ses-column-letter col)))
1955 (push (propertize x 'face ses-box-prop) result)
1956 (push (propertize "."
1957 'display `((space :align-to ,(1- totwidth)))
1958 'face ses-box-prop)
1959 result)
1960 ;; Allow the following space to be squished to make room for the 3-D box
1961 ;; Coverage test ignores properties, thinks this is always a space!
1962 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
1963 result)))
1964 (if (> ses--header-row 0)
1965 (push (propertize (format " [row %d]" ses--header-row)
1966 'display '((height (- 1))))
1967 result))
1968 (setq ses--header-string (apply 'concat (nreverse result)))))
1971 ;;----------------------------------------------------------------------------
1972 ;; Redisplay and recalculation
1973 ;;----------------------------------------------------------------------------
1975 (defun ses-jump (sym)
1976 "Move point to cell SYM."
1977 (interactive "SJump to cell: ")
1978 (let ((rowcol (ses-sym-rowcol sym)))
1979 (or rowcol (error "Invalid cell name"))
1980 (if (eq (symbol-value sym) '*skip*)
1981 (error "Cell is covered by preceding cell"))
1982 (ses-goto-print (car rowcol) (cdr rowcol))))
1984 (defun ses-jump-safe (cell)
1985 "Like `ses-jump', but no error if invalid cell."
1986 (condition-case nil
1987 (ses-jump cell)
1988 (error)))
1990 (defun ses-reprint-all (&optional nonarrow)
1991 "Recreate the display area. Calls all printer functions. Narrows to
1992 print area if NONARROW is nil."
1993 (interactive "*P")
1994 (widen)
1995 (unless nonarrow
1996 (setq ses--deferred-narrow t))
1997 (let ((startcell (get-text-property (point) 'intangible))
1998 (inhibit-read-only t))
1999 (ses-begin-change)
2000 (goto-char (point-min))
2001 (search-forward ses-print-data-boundary)
2002 (backward-char (length ses-print-data-boundary))
2003 (delete-region (point-min) (point))
2004 ;; Insert all blank lines before printing anything, so ses-print-cell can
2005 ;; find the data area when inserting or deleting *skip* values for cells.
2006 (dotimes (row ses--numrows)
2007 (insert-and-inherit ses--blank-line))
2008 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2009 (if (eq (ses-cell-value row 0) '*skip*)
2010 ;; Column deletion left a dangling skip.
2011 (ses-set-cell row 0 'value nil))
2012 (dotimes (col ses--numcols)
2013 (ses-print-cell row col))
2014 (beginning-of-line 2))
2015 (ses-jump-safe startcell)))
2017 (defun ses-initialize-Dijkstra-attempt ()
2018 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2019 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2021 (defun ses-recalculate-cell ()
2022 "Recalculate and reprint the current cell or range.
2024 For an individual cell, shows the error if the formula or printer
2025 signals one, or otherwise shows the cell's complete value. For a range, the
2026 cells are recalculated in \"natural\" order, so cells that other cells refer
2027 to are recalculated first."
2028 (interactive "*")
2029 (ses-check-curcell 'range)
2030 (ses-begin-change)
2031 (ses-initialize-Dijkstra-attempt)
2032 (let (sig cur-rowcol)
2033 (setq ses-start-time (float-time))
2034 (if (atom ses--curcell)
2035 (when
2036 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2037 sig (progn
2038 (ses-cell-property-set :ses-Dijkstra-attempt
2039 (cons ses--Dijkstra-attempt-nb 0)
2040 (car cur-rowcol) (cdr cur-rowcol) )
2041 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2042 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2043 (cdr cur-rowcol)))))
2044 ;; First, recalculate all cells that don't refer to other cells and
2045 ;; produce a list of cells with references.
2046 (ses-dorange ses--curcell
2047 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
2048 (condition-case nil
2049 (progn
2050 ;; The t causes an error if the cell has references. If no
2051 ;; references, the t will be the result value.
2052 (1value (ses-formula-references (ses-cell-formula row col) t))
2053 (ses-cell-property-set :ses-Dijkstra-attempt
2054 (cons ses--Dijkstra-attempt-nb 0)
2055 row col)
2056 (when (setq sig (ses-calculate-cell row col t))
2057 (nconc sig (list (ses-cell-symbol row col)))))
2058 (wrong-type-argument
2059 ;; The formula contains a reference.
2060 (add-to-list 'ses--deferred-recalc (ses-cell-symbol row col))))))
2061 ;; Do the update now, so we can force recalculation.
2062 (let ((x ses--deferred-recalc))
2063 (setq ses--deferred-recalc nil)
2064 (condition-case hold
2065 (ses-update-cells x t)
2066 (error (setq sig hold))))
2067 (cond
2068 (sig
2069 (message "%s" (error-message-string sig)))
2070 ((consp ses--curcell)
2071 (message " "))
2073 (princ (symbol-value ses--curcell))))))
2075 (defun ses-recalculate-all ()
2076 "Recalculate and reprint all cells."
2077 (interactive "*")
2078 (let ((startcell (get-text-property (point) 'intangible))
2079 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2080 (1- ses--numcols)))))
2081 (ses-recalculate-cell)
2082 (ses-jump-safe startcell)))
2084 (defun ses-truncate-cell ()
2085 "Reprint current cell, but without spillover into any following blank
2086 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 cancelled."
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. See
2335 `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. See
2352 `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. With prefix, insert COUNT rows
2367 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. With prefix, Deletes COUNT rows starting from the
2420 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. With prefix, Deletes COUNT columns starting
2513 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 jumps 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. We clear the killed
2691 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 outsite 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', when
2753 the region contains a stretch of reinserted previously-killed text. We
2754 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, inserts 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, treats the tabs as
2852 column-separators and the newlines as row-separators and inserts 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, asks for
2891 confirmation and then inserts 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
2935 rows. Result is placed in kill ring. The export is values unless
2936 WANT-FORMULAS 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 "Marks 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 "Marks 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. Use after \\[widen]."
3050 (interactive)
3051 (setq ses--deferred-narrow t))
3053 (defun ses-sort-column (sorter &optional reverse)
3054 "Sorts the range by a specified column. With prefix, sorts in
3055 REVERSE order."
3056 (interactive "*sSort column: \nP")
3057 (ses-check-curcell 'needrange)
3058 (let ((min (ses-sym-rowcol (car ses--curcell)))
3059 (max (ses-sym-rowcol (cdr ses--curcell))))
3060 (let ((minrow (car min))
3061 (mincol (cdr min))
3062 (maxrow (car max))
3063 (maxcol (cdr max))
3064 keys extracts end)
3065 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3066 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3067 (error "Invalid sort column"))
3068 ;;Get key columns and sort them
3069 (dotimes (x (- maxrow minrow -1))
3070 (ses-goto-print (+ minrow x) sorter)
3071 (setq end (next-single-property-change (point) 'intangible))
3072 (push (cons (buffer-substring-no-properties (point) end)
3073 (+ minrow x))
3074 keys))
3075 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3076 ;;Extract the lines in reverse sorted order
3077 (or reverse
3078 (setq keys (nreverse keys)))
3079 (dolist (x keys)
3080 (ses-goto-print (cdr x) (1+ maxcol))
3081 (setq end (point))
3082 (ses-goto-print (cdr x) mincol)
3083 (push (ses-copy-region (point) end) extracts))
3084 (deactivate-mark)
3085 ;;Paste the lines sequentially
3086 (dotimes (x (- maxrow minrow -1))
3087 (ses-goto-print (+ minrow x) mincol)
3088 (ses-set-curcell)
3089 (ses-yank-cells (pop extracts) nil)))))
3091 (defun ses-sort-column-click (event reverse)
3092 "Mouse version of `ses-sort-column'."
3093 (interactive "*e\nP")
3094 (setq event (event-end event))
3095 (select-window (posn-window event))
3096 (setq event (car (posn-col-row event))) ; Click column.
3097 (let ((col 0))
3098 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3099 (setq event (- event (ses-col-width col) 1)
3100 col (1+ col)))
3101 (if (>= col ses--numcols)
3102 (ding)
3103 (ses-sort-column (ses-column-letter col) reverse))))
3105 (defun ses-insert-range ()
3106 "Inserts into minibuffer the list of cells currently highlighted in the
3107 spreadsheet."
3108 (interactive "*")
3109 (let (x)
3110 (with-current-buffer (window-buffer minibuffer-scroll-window)
3111 (ses-command-hook) ; For ses-coverage.
3112 (ses-check-curcell 'needrange)
3113 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3114 ,(cdr ses--curcell))))))
3115 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3117 (defun ses-insert-ses-range ()
3118 "Inserts \"(ses-range x y)\" in the minibuffer to represent the currently
3119 highlighted range in the spreadsheet."
3120 (interactive "*")
3121 (let (x)
3122 (with-current-buffer (window-buffer minibuffer-scroll-window)
3123 (ses-command-hook) ; For ses-coverage.
3124 (ses-check-curcell 'needrange)
3125 (setq x (format "(ses-range %S %S)"
3126 (car ses--curcell)
3127 (cdr ses--curcell))))
3128 (insert x)))
3130 (defun ses-insert-range-click (event)
3131 "Mouse version of `ses-insert-range'."
3132 (interactive "*e")
3133 (mouse-set-point event)
3134 (ses-insert-range))
3136 (defun ses-insert-ses-range-click (event)
3137 "Mouse version of `ses-insert-ses-range'."
3138 (interactive "*e")
3139 (mouse-set-point event)
3140 (ses-insert-ses-range))
3143 ;;----------------------------------------------------------------------------
3144 ;; Checking formulas for safety
3145 ;;----------------------------------------------------------------------------
3147 (defun ses-safe-printer (printer)
3148 "Returns PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
3149 (if (or (stringp printer)
3150 (stringp (car-safe printer))
3151 (not printer)
3152 (ses-warn-unsafe printer 'unsafep-function))
3153 printer
3154 'ses-unsafe))
3156 (defun ses-safe-formula (formula)
3157 "Returns FORMULA if safe, or the substitute formula *unsafe* otherwise."
3158 (if (ses-warn-unsafe formula 'unsafep)
3159 formula
3160 `(ses-unsafe ',formula)))
3162 (defun ses-warn-unsafe (formula checker)
3163 "Applies CHECKER to FORMULA. If result is non-nil, asks user for
3164 confirmation about FORMULA, which might be unsafe. Returns t if formula
3165 is safe or user allows execution anyway. Always returns t if
3166 `safe-functions' is t."
3167 (if (eq safe-functions t)
3169 (setq checker (funcall checker formula))
3170 (if (not checker)
3172 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3173 formula checker)))))
3176 ;;----------------------------------------------------------------------------
3177 ;; Standard formulas
3178 ;;----------------------------------------------------------------------------
3180 (defun ses--clean-! (&rest x)
3181 "Clean by delq list X from any occurrence of `nil' or `*skip*'."
3182 (delq nil (delq '*skip* x)))
3184 (defun ses--clean-_ (x y)
3185 "Clean list X by replacing by Y any occurrence of `nil' or `*skip*'.
3187 This will change X by making setcar on its cons cells."
3188 (let ((ret x) ret-elt)
3189 (while ret
3190 (setq ret-elt (car ret))
3191 (when (memq ret-elt '(nil *skip*))
3192 (setcar ret y))
3193 (setq ret (cdr ret))))
3196 (defmacro ses-range (from to &rest rest)
3197 "Expands to a list of cell-symbols for the range going from
3198 FROM up to TO. The range automatically expands to include any
3199 new row or column inserted into its middle. The SES library code
3200 specifically looks for the symbol `ses-range', so don't create an
3201 alias for this macro!
3203 By passing in REST some flags one can configure the way the range
3204 is read and how it is formatted.
3206 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3207 1 2 3 and 4 for examplication.
3209 Readout direction is specified by a `>v', '`>^', `<v', `<^',
3210 `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3211 of such a flag, a default direction of `^<' is assumed. This
3212 way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3213 while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3215 If the range is one row, then `>' can be used as a shorthand to
3216 `>v' or `>^', and `<' to `<v' or `<^'.
3218 If the range is one column, then `v' can be used as a shorthand to
3219 `v>' or `v<', and `^' to `^>' or `v<'.
3221 A `!' flag will remove all cells whose value is nil or `*skip*'.
3223 A `_' flag will replace nil or `*skip*' by the value following
3224 the `_' flag. If the `_' flag is the last argument, then they are
3225 replaced by integer 0.
3227 A `*', `*1' or `*2' flag will vectorize the range in the sense of
3228 Calc. See info node `(Calc) Top'. Flag `*' will output either a
3229 vector or a matrix depending on the number of rows, `*1' will
3230 flatten the result to a one row vector, and `*2' will make a
3231 matrix whatever the number of rows.
3233 Warning: interaction with Calc is expermimental and may produce
3234 confusing results if you are not aware of Calc data format. Use
3235 `math-format-value' as a printer for Calc objects."
3236 (let (result-row
3237 result
3238 (prev-row -1)
3239 (reorient-x nil)
3240 (reorient-y nil)
3241 transpose vectorize
3242 (clean 'list))
3243 (ses-dorange (cons from to)
3244 (when (/= prev-row row)
3245 (push result-row result)
3246 (setq result-row nil))
3247 (push (ses-cell-symbol row col) result-row)
3248 (setq prev-row row))
3249 (push result-row result)
3250 (while rest
3251 (let ((x (pop rest)))
3252 (case x
3253 ((>v) (setq transpose nil reorient-x nil reorient-y nil))
3254 ((>^)(setq transpose nil reorient-x nil reorient-y t))
3255 ((<^)(setq transpose nil reorient-x t reorient-y t))
3256 ((<v)(setq transpose nil reorient-x t reorient-y nil))
3257 ((v>)(setq transpose t reorient-x nil reorient-y t))
3258 ((^>)(setq transpose t reorient-x nil reorient-y nil))
3259 ((^<)(setq transpose t reorient-x t reorient-y nil))
3260 ((v<)(setq transpose t reorient-x t reorient-y t))
3261 ((* *2 *1) (setq vectorize x))
3262 ((!) (setq clean 'ses--clean-!))
3263 ((_) (setq clean `(lambda (&rest x) (ses--clean-_ x ,(if rest (pop rest) 0)))))
3265 (cond
3266 ; shorthands one row
3267 ((and (null (cddr result)) (memq x '(> <)))
3268 (push (intern (concat (symbol-name x) "v")) rest))
3269 ; shorthands one col
3270 ((and (null (cdar result)) (memq x '(v ^)))
3271 (push (intern (concat (symbol-name x) ">")) rest))
3272 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3273 (if reorient-y
3274 (setcdr (last result 2) nil)
3275 (setq result (cdr (nreverse result))))
3276 (unless reorient-x
3277 (setq result (mapcar 'nreverse result)))
3278 (when transpose
3279 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3280 (while result
3281 (setq iter ret)
3282 (dolist (elt (pop result))
3283 (setcar iter (cons elt (car iter)))
3284 (setq iter (cdr iter))))
3285 (setq result ret)))
3287 (flet ((vectorize-*1
3288 (clean result)
3289 (cons clean (cons (quote 'vec) (apply 'append result))))
3290 (vectorize-*2
3291 (clean result)
3292 (cons clean (cons (quote 'vec) (mapcar (lambda (x)
3293 (cons clean (cons (quote 'vec) x)))
3294 result)))))
3295 (case vectorize
3296 ((nil) (cons clean (apply 'append result)))
3297 ((*1) (vectorize-*1 clean result))
3298 ((*2) (vectorize-*2 clean result))
3299 ((*) (if (cdr result)
3300 (vectorize-*2 clean result)
3301 (vectorize-*1 clean result)))))))
3303 (defun ses-delete-blanks (&rest args)
3304 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3305 (let (result)
3306 (dolist (cur args)
3307 (unless (memq cur '(nil *skip*))
3308 (push cur result)))
3309 result))
3311 (defun ses+ (&rest args)
3312 "Compute the sum of the arguments, ignoring blanks."
3313 (apply '+ (apply 'ses-delete-blanks args)))
3315 (defun ses-average (list)
3316 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3317 are ignored. Result is always floating-point, even if all args are integers."
3318 (setq list (apply 'ses-delete-blanks list))
3319 (/ (float (apply '+ list)) (length list)))
3321 (defmacro ses-select (fromrange test torange)
3322 "Select cells in FROMRANGE that are `equal' to TEST. For each match, return
3323 the corresponding cell from TORANGE. The ranges are macroexpanded but not
3324 evaluated so they should be either (ses-range BEG END) or (list ...). The
3325 TEST is evaluated."
3326 (setq fromrange (cdr (macroexpand fromrange))
3327 torange (cdr (macroexpand torange))
3328 test (eval test))
3329 (or (= (length fromrange) (length torange))
3330 (error "ses-select: Ranges not same length"))
3331 (let (result)
3332 (dolist (x fromrange)
3333 (if (equal test (symbol-value x))
3334 (push (car torange) result))
3335 (setq torange (cdr torange)))
3336 (cons 'list result)))
3338 ;;All standard formulas are safe
3339 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3340 ses-select))
3341 (put x 'side-effect-free t))
3344 ;;----------------------------------------------------------------------------
3345 ;; Standard print functions
3346 ;;----------------------------------------------------------------------------
3348 ;; These functions use the variables 'row' and 'col' that are dynamically bound
3349 ;; by ses-print-cell. We define these variables at compile-time to make the
3350 ;; compiler happy.
3351 (defvar row)
3352 (defvar col)
3354 (defun ses-center (value &optional span fill)
3355 "Print VALUE, centered within column. FILL is the fill character for
3356 centering (default = space). SPAN indicates how many additional rightward
3357 columns to include in width (default = 0)."
3358 (let ((printer (or (ses-col-printer col) ses--default-printer))
3359 (width (ses-col-width col))
3360 half)
3361 (or fill (setq fill ?\s))
3362 (or span (setq span 0))
3363 (setq value (ses-call-printer printer value))
3364 (dotimes (x span)
3365 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
3366 ;; Set column width.
3367 (setq width (- width (string-width value)))
3368 (if (<= width 0)
3369 value ; Too large for field, anyway.
3370 (setq half (make-string (/ width 2) fill))
3371 (concat half value half
3372 (if (> (% width 2) 0) (char-to-string fill))))))
3374 (defun ses-center-span (value &optional fill)
3375 "Print VALUE, centered within the span that starts in the current column
3376 and continues until the next nonblank column. FILL specifies the fill
3377 character (default = space)."
3378 (let ((end (1+ col)))
3379 (while (and (< end ses--numcols)
3380 (memq (ses-cell-value row end) '(nil *skip*)))
3381 (setq end (1+ end)))
3382 (ses-center value (- end col 1) fill)))
3384 (defun ses-dashfill (value &optional span)
3385 "Print VALUE centered using dashes. SPAN indicates how many rightward
3386 columns to include in width (default = 0)."
3387 (ses-center value span ?-))
3389 (defun ses-dashfill-span (value)
3390 "Print VALUE, centered using dashes within the span that starts in the
3391 current column and continues until the next nonblank column."
3392 (ses-center-span value ?-))
3394 (defun ses-tildefill-span (value)
3395 "Print VALUE, centered using tildes within the span that starts in the
3396 current column and continues until the next nonblank column."
3397 (ses-center-span value ?~))
3399 (defun ses-unsafe (value)
3400 "Substitute for an unsafe formula or printer"
3401 (error "Unsafe formula or printer"))
3403 ;;All standard printers are safe, including ses-unsafe!
3404 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3405 (put x 'side-effect-free t))
3407 (defun ses-unload-function ()
3408 "Unload the Simple Emacs Spreadsheet."
3409 (dolist (fun '(copy-region-as-kill yank))
3410 (ad-remove-advice fun 'around (intern (concat "ses-" (symbol-name fun))))
3411 (ad-update fun))
3412 ;; continue standard unloading
3413 nil)
3415 (provide 'ses)
3417 ;;; ses.el ends here