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