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