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