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