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