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