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