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