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