1 ;;; ses.el -- Simple Emacs Spreadsheet -*- lexical-binding:t -*-
3 ;; Copyright (C) 2002-2014 Free Software Foundation, Inc.
5 ;; Author: Jonathan Yavner <jyavner@member.fsf.org>
6 ;; Maintainer: Vincent Belaïche <vincentb1@users.sourceforge.net>
7 ;; Keywords: spreadsheet Dijkstra
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; * split (catch 'cycle ...) call back into one or more functions
29 ;; * Use $ or … for truncated fields
30 ;; * Add command to make a range of columns be temporarily invisible.
31 ;; * Allow paste of one cell to a range of cells -- copy formula to each.
32 ;; * Do something about control characters & octal codes in cell print
33 ;; areas. Use string-width?
34 ;; * Input validation functions. How specified?
35 ;; * Faces (colors & styles) in print cells.
36 ;; * Move a column by dragging its letter in the header line.
37 ;; * Left-margin column for row number.
38 ;; * Move a row by dragging its number in the left-margin.
42 ;; Cycles used to be detected by stationarity of ses--deferred-recalc. This was
43 ;; working fine in most cases, however failed in some cases of several path
46 ;; The current algorithm is based on Dijkstra's algorithm. The cycle length is
47 ;; stored in some cell property. In order not to reset in all cells such
48 ;; property at each update, the cycle length is stored in this property along
49 ;; with some update attempt id that is incremented at each update. The current
50 ;; update id is ses--Dijkstra-attempt-nb. In case there is a cycle the cycle
51 ;; length diverge to infinite so it will exceed ses--Dijkstra-weight-bound at
52 ;; some point of time that allows detection. Otherwise it converges to the
53 ;; longest path length in the update tree.
59 (eval-when-compile (require 'cl-lib
))
62 ;;----------------------------------------------------------------------------
63 ;; User-customizable variables
64 ;;----------------------------------------------------------------------------
67 "Simple Emacs Spreadsheet."
70 :link
'(custom-manual "(ses) Top")
74 (defcustom ses-initial-size
'(1 .
1)
75 "Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
77 :type
'(cons (integer :tag
"numrows") (integer :tag
"numcols")))
79 (defcustom ses-initial-column-width
7
80 "Initial width of columns in a new spreadsheet."
82 :type
'(integer :match
(lambda (widget value
) (> value
0))))
84 (defcustom ses-initial-default-printer
"%.7g"
85 "Initial default printer for a new spreadsheet."
88 (list :tag
"Parenthesized string" string
)
91 (defcustom ses-after-entry-functions
'(forward-char)
92 "Things to do after entering a value into a cell.
93 An abnormal hook that usually runs a cursor-movement function.
94 Each function is called with ARG=1."
97 :options
'(forward-char backward-char next-line previous-line
))
99 (defcustom ses-mode-hook nil
100 "Hook functions to be run upon entering SES mode."
105 ;;----------------------------------------------------------------------------
106 ;; Global variables and constants
107 ;;----------------------------------------------------------------------------
109 (defvar ses-read-cell-history nil
110 "List of formulas that have been typed in.")
112 (defvar ses-read-printer-history nil
113 "List of printer functions that have been typed in.")
115 (easy-menu-define ses-header-line-menu nil
116 "Context menu when mouse-3 is used on the header-line in an SES buffer."
118 ["Set current row" ses-set-header-row t
]
119 ["Unset row" ses-unset-header-row
(> ses--header-row
0)]))
121 (defconst ses-mode-map
122 (let ((keys `("\C-c\M-\C-l" ses-reconstruct-all
123 "\C-c\C-l" ses-recalculate-all
124 "\C-c\C-n" ses-renarrow-buffer
125 "\C-c\C-c" ses-recalculate-cell
126 "\C-c\M-\C-s" ses-sort-column
127 "\C-c\M-\C-h" ses-set-header-row
128 "\C-c\C-t" ses-truncate-cell
130 "\C-c\C-p" ses-read-default-printer
131 "\M-\C-l" ses-reprint-all
132 [?\S-\C-l
] ses-reprint-all
133 [header-line down-mouse-3
] ,ses-header-line-menu
134 [header-line mouse-2
] ses-sort-column-click
))
135 (newmap (make-sparse-keymap)))
137 (define-key (1value newmap
) (car keys
) (cadr keys
))
138 (setq keys
(cddr keys
)))
140 "Local keymap for Simple Emacs Spreadsheet.")
142 (easy-menu-define ses-menu ses-mode-map
143 "Menu bar menu for SES."
145 ["Insert row" ses-insert-row
(ses-in-print-area)]
146 ["Delete row" ses-delete-row
(ses-in-print-area)]
147 ["Insert column" ses-insert-column
(ses-in-print-area)]
148 ["Delete column" ses-delete-column
(ses-in-print-area)]
149 ["Set column printer" ses-read-column-printer t
]
150 ["Set column width" ses-set-column-width t
]
151 ["Set default printer" ses-read-default-printer t
]
152 ["Jump to cell" ses-jump t
]
153 ["Set cell printer" ses-read-cell-printer t
]
154 ["Recalculate cell" ses-recalculate-cell t
]
155 ["Truncate cell display" ses-truncate-cell t
]
156 ["Export values" ses-export-tsv t
]
157 ["Export formulas" ses-export-tsf t
]))
159 (defconst ses-mode-edit-map
160 (let ((keys '("\C-c\C-r" ses-insert-range
161 "\C-c\C-s" ses-insert-ses-range
162 [S-mouse-3
] ses-insert-range-click
163 [C-S-mouse-3
] ses-insert-ses-range-click
164 "\M-\C-i" lisp-complete-symbol
))
165 (newmap (make-sparse-keymap)))
166 (set-keymap-parent newmap minibuffer-local-map
)
168 (define-key newmap
(pop keys
) (pop keys
)))
170 "Local keymap for SES minibuffer cell-editing.")
172 ;Local keymap for SES print area
173 (defalias 'ses-mode-print-map
174 (let ((keys '([backtab] backward-char
175 [tab] ses-forward-or-insert
176 "\C-i" ses-forward-or-insert ; Needed for ses-coverage.el?
177 "\M-o" ses-insert-column
178 "\C-o" ses-insert-row
180 "\M-k" ses-delete-column
182 "\C-k" ses-delete-row
183 "\C-j" ses-append-row-jump-first-column
185 "\M-H" ses-mark-column
186 "\C-d" ses-clear-cell-forward
187 "\C-?" ses-clear-cell-backward
192 "c" ses-recalculate-cell
194 "p" ses-read-cell-printer
195 "t" ses-truncate-cell
196 "w" ses-set-column-width
197 "x" ses-export-keymap
198 "\M-p" ses-read-column-printer))
199 (repl '(;;We'll replace these wherever they appear in the keymap
200 clipboard-kill-region ses-kill-override
201 end-of-line ses-end-of-line
202 kill-line ses-delete-row
203 kill-region ses-kill-override
204 open-line ses-insert-row))
205 (numeric "0123456789.-")
206 (newmap (make-keymap)))
207 ;;Get rid of printables
208 (suppress-keymap newmap t)
209 ;;These keys insert themselves as the beginning of a numeric value
210 (dotimes (x (length numeric))
211 (define-key newmap (substring numeric x (1+ x)) 'ses-read-cell))
212 ;;Override these global functions wherever they're bound
214 (substitute-key-definition (car repl) (cadr repl) newmap
215 (current-global-map))
216 (setq repl (cddr repl)))
217 ;;Apparently substitute-key-definition doesn't catch this?
218 (define-key newmap [(menu-bar) edit cut] 'ses-kill-override)
219 ;;Define our other local keys
221 (define-key newmap (car keys) (cadr keys))
222 (setq keys (cddr keys)))
225 ;;Helptext for ses-mode wants keymap as variable, not function
226 (defconst ses-mode-print-map (symbol-function 'ses-mode-print-map))
228 ;;Key map used for 'x' key.
229 (defalias 'ses-export-keymap
230 (let ((map (make-sparse-keymap "SES export")))
231 (define-key map "T" (cons " tab-formulas" 'ses-export-tsf))
232 (define-key map "t" (cons " tab-values" 'ses-export-tsv))
235 (defconst ses-print-data-boundary "\n\014\n"
236 "Marker string denoting the boundary between print area and data area.")
238 (defconst ses-initial-global-parameters
239 "\n( ;Global parameters (these are read first)\n 2 ;SES file-format\n 1 ;numrows\n 1 ;numcols\n)\n\n"
240 "Initial contents for the three-element list at the bottom of the data area.")
242 (defconst ses-initial-global-parameters-re
243 "\n( ;Global parameters (these are read first)\n [23] ;SES file-format\n [0-9]+ ;numrows\n [0-9]+ ;numcols\n\\( [0-9]+ ;numlocprn\n\\)?)\n\n"
244 "Match Global parameters for .")
246 (defconst ses-initial-file-trailer
247 ";; Local Variables:\n;; mode: ses\n;; End:\n"
248 "Initial contents for the file-trailer area at the bottom of the file.")
250 (defconst ses-initial-file-contents
251 (concat " \n" ; One blank cell in print area.
252 ses-print-data-boundary
253 "(ses-cell A1 nil nil nil nil)\n" ; One blank cell in data area.
254 "\n" ; End-of-row terminator for the one row in data area.
255 "(ses-column-widths [7])\n"
256 "(ses-column-printers [nil])\n"
257 "(ses-default-printer \"%.7g\")\n"
258 "(ses-header-row 0)\n"
259 ses-initial-global-parameters
260 ses-initial-file-trailer)
261 "The initial contents of an empty spreadsheet.")
263 (defconst ses-box-prop '(:box (:line-width 2 :style released-button))
264 "Display properties to create a raised box for cells in the header line.")
266 (defconst ses-standard-printer-functions
267 '(ses-center ses-center-span ses-dashfill ses-dashfill-span
269 "List of print functions to be included in initial history of printer
270 functions. None of these standard-printer functions is suitable for use as a
271 column printer or a global-default printer because they invoke the column or
272 default printer and then modify its output.")
275 ;;----------------------------------------------------------------------------
276 ;; Local variables and constants
277 ;;----------------------------------------------------------------------------
280 (defconst ses-localvars
281 '(ses--blank-line ses--cells ses--col-printers
282 ses--col-widths ses--curcell ses--curcell-overlay
284 (ses--local-printer-hashmap . :hashmap)
285 (ses--numlocprn . 0); count of local printers
286 ses--deferred-narrow ses--deferred-recalc
287 ses--deferred-write ses--file-format
288 ses--named-cell-hashmap
289 (ses--header-hscroll . -1) ; Flag for "initial recalc needed"
290 ses--header-row ses--header-string ses--linewidth
291 ses--numcols ses--numrows ses--symbolic-formulas
292 ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
293 ses--Dijkstra-weight-bound
294 ;; This list is useful to speed-up clean-up of symbols when
295 ;; an area containing renamed cell is deleted.
296 ses--renamed-cell-symb-list
297 ;; Global variables that we override
298 mode-line-process next-line-add-newlines transient-mark-mode)
299 "Buffer-local variables used by SES."))
301 (defmacro ses--metaprogramming (exp) (declare (debug t)) (eval exp t))
302 (ses--metaprogramming
303 `(progn ,@(mapcar (lambda (x) `(defvar ,(or (car-safe x) x))) ses-localvars)))
305 (defun ses-set-localvars ()
306 "Set buffer-local and initialize some SES variables."
307 (dolist (x ses-localvars)
310 (set (make-local-variable x) nil))
314 (set (make-local-variable (car x)) (cdr x)))
315 ((eq (cdr x) :hashmap)
316 (set (make-local-variable (car x)) (make-hash-table :test 'eq)))
317 (t (error "Unexpected initializer `%S' in list `ses-localvars' for entry %S"
318 (cdr x) (car x)) ) ))
319 (t (error "Unexpected elements `%S' in list `ses-localvars'" x)))))
321 ;;; This variable is documented as being permitted in file-locals:
322 (put 'ses--symbolic-formulas 'safe-local-variable 'consp)
324 (defconst ses-paramlines-plist
325 '(ses--col-widths -5 ses--col-printers -4 ses--default-printer -3
326 ses--header-row -2 ses--file-format 1 ses--numrows 2
327 ses--numcols 3 ses--numlocprn 4)
328 "Offsets from 'Global parameters' line to various parameter lines in the
329 data area of a spreadsheet.")
331 (defconst ses-paramfmt-plist
332 '(ses--col-widths "(ses-column-widths %S)"
333 ses--col-printers "(ses-column-printers %S)"
334 ses--default-printer "(ses-default-printer %S)"
335 ses--header-row "(ses-header-row %S)"
336 ses--file-format " %S ;SES file-format"
337 ses--numrows " %S ;numrows"
338 ses--numcols " %S ;numcols"
339 ses--numlocprn " %S ;numlocprn")
340 "Formats of 'Global parameters' various parameters in the data
341 area of a spreadsheet.")
344 ;; "Side-effect variables". They are set in one function, altered in
345 ;; another as a side effect, then read back by the first, as a way of
346 ;; passing back more than one value. These declarations are just to make
347 ;; the compiler happy, and to conform to standard Emacs-Lisp practice (I
348 ;; think the make-local-variable trick above is cleaner).
351 (defvar ses-relocate-return nil
352 "Set by `ses-relocate-formula' and `ses-relocate-range', read by
353 `ses-relocate-all'. Set to 'delete if a cell-reference was deleted from a
354 formula--so the formula needs recalculation. Set to 'range if the size of a
355 `ses-range' was changed--so both the formula's value and list of dependents
356 need to be recalculated.")
358 (defvar ses-call-printer-return nil
359 "Set to t if last cell printer invoked by `ses-call-printer' requested
360 left-justification of the result. Set to error-signal if `ses-call-printer'
361 encountered an error during printing. Otherwise nil.")
363 (defvar ses-start-time nil
364 "Time when current operation started. Used by `ses-time-check' to decide
365 when to emit a progress message.")
368 ;;----------------------------------------------------------------------------
370 ;;----------------------------------------------------------------------------
372 (defmacro ses-get-cell (row col)
373 "Return the cell structure that stores information about cell (ROW,COL)."
375 `(aref (aref ses--cells ,row) ,col))
377 (cl-defstruct (ses-cell
379 (:constructor ses-make-cell
380 (&optional symbol formula printer references))
382 ;; This is treated as an 4-elem array in various places.
383 ;; Mostly in ses-set-cell.
384 (:type vector) ;Not named.
385 (:conc-name ses-cell--))
386 symbol formula printer references properties)
388 (cl-defstruct (ses--locprn
390 (:constructor ses-make-local-printer-info
391 (def &optional (compiled (ses-local-printer-compile def))
392 (number ses--numlocprn))))
398 (defmacro ses-cell-symbol (row &optional col)
399 "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value. (0,0) => A1."
401 `(ses-cell--symbol ,(if col `(ses-get-cell ,row ,col) row)))
402 (put 'ses-cell-symbol 'safe-function t)
404 (defmacro ses-cell-formula (row &optional col)
405 "From a CELL or a pair (ROW,COL), get the function that computes its value."
407 `(ses-cell--formula ,(if col `(ses-get-cell ,row ,col) row)))
409 (defmacro ses-cell-printer (row &optional col)
410 "From a CELL or a pair (ROW,COL), get the function that prints its value."
412 `(ses-cell--printer ,(if col `(ses-get-cell ,row ,col) row)))
414 (defmacro ses-cell-references (row &optional col)
415 "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
416 functions refer to its value."
418 `(ses-cell--references ,(if col `(ses-get-cell ,row ,col) row)))
420 (defun ses-cell-p (cell)
421 "Return non-nil if CELL is a cell of current buffer."
424 (eq cell (let ((rowcol (ses-sym-rowcol (ses-cell-symbol cell))))
426 (ses-get-cell (car rowcol) (cdr rowcol)))))))
429 (defun ses--alist-get (key alist &optional remove)
430 "Get the value associated to KEY in ALIST."
434 (macroexp-let2 macroexp-copyable-p k key
435 (gv-letplace (getter setter) alist
436 (macroexp-let2 nil p `(assq ,k ,getter)
437 (funcall do `(cdr ,p)
440 `(if ,p (setcdr ,p ,v)
442 `(cons (setq ,p (cons ,k ,v))
445 ((null remove) set-exp)
447 `(if ,p ,(funcall setter `(delq ,p ,getter))))
452 `(delq ,p ,getter)))))))))))))))
453 (ignore remove) ;;Silence byte-compiler.
454 (cdr (assoc key alist)))
456 (defmacro ses--letref (vars place &rest body)
457 (declare (indent 2) (debug (sexp form &rest body)))
458 (gv-letplace (getter setter) place
459 `(cl-macrolet ((,(nth 0 vars) () ',getter)
460 (,(nth 1 vars) (v) (funcall ,setter v)))
463 (defmacro ses-cell-property (property-name row &optional col)
464 "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
466 When COL is omitted, CELL=ROW is a cell object. When COL is
467 present ROW and COL are the integer coordinates of the cell of
470 `(ses--alist-get ,property-name
471 (ses-cell--properties
472 ,(if col `(ses-get-cell ,row ,col) row))))
474 (defmacro ses-cell-property-pop (property-name row &optional col)
475 "From a CELL or a pair (ROW,COL), get and remove the property value of
476 the corresponding cell with name PROPERTY-NAME."
477 `(ses--letref (pget pset)
478 (ses--alist-get ,property-name
479 (ses-cell--properties
480 ,(if col `(ses-get-cell ,row ,col) row))
482 (prog1 (pget) (pset nil))))
484 (defmacro ses-cell-value (row &optional col)
485 "From a CELL or a pair (ROW,COL), get the current value for that cell."
486 `(symbol-value (ses-cell-symbol ,row ,col)))
488 (defmacro ses-col-width (col)
489 "Return the width for column COL."
490 `(aref ses--col-widths ,col))
492 (defmacro ses-col-printer (col)
493 "Return the default printer for column COL."
494 `(aref ses--col-printers ,col))
496 (defmacro ses-sym-rowcol (sym)
497 "From a cell-symbol SYM, gets the cons (row . col). A1 => (0 . 0). Result
498 is nil if SYM is not a symbol that names a cell."
499 `(let ((rc (and (symbolp ,sym) (get ,sym 'ses-cell))))
500 (if (eq rc :ses-named)
501 (gethash ,sym ses--named-cell-hashmap)
504 (defun ses-is-cell-sym-p (sym)
505 "Check whether SYM point at a cell of this spread sheet."
506 (let ((rowcol (get sym 'ses-cell)))
508 (if (eq rowcol :ses-named)
509 (and ses--named-cell-hashmap (gethash sym ses--named-cell-hashmap))
510 (and (< (car rowcol) ses--numrows)
511 (< (cdr rowcol) ses--numcols)
512 (eq (ses-cell-symbol (car rowcol) (cdr rowcol)) sym))))))
514 (defun ses--cell (sym value formula printer references)
515 "Load a cell SYM from the spreadsheet file. Does not recompute VALUE from
516 FORMULA, does not reprint using PRINTER, does not check REFERENCES.
517 Safety-checking for FORMULA and PRINTER are deferred until first use."
518 (let ((rowcol (ses-sym-rowcol sym)))
519 (ses-formula-record formula)
520 (ses-printer-record printer)
521 (unless formula (setq formula value))
523 (eq safe-functions t)
524 (setq formula `(ses-safe-formula ,formula)))
527 (eq safe-functions t)
528 (setq printer `(ses-safe-printer ,printer)))
529 (setf (ses-get-cell (car rowcol) (cdr rowcol))
530 (ses-make-cell sym formula printer references)))
533 (defun ses-local-printer-compile (printer)
534 "Convert local printer function into faster printer
537 ((functionp printer) printer)
539 `(lambda (x) (format ,printer x)))
540 (t (error "Invalid printer %S" printer))))
542 (defun ses--local-printer (name def)
543 "Define a local printer with name NAME and definition DEF.
544 Return the printer info."
547 (ses-printer-validate def))
548 (error "Invalid local printer definition"))
549 (and (gethash name ses--local-printer-hashmap)
550 (error "Duplicate printer definition %S" name))
551 (add-to-list 'ses-read-printer-history (symbol-name name))
553 (ses-make-local-printer-info (ses-safe-printer def))
554 ses--local-printer-hashmap))
556 (defmacro ses-column-widths (widths)
557 "Load the vector of column widths from the spreadsheet file. This is a
558 macro to prevent propagate-on-load viruses."
559 (or (and (vectorp widths) (= (length widths) ses--numcols))
560 (error "Bad column-width vector"))
561 ;;To save time later, we also calculate the total width of each line in the
562 ;;print area (excluding the terminating newline)
563 (setq ses--col-widths widths
564 ses--linewidth (apply '+ -1 (mapcar '1+ widths))
565 ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
568 (defmacro ses-column-printers (printers)
569 "Load the vector of column printers from the spreadsheet file and checks
570 them for safety. This is a macro to prevent propagate-on-load viruses."
571 (or (and (vectorp printers) (= (length printers) ses--numcols))
572 (error "Bad column-printers vector"))
573 (dotimes (x ses--numcols)
574 (aset printers x (ses-safe-printer (aref printers x))))
575 (setq ses--col-printers printers)
576 (mapc 'ses-printer-record printers)
579 (defmacro ses-default-printer (def)
580 "Load the global default printer from the spreadsheet file and checks it
581 for safety. This is a macro to prevent propagate-on-load viruses."
582 (setq ses--default-printer (ses-safe-printer def))
583 (ses-printer-record def)
586 (defmacro ses-header-row (row)
587 "Load the header row from the spreadsheet file and checks it
588 for safety. This is a macro to prevent propagate-on-load viruses."
589 (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
590 (error "Bad header-row"))
591 (setq ses--header-row row)
594 (defmacro ses-dorange (curcell &rest body)
595 "Execute BODY repeatedly, with the variables `row' and `col' set to each
596 cell in the range specified by CURCELL. The range is available in the
597 variables `minrow', `maxrow', `mincol', and `maxcol'."
598 (declare (indent defun) (debug (form body)))
599 (let ((cur (make-symbol "cur"))
600 (min (make-symbol "min"))
601 (max (make-symbol "max"))
602 (r (make-symbol "r"))
603 (c (make-symbol "c")))
604 `(let* ((,cur ,curcell)
605 (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
606 (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
607 (let ((minrow (car ,min))
612 (if (or (> minrow maxrow) (> mincol maxcol))
613 (error "Empty range"))
614 (dotimes (,r (- maxrow minrow -1))
615 (setq row (+ ,r minrow))
616 (dotimes (,c (- maxcol mincol -1))
617 (setq col (+ ,c mincol))
620 ;;Support for coverage testing.
621 (defmacro 1value (form)
622 "For code-coverage testing, indicate that FORM is expected to always have
626 (defmacro noreturn (form)
627 "For code-coverage testing, indicate that FORM will always signal an error."
632 ;;----------------------------------------------------------------------------
634 ;;----------------------------------------------------------------------------
636 (defun ses-vector-insert (array idx new)
637 "Create a new vector which is one larger than ARRAY and has NEW inserted
639 (let* ((len (length array))
640 (result (make-vector (1+ len) new)))
643 (if (< x idx) x (1+ x))
647 ;;Allow ARRAY to be a symbol for use in buffer-undo-list
648 (defun ses-vector-delete (array idx count)
649 "Create a new vector which is a copy of ARRAY with COUNT objects removed
650 starting at element IDX. ARRAY is either a vector or a symbol whose value
651 is a vector--if a symbol, the new vector is assigned as the symbol's value."
652 (let* ((a (if (arrayp array) array (symbol-value array)))
653 (len (- (length a) count))
654 (result (make-vector len nil)))
656 (aset result x (aref a (if (< x idx) x (+ x count)))))
661 (defun ses-delete-line (count)
662 "Like `kill-line', but no kill ring."
665 (delete-region pos (point))))
667 (defun ses-printer-validate (printer)
668 "Signal an error if PRINTER is not a valid SES cell printer."
671 ;; printer is a local printer
672 (and (symbolp printer) (gethash printer ses--local-printer-hashmap))
674 (and (stringp (car-safe printer)) (not (cdr printer)))
675 (error "Invalid printer function %S" printer))
678 (defun ses-printer-record (printer)
679 "Add PRINTER to `ses-read-printer-history' if not already there, after first
680 checking that it is a valid printer function."
681 (ses-printer-validate printer)
682 ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
684 (add-to-list 'ses-read-printer-history (prin1-to-string printer))))
686 (defun ses-formula-record (formula)
687 "If FORMULA is of the form 'symbol, add it to the list of symbolic formulas
688 for this spreadsheet."
689 (when (and (eq (car-safe formula) 'quote)
690 (symbolp (cadr formula)))
691 (add-to-list 'ses--symbolic-formulas
692 (list (symbol-name (cadr formula))))))
694 (defun ses-column-letter (col)
695 "Return the alphabetic name of column number COL.
696 0-25 become A-Z; 26-701 become AA-ZZ, and so on."
697 (let ((units (char-to-string (+ ?A (% col 26)))))
700 (concat (ses-column-letter (1- (/ col 26))) units))))
702 (defun ses-create-cell-symbol (row col)
703 "Produce a symbol that names the cell (ROW,COL). (0,0) => 'A1."
704 (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))
706 (defun ses-decode-cell-symbol (str)
707 "Decode a symbol \"A1\" => (0,0). Return nil if STR is not a
708 canonical cell name."
709 (let (case-fold-search)
710 (and (string-match "\\`\\([A-Z]+\\)\\([0-9]+\\)\\'" str)
711 (let* ((col-str (match-string-no-properties 1 str))
714 (col-idx (1- (length col-str)))
715 (row (1- (string-to-number
716 (match-string-no-properties 2 str)))))
721 (setq col (+ col (* (- (aref col-str col-idx) ?A)
723 col-base (* col-base 26)
724 col-idx (1- col-idx))
726 (setq col (+ col col-base)))))
729 (defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
730 "Create buffer-local variables for cells. This is undoable."
731 (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
734 (dotimes (row (1+ (- maxrow minrow)))
735 (dotimes (col (1+ (- maxcol mincol)))
736 (setq xrow (+ row minrow)
738 sym (ses-create-cell-symbol xrow xcol))
739 (put sym 'ses-cell (cons xrow xcol))
740 (make-local-variable sym)))))
742 (defun ses-create-cell-variable (sym row col)
743 "Create a buffer-local variable `SYM' for cell at position (ROW, COL).
745 SYM is the symbol for that variable, ROW and COL are integers for
746 row and column of the cell, with numbering starting from 0.
748 Return nil in case of failure."
749 (unless (local-variable-p sym)
750 (make-local-variable sym)
751 (if (let (case-fold-search) (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name sym)))
752 (put sym 'ses-cell (cons row col))
753 (put sym 'ses-cell :ses-named)
754 (setq ses--named-cell-hashmap (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
755 (puthash sym (cons row col) ses--named-cell-hashmap))))
757 ;; We do not delete the ses-cell properties for the cell-variables, in
758 ;; case a formula that refers to this cell is in the kill-ring and is
759 ;; later pasted back in.
760 (defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
761 "Destroy buffer-local variables for cells. This is undoable."
763 (dotimes (row (1+ (- maxrow minrow)))
764 (dotimes (col (1+ (- maxcol mincol)))
765 (let ((xrow (+ row minrow)) (xcol (+ col mincol)))
766 (setq sym (if (and (< xrow ses--numrows) (< xcol ses--numcols))
767 (ses-cell-symbol xrow xcol)
768 (ses-create-cell-symbol xrow xcol))))
770 (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
772 (kill-local-variable sym))))
773 (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
776 (defun ses-reset-header-string ()
777 "Flag the header string for update. Upon undo, the header string will be
779 (push '(apply ses-reset-header-string) buffer-undo-list)
780 (setq ses--header-hscroll -1))
782 ;;Split this code off into a function to avoid coverage-testing difficulties
783 (defun ses-time-check (format arg)
784 "If `ses-start-time' is more than a second ago, call `message' with FORMAT
785 and (eval ARG) and reset `ses-start-time' to the current time."
786 (when (> (- (float-time) ses-start-time) 1.0)
787 (message format (eval arg))
788 (setq ses-start-time (float-time)))
792 ;;----------------------------------------------------------------------------
794 ;;----------------------------------------------------------------------------
796 (defmacro ses-set-cell (row col field val)
797 "Install VAL as the contents for field FIELD (named by a quoted symbol) of
798 cell (ROW,COL). This is undoable. The cell's data will be updated through
799 `post-command-hook'."
803 (let* ((cell (ses-get-cell row col))
805 ,(let ((field (eval field t)))
806 (if (eq field 'value)
807 `(ses-set-with-undo (ses-cell-symbol cell) val)
808 ;; (let* ((slots (get 'ses-cell 'cl-struct-slots))
809 ;; (slot (or (assq field slots)
810 ;; (error "Unknown field %S" field)))
811 ;; (idx (- (length slots)
812 ;; (length (memq slot slots)))))
813 ;; `(ses-aset-with-undo cell ,idx val))
814 (let ((getter (intern-soft (format "ses-cell--%s" field))))
815 `(ses-setter-with-undo
818 (lambda (newval cell)
819 (setf (,getter cell) newval))))
822 (add-to-list 'ses--deferred-write (cons row col))))
823 nil)) ; Make coverage-tester happy.
825 (defun ses-cell-set-formula (row col formula)
826 "Store a new formula for (ROW . COL) and enqueue the cell for
827 recalculation via `post-command-hook'. Updates the reference lists for the
828 cells that this cell refers to. Does not update cell value or reprint the
829 cell. To avoid inconsistencies, this function is not interruptible, which
830 means Emacs will crash if FORMULA contains a circular list."
831 (let* ((cell (ses-get-cell row col))
832 (old (ses-cell-formula cell)))
833 (let ((sym (ses-cell-symbol cell))
834 (oldref (ses-formula-references old))
835 (newref (ses-formula-references formula))
838 (cl-pushnew sym ses--deferred-recalc)
839 ;;Delete old references from this cell. Skip the ones that are also
842 (unless (memq ref newref)
843 (setq x (ses-sym-rowcol ref)
846 (ses-set-cell xrow xcol 'references
847 (delq sym (ses-cell-references xrow xcol)))))
848 ;;Add new ones. Skip ones left over from old list
850 (setq x (ses-sym-rowcol ref)
853 x (ses-cell-references xrow xcol))
855 (ses-set-cell xrow xcol 'references (cons sym x))))
856 (ses-formula-record formula)
857 (ses-set-cell row col 'formula formula))))
860 (defun ses-repair-cell-reference-all ()
861 "Repair cell reference and warn if there was some reference corruption."
864 ;; Step 1, reset :ses-repair-reference cell property in the whole sheet.
865 (dotimes (row ses--numrows)
866 (dotimes (col ses--numcols)
867 (let ((references (ses-cell-property-pop :ses-repair-reference
870 (push (list (ses-cell-symbol row col)
875 ;; Step 2, build new.
876 (dotimes (row ses--numrows)
877 (dotimes (col ses--numcols)
878 (let* ((cell (ses-get-cell row col))
879 (sym (ses-cell-symbol cell))
880 (formula (ses-cell-formula cell))
881 (new-ref (ses-formula-references formula)))
882 (dolist (ref new-ref)
883 (let ((rowcol (ses-sym-rowcol ref)))
884 (cl-pushnew sym (ses-cell-property :ses-repair-reference
888 ;; Step 3, overwrite with check.
889 (dotimes (row ses--numrows)
890 (dotimes (col ses--numcols)
891 (let* ((cell (ses-get-cell row col))
892 (irrelevant (ses-cell-references cell))
893 (new-ref (ses-cell-property-pop :ses-repair-reference cell))
895 (dolist (ref new-ref)
896 (if (memq ref irrelevant)
897 (setq irrelevant (delq ref irrelevant))
899 (ses-set-cell row col 'references new-ref)
900 (when (or missing irrelevant)
901 (push `( ,(ses-cell-symbol cell)
902 ,@(and missing (list :missing missing))
903 ,@(and irrelevant (list :irrelevant irrelevant)))
906 (warn "----------------------------------------------------------------
907 Some references were corrupted.
909 The following is a list where each element ELT is such
910 that (car ELT) is the reference of cell CELL with corruption,
911 and (cdr ELT) is a property list where
913 * property `:corrupt-property' means that
914 property `:ses-repair-reference' of cell CELL was initially non
917 * property `:missing' is a list of missing references
919 * property `:irrelevant' is a list of non needed references
922 (message "No reference corruption found"))))
924 (defun ses-calculate-cell (row col force)
925 "Calculate and print the value for cell (ROW,COL) using the cell's formula
926 function and print functions, if any. Result is nil for normal operation, or
927 the error signal if the formula or print function failed. The old value is
928 left unchanged if it was *skip* and the new value is nil.
929 Any cells that depend on this cell are queued for update after the end of
930 processing for the current keystroke, unless the new value is the same as
931 the old and FORCE is nil."
932 (let ((cell (ses-get-cell row col))
933 cycle-error formula-error printer-error)
934 (let ((oldval (ses-cell-value cell))
935 (formula (ses-cell-formula cell))
937 this-cell-Dijkstra-attempt+1)
938 (when (eq (car-safe formula) 'ses-safe-formula)
939 (setq formula (ses-safe-formula (cadr formula)))
940 (ses-set-cell row col 'formula formula))
942 (setq newval (eval formula))
944 ;; Variable `sig' can't be nil.
945 (nconc sig (list (ses-cell-symbol cell)))
946 (setq formula-error sig
948 (if (and (not newval) (eq oldval '*skip*))
949 ;; Don't lose the *skip* --- previous field spans this one.
950 (setq newval '*skip*))
952 (when (or force (not (eq newval oldval)))
953 (cl-pushnew (cons row col) ses--deferred-write :test #'equal) ; In case force=t.
954 (ses--letref (pget pset)
955 (ses-cell-property :ses-Dijkstra-attempt cell)
956 (let ((this-cell-Dijkstra-attempt (pget)))
957 (if (null this-cell-Dijkstra-attempt)
959 (setq this-cell-Dijkstra-attempt
960 (cons ses--Dijkstra-attempt-nb 0)))
961 (unless (= ses--Dijkstra-attempt-nb
962 (car this-cell-Dijkstra-attempt))
963 (setcar this-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
964 (setcdr this-cell-Dijkstra-attempt 0)))
965 (setq this-cell-Dijkstra-attempt+1
966 (1+ (cdr this-cell-Dijkstra-attempt)))))
967 (ses-set-cell row col 'value newval)
968 (dolist (ref (ses-cell-references cell))
969 (cl-pushnew ref ses--deferred-recalc)
970 (ses--letref (pget pset)
971 (let ((ref-rowcol (ses-sym-rowcol ref)))
973 :ses-Dijkstra-attempt
974 (car ref-rowcol) (cdr ref-rowcol)))
975 (let ((ref-cell-Dijkstra-attempt (pget)))
977 (if (null ref-cell-Dijkstra-attempt)
979 (setq ref-cell-Dijkstra-attempt
980 (cons ses--Dijkstra-attempt-nb
981 this-cell-Dijkstra-attempt+1)))
982 (if (= (car ref-cell-Dijkstra-attempt) ses--Dijkstra-attempt-nb)
983 (setcdr ref-cell-Dijkstra-attempt
984 (max (cdr ref-cell-Dijkstra-attempt)
985 this-cell-Dijkstra-attempt+1))
986 (setcar ref-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
987 (setcdr ref-cell-Dijkstra-attempt
988 this-cell-Dijkstra-attempt+1)))))
990 (when (> this-cell-Dijkstra-attempt+1 ses--Dijkstra-weight-bound)
991 ;; Update print of this cell.
992 (throw 'cycle (setq formula-error
993 `(error ,(format "Found cycle on cells %S"
994 (ses-cell-symbol cell)))
995 cycle-error formula-error)))))))
996 (setq printer-error (ses-print-cell row col))
999 (error (error-message-string cycle-error)))
1000 formula-error printer-error)))
1002 (defun ses-clear-cell (row col)
1003 "Delete formula and printer for cell (ROW,COL)."
1004 (ses-set-cell row col 'printer nil)
1005 (ses-cell-set-formula row col nil))
1007 (defcustom ses-self-reference-early-detection nil
1008 "True if cycle detection is early for cells that refer to themselves."
1013 (defun ses-update-cells (list &optional force)
1014 "Recalculate cells in LIST, checking for dependency loops. Prints
1015 progress messages every second. Dependent cells are not recalculated
1016 if the cell's value is unchanged and FORCE is nil."
1017 (let ((ses--deferred-recalc list)
1020 curlist prevlist this-sym this-rowcol formula)
1021 (with-temp-message " "
1022 (while ses--deferred-recalc
1023 ;; In each loop, recalculate cells that refer only to other cells that
1024 ;; have already been recalculated or aren't in the recalculation region.
1025 ;; Repeat until all cells have been processed or until the set of cells
1026 ;; being worked on stops changing.
1028 (message "Recalculating... (%d cells left)"
1029 (length ses--deferred-recalc)))
1030 (setq curlist ses--deferred-recalc
1031 ses--deferred-recalc nil
1034 ;; this-sym has to be popped from curlist *BEFORE* the check, and not
1035 ;; after because of the case of cells referring to themselves.
1036 (setq this-sym (pop curlist)
1037 this-rowcol (ses-sym-rowcol this-sym)
1038 formula (ses-cell-formula (car this-rowcol)
1041 (dolist (ref (ses-formula-references formula))
1042 (if (and ses-self-reference-early-detection (eq ref this-sym))
1043 (error "Cycle found: cell %S is self-referring" this-sym)
1044 (when (or (memq ref curlist)
1045 (memq ref ses--deferred-recalc))
1046 ;; This cell refers to another that isn't done yet
1047 (cl-pushnew this-sym ses--deferred-recalc :test #'equal)
1049 ;; ses-update-cells is called from post-command-hook, so
1050 ;; inhibit-quit is implicitly bound to t.
1052 ;; Abort the recalculation. User will probably undo now.
1054 (ses-calculate-cell (car this-rowcol) (cdr this-rowcol) force)))
1055 (dolist (ref ses--deferred-recalc)
1056 (cl-pushnew ref nextlist :test #'equal)))
1057 (when ses--deferred-recalc
1058 ;; Just couldn't finish these.
1059 (dolist (x ses--deferred-recalc)
1060 (let ((this-rowcol (ses-sym-rowcol x)))
1061 (ses-set-cell (car this-rowcol) (cdr this-rowcol) 'value '*error*)
1062 (1value (ses-print-cell (car this-rowcol) (cdr this-rowcol)))))
1063 (error "Circular references: %s" ses--deferred-recalc))
1065 ;; Can't use save-excursion here: if the cell under point is updated,
1066 ;; save-excursion's marker will move past the cell.
1070 ;;----------------------------------------------------------------------------
1072 ;;----------------------------------------------------------------------------
1074 (defun ses-in-print-area ()
1075 "Return t if point is in print area of spreadsheet."
1076 (<= (point) ses--data-marker))
1078 ;; We turn off point-motion-hooks and explicitly position the cursor, in case
1079 ;; the intangible properties have gotten screwed up (e.g., when ses-goto-print
1080 ;; is called during a recursive ses-print-cell).
1081 (defun ses-goto-print (row col)
1082 "Move point to print area for cell (ROW,COL)."
1083 (let ((inhibit-point-motion-hooks t)
1085 (goto-char (point-min))
1087 ;; Calculate column position.
1089 (setq n (+ n (ses-col-width c) 1)))
1090 ;; Move to the position.
1091 (and (> n (move-to-column n))
1093 ;; Move point to the bol of next line (for TAB at the last cell).
1096 (defun ses-set-curcell ()
1097 "Set `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
1098 region, or nil if cursor is not at a cell."
1099 (if (or (not mark-active)
1101 (= (region-beginning) (region-end)))
1103 (setq ses--curcell (get-text-property (point) 'intangible))
1105 (let ((bcell (get-text-property (region-beginning) 'intangible))
1106 (ecell (get-text-property (1- (region-end)) 'intangible)))
1107 (when (= (region-end) ses--data-marker)
1108 ;; Correct for overflow.
1109 (setq ecell (get-text-property (- (region-end) 2) 'intangible)))
1110 (setq ses--curcell (if (and bcell ecell)
1115 (defun ses-check-curcell (&rest args)
1116 "Signal an error if `ses--curcell' is inappropriate.
1117 The end marker is appropriate if some argument is 'end.
1118 A range is appropriate if some argument is 'range.
1119 A single cell is appropriate unless some argument is 'needrange."
1120 (if (eq ses--curcell t)
1121 ;; curcell recalculation was postponed, but user typed ahead.
1125 (or (memq 'end args)
1126 (error "Not at cell")))
1127 ((consp ses--curcell)
1128 (or (memq 'range args)
1129 (memq 'needrange args)
1130 (error "Can't use a range")))
1131 ((memq 'needrange args)
1132 (error "Need a range"))))
1134 (defun ses-print-cell (row col)
1135 "Format and print the value of cell (ROW,COL) to the print area.
1136 Use the cell's printer function. If the cell's new print form is too wide,
1137 it will spill over into the following cell, but will not run off the end of the
1138 row or overwrite the next non-nil field. Result is nil for normal operation,
1139 or the error signal if the printer function failed and the cell was formatted
1140 with \"%s\". If the cell's value is *skip*, nothing is printed because the
1141 preceding cell has spilled over."
1142 (catch 'ses-print-cell
1143 (let* ((cell (ses-get-cell row col))
1144 (value (ses-cell-value cell))
1145 (printer (ses-cell-printer cell))
1147 text sig startpos x)
1148 ;; Create the string to print.
1151 ;; Don't print anything.
1152 (throw 'ses-print-cell nil))
1153 ((eq value '*error*)
1154 (setq text (make-string (ses-col-width col) ?#)))
1156 ;; Deferred safety-check on printer.
1157 (if (eq (car-safe printer) 'ses-safe-printer)
1158 (ses-set-cell row col 'printer
1159 (setq printer (ses-safe-printer (cadr printer)))))
1161 (setq text (ses-call-printer (or printer
1162 (ses-col-printer col)
1163 ses--default-printer)
1165 (if (consp ses-call-printer-return)
1166 ;; Printer returned an error.
1167 (setq sig ses-call-printer-return))))
1168 ;; Adjust print width to match column width.
1169 (let ((width (ses-col-width col))
1170 (len (string-width text)))
1173 ;; Fill field to length with spaces.
1174 (setq len (make-string (- width len) ?\s)
1175 text (if (or (stringp value)
1176 (eq ses-call-printer-return t))
1178 (concat len text))))
1180 ;; Spill over into following cells, if possible.
1181 (let ((maxwidth width))
1182 (while (and (> len maxwidth)
1183 (< maxcol ses--numcols)
1184 (or (not (setq x (ses-cell-value row maxcol)))
1187 ;; Set this cell to '*skip* so it won't overwrite our spillover.
1188 (ses-set-cell row maxcol 'value '*skip*))
1189 (setq maxwidth (+ maxwidth (ses-col-width maxcol) 1)
1190 maxcol (1+ maxcol)))
1191 (if (<= len maxwidth)
1192 ;; Fill to complete width of all the fields spanned.
1193 (setq text (concat text (make-string (- maxwidth len) ?\s)))
1194 ;; Not enough room to end of line or next non-nil field. Truncate
1195 ;; if string or decimal; otherwise fill with error indicator.
1196 (setq sig `(error "Too wide" ,text))
1199 (setq text (truncate-string-to-width text maxwidth 0 ?\s)))
1200 ((and (numberp value)
1201 (string-match "\\.[0-9]+" text)
1204 (- (match-end 0) (match-beginning 0))))))
1205 ;; Turn 6.6666666666e+49 into 6.66e+49. Rounding is too hard!
1206 (setq text (concat (substring text
1208 (- (match-beginning 0) width))
1209 (substring text (match-end 0)))))
1211 (setq text (make-string maxwidth ?#)))))))))
1212 ;; Substitute question marks for tabs and newlines. Newlines are used as
1213 ;; row-separators; tabs could confuse the reimport logic.
1214 (setq text (replace-regexp-in-string "[\t\n]" "?" text))
1215 (ses-goto-print row col)
1216 (setq startpos (point))
1217 ;; Install the printed result. This is not interruptible.
1218 (let ((inhibit-read-only t)
1220 (let ((inhibit-point-motion-hooks t))
1221 (delete-region (point) (progn
1222 (move-to-column (+ (current-column)
1223 (string-width text)))
1225 ;; We use concat instead of inserting separate strings in order to
1226 ;; reduce the number of cells in the undo list.
1227 (setq x (concat text (if (< maxcol ses--numcols) " " "\n")))
1228 ;; We use set-text-properties to prevent a wacky print function from
1229 ;; inserting rogue properties, and to ensure that the keymap property is
1230 ;; inherited (is it a bug that only unpropertized strings actually
1231 ;; inherit from surrounding text?)
1232 (set-text-properties 0 (length x) nil x)
1233 (insert-and-inherit x)
1234 (put-text-property startpos (point) 'intangible
1235 (ses-cell-symbol cell))
1236 (when (and (zerop row) (zerop col))
1237 ;; Reconstruct special beginning-of-buffer attributes.
1238 (put-text-property (point-min) (point) 'keymap 'ses-mode-print-map)
1239 (put-text-property (point-min) (point) 'read-only 'ses)
1240 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)))
1241 (if (= row (1- ses--header-row))
1242 ;; This line is part of the header --- force recalc.
1243 (ses-reset-header-string))
1244 ;; If this cell (or a preceding one on the line) previously spilled over
1245 ;; and has gotten shorter, redraw following cells on line recursively.
1246 (when (and (< maxcol ses--numcols)
1247 (eq (ses-cell-value row maxcol) '*skip*))
1248 (ses-set-cell row maxcol 'value nil)
1249 (ses-print-cell row maxcol))
1250 ;; Return to start of cell.
1251 (goto-char startpos)
1254 (defun ses-call-printer (printer &optional value)
1255 "Invoke PRINTER (a string or parenthesized string or function-symbol or
1256 lambda of one argument) on VALUE. Result is the printed cell as a string.
1257 The variable `ses-call-printer-return' is set to t if the printer used
1258 parenthesis to request left-justification, or the error-signal if the
1259 printer signaled one (and \"%s\" is used as the default printer), else nil."
1260 (setq ses-call-printer-return nil)
1261 (condition-case signal
1265 (format printer value)
1267 ((stringp (car-safe printer))
1268 (setq ses-call-printer-return t)
1270 (format (car printer) value)
1273 (setq value (funcall
1274 (or (and (symbolp printer)
1275 (let ((locprn (gethash printer ses--local-printer-hashmap)))
1277 (ses--locprn-compiled locprn))))
1282 (or (stringp (car-safe value))
1283 (error "Printer should return \"string\" or (\"string\")"))
1284 (setq ses-call-printer-return t)
1287 (setq ses-call-printer-return signal)
1288 (prin1-to-string value t))))
1290 (defun ses-adjust-print-width (col change)
1291 "Insert CHANGE spaces in front of column COL, or at end of line if
1292 COL=NUMCOLS. Deletes characters if CHANGE < 0. Caller should bind
1293 `inhibit-quit' to t."
1294 (let ((inhibit-read-only t)
1295 (blank (if (> change 0) (make-string change ?\s)))
1296 (at-end (= col ses--numcols)))
1297 (ses-set-with-undo 'ses--linewidth (+ ses--linewidth change))
1298 ;; ses-set-with-undo always returns t for strings.
1299 (1value (ses-set-with-undo 'ses--blank-line
1300 (concat (make-string ses--linewidth ?\s) "\n")))
1301 (dotimes (row ses--numrows)
1302 (ses-goto-print row col)
1304 ;; Insert new columns before newline.
1305 (let ((inhibit-point-motion-hooks t))
1309 (delete-char (- change))))))
1311 (defun ses-print-cell-new-width (row col)
1312 "Same as `ses-print-cell', except if the cell's value is *skip*,
1313 the preceding nonskipped cell is reprinted. This function is used
1314 when the width of cell (ROW,COL) has changed."
1315 (if (not (eq (ses-cell-value row col) '*skip*))
1316 (ses-print-cell row col)
1317 ;;Cell was skipped over - reprint previous
1318 (ses-goto-print row col)
1320 (let ((rowcol (ses-sym-rowcol (get-text-property (point) 'intangible))))
1321 (ses-print-cell (car rowcol) (cdr rowcol)))))
1324 ;;----------------------------------------------------------------------------
1326 ;;----------------------------------------------------------------------------
1329 "Turn off narrowing, to be reenabled at end of command loop."
1330 (if (buffer-narrowed-p)
1331 (setq ses--deferred-narrow t))
1334 (defun ses-goto-data (def &optional col)
1335 "Move point to data area for (DEF,COL). If DEF is a row
1336 number, COL is the column number for a data cell -- otherwise DEF
1337 is one of the symbols ses--col-widths, ses--col-printers,
1338 ses--default-printer, ses--numrows, or ses--numcols."
1340 (let ((inhibit-point-motion-hooks t)) ; In case intangible attrs are wrong.
1344 (goto-char ses--data-marker)
1345 (forward-line (+ 1 (* def (1+ ses--numcols)) col)))
1346 ;; Convert def-symbol to offset.
1347 (setq def (plist-get ses-paramlines-plist def))
1348 (or def (signal 'args-out-of-range nil))
1349 (goto-char ses--params-marker)
1350 (forward-line def))))
1352 (defun ses-file-format-extend-paramter-list (new-file-format)
1353 "Extend the global parameters list when file format is updated
1354 from 2 to 3. This happens when local printer function are added
1355 to a sheet that was created with SES version 2. This is not
1356 undoable. Return nil when there was no change, and non nil otherwise."
1359 ((and (= ses--file-format 2) (= 3 new-file-format))
1360 (ses-set-parameter 'ses--file-format 3)
1361 (message "Upgrading from SES-2 to SES-3 file format")
1363 (goto-char ses--params-marker)
1364 (forward-line (plist-get ses-paramlines-plist 'ses--numlocprn ))
1365 (insert (format (plist-get ses-paramfmt-plist 'ses--numlocprn)
1370 (defun ses-set-parameter (def value &optional elem)
1371 "Set parameter DEF to VALUE (with undo) and write the value to the data area.
1372 See `ses-goto-data' for meaning of DEF. Newlines in the data are escaped.
1373 If ELEM is specified, it is the array subscript within DEF to be set to VALUE."
1375 ;; We call ses-goto-data early, using the old values of numrows and numcols
1376 ;; in case one of them is being changed.
1378 (let ((inhibit-read-only t)
1379 (fmt (plist-get ses-paramfmt-plist
1384 (setq oldval (aref (symbol-value def) elem))
1385 (aset (symbol-value def) elem value))
1386 (setq oldval (symbol-value def))
1388 ;; Special undo since it's outside the narrowed buffer.
1389 (let (buffer-undo-list)
1390 (delete-region (point) (line-end-position))
1391 (insert (format fmt (symbol-value def))))
1392 (push `(apply ses-set-parameter ,def ,oldval ,elem) buffer-undo-list))))
1395 (defun ses-write-cells ()
1396 "Write cells in `ses--deferred-write' from local variables to data area.
1397 Newlines in the data are escaped."
1398 (let* ((inhibit-read-only t)
1399 (print-escape-newlines t)
1400 rowcol row col cell sym formula printer text)
1401 (setq ses-start-time (float-time))
1402 (with-temp-message " "
1404 (while ses--deferred-write
1405 (ses-time-check "Writing... (%d cells left)"
1406 '(length ses--deferred-write))
1407 (setq rowcol (pop ses--deferred-write)
1410 cell (ses-get-cell row col)
1411 sym (ses-cell-symbol cell)
1412 formula (ses-cell-formula cell)
1413 printer (ses-cell-printer cell))
1414 (if (eq (car-safe formula) 'ses-safe-formula)
1415 (setq formula (cadr formula)))
1416 (if (eq (car-safe printer) 'ses-safe-printer)
1417 (setq printer (cadr printer)))
1418 (setq text (prin1-to-string
1419 ;; We could shorten it to (ses-cell SYM VAL) when
1420 ;; the other parameters are nil, but in practice most
1421 ;; cells have non-nil `references', so it's
1422 ;; rather pointless.
1425 ,(unless (equal formula (symbol-value sym))
1428 ,(ses-cell-references cell))))
1429 (ses-goto-data row col)
1430 (delete-region (point) (line-end-position))
1435 ;;----------------------------------------------------------------------------
1436 ;; Formula relocation
1437 ;;----------------------------------------------------------------------------
1439 (defun ses-formula-references (formula &optional result-so-far)
1440 "Produce a list of symbols for cells that this FORMULA's value
1441 refers to. For recursive calls, RESULT-SO-FAR is the list being
1442 constructed, or t to get a wrong-type-argument error when the
1443 first reference is found."
1444 (if (ses-sym-rowcol formula)
1445 ;; Entire formula is one symbol.
1446 (cl-pushnew formula result-so-far :test #'equal)
1449 ((eq (car formula) 'ses-range)
1451 (cdr (funcall 'macroexpand
1452 (list 'ses-range (nth 1 formula)
1454 (cl-pushnew cur result-so-far :test #'equal)))
1455 ((null (eq (car formula) 'quote))
1456 ;;Recursive call for subformulas
1457 (dolist (cur formula)
1458 (setq result-so-far (ses-formula-references cur result-so-far))))
1460 ;;Ignore other stuff
1462 ;; other type of atom are ignored
1466 (defsubst ses-relocate-symbol (sym rowcol startrow startcol rowincr colincr)
1467 "Relocate one symbol SYM, which corresponds to ROWCOL (a cons of ROW and
1468 COL). Cells starting at (STARTROW,STARTCOL) are being shifted
1469 by (ROWINCR,COLINCR)."
1470 (let ((row (car rowcol))
1472 (if (or (< row startrow) (< col startcol))
1474 (setq row (+ row rowincr)
1475 col (+ col colincr))
1476 (if (and (>= row startrow) (>= col startcol)
1477 (< row ses--numrows) (< col ses--numcols))
1478 ;;Relocate this variable
1479 (ses-create-cell-symbol row col)
1480 ;;Delete reference to a deleted cell
1483 (defun ses-relocate-formula (formula startrow startcol rowincr colincr)
1484 "Produce a copy of FORMULA where all symbols that refer to cells in row
1485 STARTROW or above, and col STARTCOL or above, are altered by adding ROWINCR
1486 and COLINCR. STARTROW and STARTCOL are 0-based. Example:
1487 (ses-relocate-formula '(+ A1 B2 D3) 1 2 1 -1)
1489 If ROWINCR or COLINCR is negative, references to cells being deleted are
1491 (ses-relocate-formula '(+ A1 B2 D3) 0 1 0 -1)
1493 Sets `ses-relocate-return' to 'delete if cell-references were removed."
1494 (let (rowcol result)
1495 (if (or (atom formula) (eq (car formula) 'quote))
1496 (if (and (setq rowcol (ses-sym-rowcol formula))
1497 (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name formula)))
1498 (ses-relocate-symbol formula rowcol
1499 startrow startcol rowincr colincr)
1500 formula) ; Pass through as-is.
1501 (dolist (cur formula)
1502 (setq rowcol (ses-sym-rowcol cur))
1505 (setq cur (ses-relocate-symbol cur rowcol
1506 startrow startcol rowincr colincr))
1509 ;; Reference to a deleted cell. Set a flag in ses-relocate-return.
1510 ;; don't change the flag if it's already 'range, since range implies
1512 (unless ses-relocate-return
1513 (setq ses-relocate-return 'delete))))
1514 ((eq (car-safe cur) 'ses-range)
1515 (setq cur (ses-relocate-range cur startrow startcol rowincr colincr))
1518 ((or (atom cur) (eq (car cur) 'quote))
1519 ;; Constants pass through unchanged.
1522 ;; Recursively copy and alter subformulas.
1523 (push (ses-relocate-formula cur startrow startcol
1526 (nreverse result))))
1528 (defun ses-relocate-range (range startrow startcol rowincr colincr)
1529 "Relocate one RANGE, of the form '(ses-range min max). Cells starting
1530 at (STARTROW,STARTCOL) are being shifted by (ROWINCR,COLINCR). Result is the
1531 new range, or nil if the entire range is deleted. If new rows are being added
1532 just beyond the end of a row range, or new columns just beyond a column range,
1533 the new rows/columns will be added to the range. Sets `ses-relocate-return'
1534 if the range was altered."
1535 (let* ((minorig (cadr range))
1536 (minrowcol (ses-sym-rowcol minorig))
1537 (min (ses-relocate-symbol minorig minrowcol
1540 (maxorig (nth 2 range))
1541 (maxrowcol (ses-sym-rowcol maxorig))
1542 (max (ses-relocate-symbol maxorig maxrowcol
1547 ((and (not min) (not max))
1548 (setq range nil)) ; The entire range is deleted.
1550 ;; Inserting or deleting rows.
1553 ;; Chopped off beginning of range.
1554 (setq min (ses-create-cell-symbol startrow (cdr minrowcol))
1555 ses-relocate-return 'range))
1558 ;; Trying to insert a nonexistent row.
1559 (setq max (ses-create-cell-symbol (1- ses--numrows)
1561 ;; End of range is being deleted.
1562 (setq max (ses-create-cell-symbol (1- startrow) (cdr minrowcol))
1563 ses-relocate-return 'range))
1565 (= (car maxrowcol) (1- startrow))
1566 (= (cdr minrowcol) (cdr maxrowcol))
1567 ;; Insert after ending row of vertical range --- include it.
1568 (setq max (ses-create-cell-symbol (+ startrow rowincr -1)
1569 (cdr maxrowcol))))))
1571 ;; Inserting or deleting columns.
1574 ;; Chopped off beginning of range.
1575 (setq min (ses-create-cell-symbol (car minrowcol) startcol)
1576 ses-relocate-return 'range))
1579 ;; Trying to insert a nonexistent column.
1580 (setq max (ses-create-cell-symbol (car maxrowcol)
1582 ;; End of range is being deleted.
1583 (setq max (ses-create-cell-symbol (car maxrowcol) (1- startcol))
1584 ses-relocate-return 'range))
1586 (= (cdr maxrowcol) (1- startcol))
1587 (= (car minrowcol) (car maxrowcol))
1588 ;; Insert after ending column of horizontal range --- include it.
1589 (setq max (ses-create-cell-symbol (car maxrowcol)
1590 (+ startcol colincr -1)))))))
1592 (if (/= (- (funcall field maxrowcol)
1593 (funcall field minrowcol))
1594 (- (funcall field (ses-sym-rowcol max))
1595 (funcall field (ses-sym-rowcol min))))
1596 ;; This range has changed size.
1597 (setq ses-relocate-return 'range))
1598 `(ses-range ,min ,max ,@(cl-cdddr range)))))
1600 (defun ses-relocate-all (minrow mincol rowincr colincr)
1601 "Alter all cell values, symbols, formulas, and reference-lists to relocate
1602 the rectangle (MINROW,MINCOL)..(NUMROWS,NUMCOLS) by adding ROWINCR and COLINCR
1605 (let (mycell newval xrow)
1606 (dotimes-with-progress-reporter
1607 (row ses--numrows) "Relocating formulas..."
1608 (dotimes (col ses--numcols)
1609 (setq ses-relocate-return nil
1610 mycell (ses-get-cell row col)
1611 newval (ses-relocate-formula (ses-cell-formula mycell)
1612 minrow mincol rowincr colincr)
1613 xrow (- row rowincr))
1614 (ses-set-cell row col 'formula newval)
1615 (if (eq ses-relocate-return 'range)
1616 ;; This cell contains a (ses-range X Y) where a cell has been
1617 ;; inserted or deleted in the middle of the range.
1618 (push (cons row col) reform))
1619 (if ses-relocate-return
1620 ;; This cell referred to a cell that's been deleted or is no
1621 ;; longer part of the range. We can't fix that now because
1622 ;; reference lists cells have been partially updated.
1623 (cl-pushnew (ses-create-cell-symbol row col)
1624 ses--deferred-recalc :test #'equal))
1625 (setq newval (ses-relocate-formula (ses-cell-references mycell)
1626 minrow mincol rowincr colincr))
1627 (ses-set-cell row col 'references newval)
1628 (and (>= row minrow) (>= col mincol)
1629 (let ((sym (ses-cell-symbol row col))
1630 (xcol (- col colincr)))
1636 (ses-create-cell-symbol xrow xcol))))
1637 ;; This is a renamed cell, do not update the cell
1638 ;; name, but just update the coordinate property.
1639 (put sym 'ses-cell (cons row col))
1640 (ses-set-cell row col 'symbol
1641 (setq sym (ses-create-cell-symbol row col)))
1642 (unless (and (boundp sym) (local-variable-p sym))
1643 (set (make-local-variable sym) nil)
1644 (put sym 'ses-cell (cons row col)))))) )))
1645 ;; Relocate the cell values.
1646 (let (oldval myrow mycol xrow xcol)
1648 ((and (<= rowincr 0) (<= colincr 0))
1649 ;; Deletion of rows and/or columns.
1650 (dotimes-with-progress-reporter
1651 (row (- ses--numrows minrow)) "Relocating variables..."
1652 (setq myrow (+ row minrow))
1653 (dotimes (col (- ses--numcols mincol))
1654 (setq mycol (+ col mincol)
1655 xrow (- myrow rowincr)
1656 xcol (- mycol colincr))
1657 (let ((sym (ses-cell-symbol myrow mycol))
1658 (xsym (ses-create-cell-symbol xrow xcol)))
1659 ;; Make the value relocation only when if the cell is not
1660 ;; a renamed cell. Otherwise this is not needed.
1662 (ses-set-cell myrow mycol 'value
1663 (if (and (< xrow ses--numrows) (< xcol ses--numcols))
1664 (ses-cell-value xrow xcol)
1665 ;;Cell is off the end of the array
1666 (symbol-value xsym))))))))
1668 ((and (wholenump rowincr) (wholenump colincr))
1669 ;; Insertion of rows and/or columns. Run the loop backwards.
1670 (let ((disty (1- ses--numrows))
1671 (distx (1- ses--numcols))
1673 (dotimes-with-progress-reporter
1674 (row (- ses--numrows minrow)) "Relocating variables..."
1675 (setq myrow (- disty row))
1676 (dotimes (col (- ses--numcols mincol))
1677 (setq mycol (- distx col)
1678 xrow (- myrow rowincr)
1679 xcol (- mycol colincr))
1680 (if (or (< xrow minrow) (< xcol mincol))
1681 ;; Newly-inserted value.
1683 ;; Transfer old value.
1684 (setq oldval (ses-cell-value xrow xcol)))
1685 (ses-set-cell myrow mycol 'value oldval)))
1686 t)) ; Make testcover happy by returning non-nil here.
1688 (error "ROWINCR and COLINCR must have the same sign"))))
1689 ;; Reconstruct reference lists for cells that contain ses-ranges that have
1692 (message "Fixing ses-ranges...")
1694 (setq ses-start-time (float-time))
1696 (ses-time-check "Fixing ses-ranges... (%d left)" '(length reform))
1697 (setq row (caar reform)
1699 reform (cdr reform))
1700 (ses-cell-set-formula row col (ses-cell-formula row col))))
1704 ;;----------------------------------------------------------------------------
1706 ;;----------------------------------------------------------------------------
1708 (defun ses-begin-change ()
1709 "For undo, remember point before we start changing hidden stuff."
1710 (let ((inhibit-read-only t))
1711 (insert-and-inherit "X")
1712 (delete-region (1- (point)) (point))))
1714 (defun ses-setter-with-undo (accessors newval &rest args)
1715 "Set a field/variable and record it so it can be undone.
1716 Result is non-nil if field/variable has changed."
1717 (let ((oldval (apply (car accessors) args)))
1718 (unless (equal-including-properties oldval newval)
1719 (push `(apply ses-setter-with-undo ,accessors ,oldval ,@args)
1721 (apply (cdr accessors) newval args)
1724 (defun ses-aset-with-undo (array idx newval)
1725 (ses-setter-with-undo (eval-when-compile
1727 (lambda (newval array idx) (aset array idx newval))))
1730 (defun ses-set-with-undo (sym newval)
1731 (ses-setter-with-undo
1733 (cons (lambda (sym) (if (boundp sym) (symbol-value sym) :ses--unbound))
1734 (lambda (newval sym) (if (eq newval :ses--unbound)
1736 (set sym newval)))))
1739 ;;----------------------------------------------------------------------------
1740 ;; Startup for major mode
1741 ;;----------------------------------------------------------------------------
1744 "Parse the current buffer and set up buffer-local variables.
1745 Does not execute cell formulas or print functions."
1747 ;; Read our global parameters, which should be a 3-element list.
1748 (goto-char (point-max))
1749 (search-backward ";; Local Variables:\n" nil t)
1751 (setq ses--params-marker (point-marker))
1752 (let* ((params (ignore-errors (read (current-buffer))))
1753 (params-len (safe-length params)))
1754 (or (and (>= params-len 3)
1756 (numberp (car params))
1757 (numberp (cadr params))
1758 (>= (cadr params) 0)
1759 (numberp (nth 2 params))
1760 (> (nth 2 params) 0)
1761 (or (<= params-len 3)
1762 (let ((numlocprn (nth 3 params)))
1763 (and (integerp numlocprn) (>= numlocprn 0)))))
1764 (error "Invalid SES file"))
1765 (setq ses--file-format (car params)
1766 ses--numrows (cadr params)
1767 ses--numcols (nth 2 params)
1768 ses--numlocprn (or (nth 3 params) 0))
1769 (when (= ses--file-format 1)
1770 (let (buffer-undo-list) ; This is not undoable.
1771 (ses-goto-data 'ses--header-row)
1772 (insert "(ses-header-row 0)\n")
1773 (ses-set-parameter 'ses--file-format 3)
1774 (message "Upgrading from SES-1 to SES-2 file format")))
1775 (or (<= ses--file-format 3)
1776 (error "This file needs a newer version of the SES library code"))
1777 ;; Initialize cell array.
1778 (setq ses--cells (make-vector ses--numrows nil))
1779 (dotimes (row ses--numrows)
1780 (aset ses--cells row (make-vector ses--numcols nil)))
1781 ;; initialize local printer map.
1782 (clrhash ses--local-printer-hashmap))
1784 ;; Skip over print area, which we assume is correct.
1785 (goto-char (point-min))
1786 (forward-line ses--numrows)
1787 (or (looking-at-p ses-print-data-boundary)
1788 (error "Missing marker between print and data areas"))
1790 (setq ses--data-marker (point-marker))
1791 (forward-char (1- (length ses-print-data-boundary)))
1792 ;; Initialize printer and symbol lists.
1793 (mapc 'ses-printer-record ses-standard-printer-functions)
1794 (setq ses--symbolic-formulas nil)
1796 ;; Load local printer definitions.
1797 ;; This must be loaded *BEFORE* cells and column printers because the latters
1800 (forward-line (* ses--numrows (1+ ses--numcols)))
1801 (let ((numlocprn ses--numlocprn))
1802 (setq ses--numlocprn 0)
1803 (dotimes (_ numlocprn)
1804 (let ((x (read (current-buffer))))
1805 (or (and (looking-at-p "\n")
1806 (eq (car-safe x) 'ses-local-printer)
1807 (apply #'ses--local-printer (cdr x)))
1808 (error "local printer-def error"))
1809 (setq ses--numlocprn (1+ ses--numlocprn))))))
1810 ;; Load cell definitions.
1811 (dotimes (row ses--numrows)
1812 (dotimes (col ses--numcols)
1813 (let* ((x (read (current-buffer)))
1814 (sym (car-safe (cdr-safe x))))
1815 (or (and (looking-at-p "\n")
1816 (eq (car-safe x) 'ses-cell)
1817 (ses-create-cell-variable sym row col))
1818 (error "Cell-def error"))
1819 (apply #'ses--cell (cdr x))))
1820 (or (looking-at-p "\n\n")
1821 (error "Missing blank line between rows")))
1822 ;; Skip local printer function declaration --- that were already loaded.
1823 (forward-line (+ 2 ses--numlocprn))
1824 ;; Load global parameters.
1825 (let ((widths (read (current-buffer)))
1826 (n1 (char-after (point)))
1827 (printers (read (current-buffer)))
1828 (n2 (char-after (point)))
1829 (def-printer (read (current-buffer)))
1830 (n3 (char-after (point)))
1831 (head-row (read (current-buffer)))
1832 (n4 (char-after (point))))
1833 (or (and (eq (car-safe widths) 'ses-column-widths)
1835 (eq (car-safe printers) 'ses-column-printers)
1837 (eq (car-safe def-printer) 'ses-default-printer)
1839 (eq (car-safe head-row) 'ses-header-row)
1841 (error "Invalid SES global parameters"))
1842 (1value (eval widths))
1843 (1value (eval def-printer))
1844 (1value (eval printers))
1845 (1value (eval head-row)))
1846 ;; Should be back at global-params.
1848 (or (looking-at-p ses-initial-global-parameters-re)
1849 (error "Problem with column-defs or global-params"))
1850 ;; Check for overall newline count in definitions area.
1852 (let ((start (point)))
1853 (ses-goto-data 'ses--numrows)
1854 (or (= (point) start)
1855 (error "Extraneous newlines someplace?"))))
1858 "Set up for display of only the printed cell values.
1860 Narrows the buffer to show only the print area. Gives it `read-only' and
1861 `intangible' properties. Sets up highlighting for current cell."
1863 (let ((end (point-min))
1864 (inhibit-read-only t)
1865 (inhibit-point-motion-hooks t)
1866 (was-modified (buffer-modified-p))
1868 (ses-goto-data 0 0) ; Include marker between print-area and data-area.
1869 (set-text-properties (point) (point-max) nil) ; Delete garbage props.
1870 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1871 ;; The print area is read-only (except for our special commands) and uses a
1873 (put-text-property (point-min) (1- (point)) 'read-only 'ses)
1874 (put-text-property (point-min) (1- (point)) 'keymap 'ses-mode-print-map)
1875 ;; For the beginning of the buffer, we want the read-only and keymap
1876 ;; attributes to be inherited from the first character.
1877 (put-text-property (point-min) (1+ (point-min)) 'front-sticky t)
1878 ;; Create intangible properties, which also indicate which cell the text
1880 (dotimes-with-progress-reporter (row ses--numrows) "Finding cells..."
1881 (dotimes (col ses--numcols)
1883 sym (ses-cell-symbol row col))
1884 ;; Include skipped cells following this one.
1885 (while (and (< col (1- ses--numcols))
1886 (eq (ses-cell-value row (1+ col)) '*skip*))
1887 (setq end (+ end (ses-col-width col) 1)
1889 (setq end (save-excursion
1891 (move-to-column (+ (current-column) (- end pos)
1892 (ses-col-width col)))
1894 (+ end (ses-col-width col) 1)
1897 (put-text-property pos end 'intangible sym)))
1898 ;; Adding these properties did not actually alter the text.
1899 (unless was-modified
1900 (restore-buffer-modified-p nil)
1901 (buffer-disable-undo)
1902 (buffer-enable-undo)))
1903 ;; Create the underlining overlay. It's impossible for (point) to be 2,
1904 ;; because column A must be at least 1 column wide.
1905 (setq ses--curcell-overlay (make-overlay (1+ (point-min)) (1+ (point-min))))
1906 (overlay-put ses--curcell-overlay 'face 'underline))
1908 (defun ses-cleanup ()
1909 "Cleanup when changing a buffer from SES mode to something else.
1910 Delete overlays, remove special text properties."
1912 (let ((inhibit-read-only t)
1913 ;; When reverting, hide the buffer name, otherwise Emacs will ask the
1914 ;; user "the file is modified, do you really want to make modifications
1915 ;; to this buffer", where the "modifications" refer to the irrelevant
1916 ;; set-text-properties below.
1917 (buffer-file-name nil)
1918 (was-modified (buffer-modified-p)))
1919 ;; Delete read-only, keymap, and intangible properties.
1920 (set-text-properties (point-min) (point-max) nil)
1922 (mapc 'delete-overlay (overlays-in (point-min) (point-max)))
1923 (unless was-modified
1924 (restore-buffer-modified-p nil))))
1928 "Major mode for Simple Emacs Spreadsheet.
1930 When you invoke SES in a new buffer, it is divided into cells
1931 that you can enter data into. You can navigate the cells with
1932 the arrow keys and add more cells with the tab key. The contents
1933 of these cells can be numbers, text, or Lisp expressions. (To
1934 enter text, enclose it in double quotes.)
1936 In an expression, you can use cell coordinates to refer to the
1937 contents of another cell. For example, you can sum a range of
1938 cells with `(+ A1 A2 A3)'. There are specialized functions like
1939 `ses+' (addition for ranges with empty cells), `ses-average' (for
1940 performing calculations on cells), and `ses-range' and `ses-select'
1941 \(for extracting ranges of cells).
1943 Each cell also has a print function that controls how it is
1946 Each SES buffer is divided into a print area and a data area.
1947 Normally, you can simply use SES to look at and manipulate the print
1948 area, and let SES manage the data area outside the visible region.
1950 See \"ses-example.ses\" (in `data-directory') for an example
1951 spreadsheet, and the Info node `(ses)Top.'
1953 In the following, note the separate keymaps for cell editing mode
1954 and print mode specifications. Key definitions:
1957 These key definitions are active only in the print area (the visible
1959 \\{ses-mode-print-map}
1960 These are active only in the minibuffer, when entering or editing a
1962 \\{ses-mode-edit-map}"
1964 (unless (and (boundp 'ses--deferred-narrow)
1965 (eq ses--deferred-narrow 'ses-mode))
1966 (kill-all-local-variables)
1968 (setq major-mode 'ses-mode
1970 next-line-add-newlines nil
1972 ;; SES deliberately puts lots of trailing whitespace in its buffer.
1973 show-trailing-whitespace nil
1974 ;; Cell ranges do not work reasonably without this.
1975 transient-mark-mode t
1976 ;; Not to use tab characters for safe (tabs may do bad for column
1978 indent-tabs-mode nil)
1979 (1value (add-hook 'change-major-mode-hook 'ses-cleanup nil t))
1980 ;; This makes revert impossible if the buffer is read-only.
1981 ;; (1value (add-hook 'before-revert-hook 'ses-cleanup nil t))
1982 (setq header-line-format '(:eval (progn
1983 (when (/= (window-hscroll)
1984 ses--header-hscroll)
1985 ;; Reset ses--header-hscroll first,
1986 ;; to avoid recursion problems when
1987 ;; debugging ses-create-header-string
1988 (setq ses--header-hscroll
1990 (ses-create-header-string))
1991 ses--header-string)))
1992 (let ((was-empty (zerop (buffer-size)))
1993 (was-modified (buffer-modified-p)))
1996 ;; Initialize buffer to contain one cell, for now.
1997 (insert ses-initial-file-contents))
2001 (unless (equal ses-initial-default-printer
2002 (1value ses--default-printer))
2003 (1value (ses-read-default-printer ses-initial-default-printer)))
2004 (unless (= ses-initial-column-width (1value (ses-col-width 0)))
2005 (1value (ses-set-column-width 0 ses-initial-column-width)))
2007 (if (> (car ses-initial-size) (1value ses--numrows))
2008 (1value (ses-insert-row (1- (car ses-initial-size)))))
2009 (if (> (cdr ses-initial-size) (1value ses--numcols))
2010 (1value (ses-insert-column (1- (cdr ses-initial-size)))))
2012 (restore-buffer-modified-p was-modified)
2013 (buffer-disable-undo)
2014 (buffer-enable-undo)
2015 (goto-char (point-min))))
2016 (use-local-map ses-mode-map)
2017 ;; Set the deferred narrowing flag (we can't narrow until after
2018 ;; after-find-file completes). If .ses is on the auto-load alist and the
2019 ;; file has "mode: ses", our ses-mode function will be called twice! Use a
2020 ;; special flag to detect this (will be reset by ses-command-hook). For
2021 ;; find-alternate-file, post-command-hook doesn't get run for some reason,
2022 ;; so use an idle timer to make sure.
2023 (setq ses--deferred-narrow 'ses-mode)
2024 (1value (add-hook 'post-command-hook 'ses-command-hook nil t))
2025 (run-with-idle-timer 0.01 nil 'ses-command-hook)
2026 (run-mode-hooks 'ses-mode-hook)))
2028 (put 'ses-mode 'mode-class 'special)
2030 (defun ses-command-hook ()
2031 "Invoked from `post-command-hook'. If point has moved to a different cell,
2032 moves the underlining overlay. Performs any recalculations or cell-data
2033 writes that have been deferred. If buffer-narrowing has been deferred,
2034 narrows the buffer now."
2036 (when (eq major-mode 'ses-mode) ; Otherwise, not our buffer anymore.
2037 (when ses--deferred-recalc
2038 ;; We reset the deferred list before starting on the recalc --- in
2039 ;; case of error, we don't want to retry the recalc after every
2041 (ses-initialize-Dijkstra-attempt)
2042 (let ((old ses--deferred-recalc))
2043 (setq ses--deferred-recalc nil)
2044 (ses-update-cells old)))
2045 (when ses--deferred-write
2046 ;; We don't reset the deferred list before starting --- the most
2047 ;; likely error is keyboard-quit, and we do want to keep trying these
2048 ;; writes after a quit.
2050 (push '(apply ses-widen) buffer-undo-list))
2051 (when ses--deferred-narrow
2052 ;; We're not allowed to narrow the buffer until after-find-file has
2053 ;; read the local variables at the end of the file. Now it's safe to
2054 ;; do the narrowing.
2055 (narrow-to-region (point-min) ses--data-marker)
2056 (setq ses--deferred-narrow nil))
2057 ;; Update the mode line.
2058 (let ((oldcell ses--curcell))
2060 (unless (eq ses--curcell oldcell)
2063 (setq mode-line-process nil))
2064 ((atom ses--curcell)
2065 (setq mode-line-process (list " cell "
2066 (symbol-name ses--curcell))))
2068 (setq mode-line-process (list " range "
2069 (symbol-name (car ses--curcell))
2071 (symbol-name (cdr ses--curcell))))))
2072 (force-mode-line-update)))
2073 ;; Use underline overlay for single-cells only, turn off otherwise.
2074 (if (listp ses--curcell)
2075 (move-overlay ses--curcell-overlay 2 2)
2076 (let ((next (next-single-property-change (point) 'intangible)))
2077 (move-overlay ses--curcell-overlay (point) (1- next))))
2078 (when (not (pos-visible-in-window-p))
2079 ;; Scrolling will happen later.
2080 (run-with-idle-timer 0.01 nil 'ses-command-hook)
2081 (setq ses--curcell t)))
2082 ;; Prevent errors in this post-command-hook from silently erasing the hook!
2084 (unless executing-kbd-macro
2086 (message "%s" (error-message-string err))))
2087 nil) ; Make coverage-tester happy.
2089 (defun ses-create-header-string ()
2090 "Set up `ses--header-string' as the buffer's header line.
2091 Based on the current set of columns and `window-hscroll' position."
2092 (let ((totwidth (- (window-hscroll)))
2094 ;; Leave room for the left-side fringe and scrollbar.
2095 (push (propertize " " 'display '((space :align-to 0))) result)
2096 (dotimes (col ses--numcols)
2097 (setq width (ses-col-width col)
2098 totwidth (+ totwidth width 1))
2100 ;; Scrolled so intercolumn space is leftmost.
2102 (when (> totwidth 1)
2103 (if (> ses--header-row 0)
2105 (ses-goto-print (1- ses--header-row) col)
2106 (setq x (buffer-substring-no-properties (point)
2108 ;; Strip trailing space.
2109 (if (string-match "[ \t]+\\'" x)
2110 (setq x (substring x 0 (match-beginning 0))))
2111 ;; Cut off excess text.
2112 (if (>= (length x) totwidth)
2113 (setq x (substring x 0 (- totwidth -1)))))
2114 (setq x (ses-column-letter col)))
2115 (push (propertize x 'face ses-box-prop) result)
2116 (push (propertize "."
2117 'display `((space :align-to ,(1- totwidth)))
2120 ;; Allow the following space to be squished to make room for the 3-D box
2121 ;; Coverage test ignores properties, thinks this is always a space!
2122 (push (1value (propertize " " 'display `((space :align-to ,totwidth))))
2124 (if (> ses--header-row 0)
2125 (push (propertize (format " [row %d]" ses--header-row)
2126 'display '((height (- 1))))
2128 (setq ses--header-string (apply 'concat (nreverse result)))))
2131 ;;----------------------------------------------------------------------------
2132 ;; Redisplay and recalculation
2133 ;;----------------------------------------------------------------------------
2135 (defun ses-jump (sym)
2136 "Move point to cell SYM."
2137 (interactive "SJump to cell: ")
2138 (let ((rowcol (ses-sym-rowcol sym)))
2139 (or rowcol (error "Invalid cell name"))
2140 (if (eq (symbol-value sym) '*skip*)
2141 (error "Cell is covered by preceding cell"))
2142 (ses-goto-print (car rowcol) (cdr rowcol))))
2144 (defun ses-jump-safe (cell)
2145 "Like `ses-jump', but no error if invalid cell."
2149 (defun ses-reprint-all (&optional nonarrow)
2150 "Recreate the display area. Calls all printer functions. Narrows to
2151 print area if NONARROW is nil."
2155 (setq ses--deferred-narrow t))
2156 (let ((startcell (get-text-property (point) 'intangible))
2157 (inhibit-read-only t))
2159 (goto-char (point-min))
2160 (search-forward ses-print-data-boundary)
2161 (backward-char (length ses-print-data-boundary))
2162 (delete-region (point-min) (point))
2163 ;; Insert all blank lines before printing anything, so ses-print-cell can
2164 ;; find the data area when inserting or deleting *skip* values for cells.
2165 (dotimes (_ ses--numrows)
2166 (insert-and-inherit ses--blank-line))
2167 (dotimes-with-progress-reporter (row ses--numrows) "Reprinting..."
2168 (if (eq (ses-cell-value row 0) '*skip*)
2169 ;; Column deletion left a dangling skip.
2170 (ses-set-cell row 0 'value nil))
2171 (dotimes (col ses--numcols)
2172 (ses-print-cell row col))
2173 (beginning-of-line 2))
2174 (ses-jump-safe startcell)))
2176 (defun ses-initialize-Dijkstra-attempt ()
2177 (setq ses--Dijkstra-attempt-nb (1+ ses--Dijkstra-attempt-nb)
2178 ses--Dijkstra-weight-bound (* ses--numrows ses--numcols)))
2180 (defun ses-recalculate-cell ()
2181 "Recalculate and reprint the current cell or range.
2183 For an individual cell, shows the error if the formula or printer
2184 signals one, or otherwise shows the cell's complete value. For a range, the
2185 cells are recalculated in \"natural\" order, so cells that other cells refer
2186 to are recalculated first."
2188 (ses-check-curcell 'range)
2190 (ses-initialize-Dijkstra-attempt)
2191 (let (sig cur-rowcol)
2192 (setq ses-start-time (float-time))
2193 (if (atom ses--curcell)
2195 (setq cur-rowcol (ses-sym-rowcol ses--curcell)
2197 (setf (ses-cell-property :ses-Dijkstra-attempt
2200 (cons ses--Dijkstra-attempt-nb 0))
2201 (ses-calculate-cell (car cur-rowcol) (cdr cur-rowcol) t)))
2202 (nconc sig (list (ses-cell-symbol (car cur-rowcol)
2203 (cdr cur-rowcol)))))
2204 ;; First, recalculate all cells that don't refer to other cells and
2205 ;; produce a list of cells with references.
2206 (ses-dorange ses--curcell
2207 (ses-time-check "Recalculating... %s" '(ses-cell-symbol row col))
2210 ;; The t causes an error if the cell has references. If no
2211 ;; references, the t will be the result value.
2212 (1value (ses-formula-references (ses-cell-formula row col) t))
2213 (setf (ses-cell-property :ses-Dijkstra-attempt row col)
2214 (cons ses--Dijkstra-attempt-nb 0))
2215 (when (setq sig (ses-calculate-cell row col t))
2216 (nconc sig (list (ses-cell-symbol row col)))))
2217 (wrong-type-argument
2218 ;; The formula contains a reference.
2219 (cl-pushnew (ses-cell-symbol row col) ses--deferred-recalc
2221 ;; Do the update now, so we can force recalculation.
2222 (let ((x ses--deferred-recalc))
2223 (setq ses--deferred-recalc nil)
2224 (condition-case hold
2225 (ses-update-cells x t)
2226 (error (setq sig hold))))
2229 (message "%s" (error-message-string sig)))
2230 ((consp ses--curcell)
2233 (princ (symbol-value ses--curcell))))))
2235 (defun ses-recalculate-all ()
2236 "Recalculate and reprint all cells."
2238 (let ((startcell (get-text-property (point) 'intangible))
2239 (ses--curcell (cons 'A1 (ses-cell-symbol (1- ses--numrows)
2240 (1- ses--numcols)))))
2241 (ses-recalculate-cell)
2242 (ses-jump-safe startcell)))
2244 (defun ses-truncate-cell ()
2245 "Reprint current cell, but without spillover into any following blank cells."
2248 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2251 (when (and (< col (1- ses--numcols)) ;;Last column can't spill over, anyway
2252 (eq (ses-cell-value row (1+ col)) '*skip*))
2253 ;; This cell has spill-over. We'll momentarily pretend the following cell
2255 (eval `(let ((,(ses-cell-symbol row (1+ col)) t))
2256 (ses-print-cell row col)))
2257 ;; Now remove the *skip*. ses-print-cell is always nil here.
2258 (ses-set-cell row (1+ col) 'value nil)
2259 (1value (ses-print-cell row (1+ col))))))
2261 (defun ses-reconstruct-all ()
2262 "Reconstruct buffer based on cell data stored in Emacs variables."
2265 ;;Reconstruct reference lists.
2267 ;;Delete old reference lists
2268 (dotimes-with-progress-reporter
2269 (row ses--numrows) "Deleting references..."
2270 (dotimes (col ses--numcols)
2271 (ses-set-cell row col 'references nil)))
2272 ;;Create new reference lists
2273 (dotimes-with-progress-reporter
2274 (row ses--numrows) "Computing references..."
2275 (dotimes (col ses--numcols)
2276 (dolist (ref (ses-formula-references (ses-cell-formula row col)))
2277 (setq x (ses-sym-rowcol ref)
2280 (ses-set-cell yrow ycol 'references
2281 (cons (ses-cell-symbol row col)
2282 (ses-cell-references yrow ycol)))))))
2283 ;; Delete everything and reconstruct basic data area.
2285 (let ((inhibit-read-only t))
2286 (goto-char (point-max))
2287 (if (search-backward ";; Local Variables:\n" nil t)
2288 (delete-region (point-min) (point))
2289 ;; Buffer is quite screwed up --- can't even save the user-specified
2291 (delete-region (point-min) (point-max))
2292 (insert ses-initial-file-trailer)
2293 (goto-char (point-min)))
2294 ;; Create a blank display area.
2295 (dotimes (_ ses--numrows)
2296 (insert ses--blank-line))
2297 (insert ses-print-data-boundary)
2298 (backward-char (1- (length ses-print-data-boundary)))
2299 (setq ses--data-marker (point-marker))
2300 (forward-char (1- (length ses-print-data-boundary)))
2301 ;; Placeholders for cell data.
2302 (insert (make-string (* ses--numrows (1+ ses--numcols)) ?\n))
2303 ;; Placeholders for col-widths, col-printers, default-printer, header-row.
2305 (insert ses-initial-global-parameters)
2306 (backward-char (1- (length ses-initial-global-parameters)))
2307 (setq ses--params-marker (point-marker))
2308 (forward-char (1- (length ses-initial-global-parameters))))
2309 (ses-set-parameter 'ses--col-widths ses--col-widths)
2310 (ses-set-parameter 'ses--col-printers ses--col-printers)
2311 (ses-set-parameter 'ses--default-printer ses--default-printer)
2312 (ses-set-parameter 'ses--header-row ses--header-row)
2313 (ses-set-parameter 'ses--numrows ses--numrows)
2314 (ses-set-parameter 'ses--numcols ses--numcols)
2315 ;;Keep our old narrowing
2317 (ses-recalculate-all)
2318 (goto-char (point-min)))
2321 ;;----------------------------------------------------------------------------
2322 ;; Input of cell formulas
2323 ;;----------------------------------------------------------------------------
2325 (defun ses-edit-cell (row col newval)
2326 "Display current cell contents in minibuffer, for editing. Returns nil if
2327 cell formula was unsafe and user declined confirmation."
2330 (barf-if-buffer-read-only)
2332 (let* ((rowcol (ses-sym-rowcol ses--curcell))
2335 (formula (ses-cell-formula row col))
2337 (if (eq (car-safe formula) 'ses-safe-formula)
2338 (setq formula (cadr formula)))
2339 (if (eq (car-safe formula) 'quote)
2340 (setq initial (format "'%S" (cadr formula)))
2341 (setq initial (prin1-to-string formula)))
2342 (if (stringp formula)
2343 ;; Position cursor inside close-quote.
2344 (setq initial (cons initial (length initial))))
2346 (read-from-minibuffer (format "Cell %s: " ses--curcell)
2349 t ; Convert to Lisp object.
2350 'ses-read-cell-history)))))
2351 (when (ses-warn-unsafe newval 'unsafep)
2353 (ses-cell-set-formula row col newval)
2356 (defun ses-read-cell (row col newval)
2357 "Self-insert for initial character of cell function."
2359 (let* ((initial (this-command-keys))
2360 (rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2361 (curval (ses-cell-formula (car rowcol) (cdr rowcol))))
2362 (barf-if-buffer-read-only)
2365 (if (equal initial "\"")
2367 (if (not (stringp curval)) (setq curval nil))
2368 (read-string (if curval
2369 (format "String Cell %s (default %s): "
2370 ses--curcell curval)
2371 (format "String Cell %s: " ses--curcell))
2372 nil 'ses-read-string-history curval))
2373 (read-from-minibuffer
2374 (format "Cell %s: " ses--curcell)
2375 (cons (if (equal initial "(") "()" initial) 2)
2377 t ; Convert to Lisp object.
2378 'ses-read-cell-history
2379 (prin1-to-string (if (eq (car-safe curval) 'ses-safe-formula)
2382 (when (ses-edit-cell row col newval)
2383 (ses-command-hook) ; Update cell widths before movement.
2384 (dolist (x ses-after-entry-functions)
2387 (defun ses-read-symbol (row col symb)
2388 "Self-insert for a symbol as a cell formula. The set of all symbols that
2389 have been used as formulas in this spreadsheet is available for completions."
2391 (let ((rowcol (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))
2393 (barf-if-buffer-read-only)
2394 (setq newval (completing-read (format "Cell %s ': " ses--curcell)
2395 ses--symbolic-formulas))
2398 (if (string= newval "")
2399 nil ; Don't create zero-length symbols!
2400 (list 'quote (intern newval))))))
2401 (when (ses-edit-cell row col symb)
2402 (ses-command-hook) ; Update cell widths before movement.
2403 (dolist (x ses-after-entry-functions)
2406 (defun ses-clear-cell-forward (count)
2407 "Delete formula and printer for current cell and then move to next cell.
2408 With prefix, deletes several cells."
2411 (1value (ses-clear-cell-backward (- count)))
2416 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2417 (or rowcol (signal 'end-of-buffer nil))
2418 (ses-clear-cell (car rowcol) (cdr rowcol)))
2421 (defun ses-clear-cell-backward (count)
2422 "Move to previous cell and then delete it. With prefix, deletes several
2426 (1value (ses-clear-cell-forward (- count)))
2427 (ses-check-curcell 'end)
2430 (backward-char 1) ; Will signal 'beginning-of-buffer if appropriate.
2432 (let ((rowcol (ses-sym-rowcol ses--curcell)))
2433 (ses-clear-cell (car rowcol) (cdr rowcol))))))
2436 ;;----------------------------------------------------------------------------
2437 ;; Input of cell-printer functions
2438 ;;----------------------------------------------------------------------------
2440 (defun ses-read-printer (prompt default)
2441 "Common code for functions `ses-read-cell-printer', `ses-read-column-printer',
2442 `ses-read-default-printer' and `ses-define-local-printer'.
2443 PROMPT should end with \": \". Result is t if operation was
2445 (barf-if-buffer-read-only)
2448 (setq prompt (format "%s (default %S): "
2449 (substring prompt 0 -2)
2451 (let ((new (read-from-minibuffer prompt
2452 nil ; Initial contents.
2454 t ; Evaluate the result.
2455 'ses-read-printer-history
2456 (prin1-to-string default))))
2457 (if (equal new default)
2458 ;; User changed mind, decided not to change printer.
2460 (ses-printer-validate new)
2463 (stringp (car-safe new))
2464 (and (symbolp new) (gethash new ses--local-printer-hashmap))
2465 (ses-warn-unsafe new 'unsafep-function)
2469 (defun ses-read-cell-printer (newval)
2470 "Set the printer function for the current cell or range.
2472 A printer function is either a string (a format control-string with one
2473 %-sequence -- result from format will be right-justified), or a list of one
2474 string (result from format will be left-justified), or a lambda-expression of
2475 one argument, or a symbol that names a function of one argument. In the
2476 latter two cases, the function's result should be either a string (will be
2477 right-justified) or a list of one string (will be left-justified)."
2480 (ses-check-curcell 'range)
2481 ;;Default is none if not all cells in range have same printer
2482 (catch 'ses-read-cell-printer
2483 (ses-dorange ses--curcell
2484 (let ((x (ses-cell-printer row col)))
2485 (if (eq (car-safe x) 'ses-safe-printer)
2489 (unless (equal default x)
2490 ;;Range contains differing printer functions
2492 (throw 'ses-read-cell-printer t))))))
2493 (list (ses-read-printer (format "Cell %S printer: " ses--curcell)
2495 (unless (eq newval t)
2497 (ses-dorange ses--curcell
2498 (ses-set-cell row col 'printer newval)
2499 (ses-print-cell row col))))
2501 (defun ses-read-column-printer (col newval)
2502 "Set the printer function for the current column.
2503 See `ses-read-cell-printer' for input forms."
2505 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2507 (list col (ses-read-printer (format "Column %s printer: "
2508 (ses-column-letter col))
2509 (ses-col-printer col)))))
2511 (unless (eq newval t)
2513 (ses-set-parameter 'ses--col-printers newval col)
2515 (dotimes (row ses--numrows)
2516 (ses-print-cell row col)))))
2518 (defun ses-read-default-printer (newval)
2519 "Set the default printer function for cells that have no other.
2520 See `ses-read-cell-printer' for input forms."
2522 (list (ses-read-printer "Default printer: " ses--default-printer)))
2523 (unless (eq newval t)
2525 (ses-set-parameter 'ses--default-printer newval)
2526 (ses-reprint-all t)))
2529 ;;----------------------------------------------------------------------------
2530 ;; Spreadsheet size adjustments
2531 ;;----------------------------------------------------------------------------
2533 (defun ses-insert-row (count)
2534 "Insert a new row before the current one.
2535 With prefix, insert COUNT rows before current one."
2537 (ses-check-curcell 'end)
2538 (or (> count 0) (signal 'args-out-of-range nil))
2540 (let ((inhibit-quit t)
2541 (inhibit-read-only t)
2542 (row (or (car (ses-sym-rowcol ses--curcell)) ses--numrows))
2544 ;;Create a new set of cell-variables
2545 (ses-create-cell-variable-range ses--numrows (+ ses--numrows count -1)
2546 0 (1- ses--numcols))
2547 (ses-set-parameter 'ses--numrows (+ ses--numrows count))
2549 (ses-goto-print row 0)
2550 (dotimes-with-progress-reporter (x count) "Inserting row..."
2551 ;;Create a row of empty cells. The `symbol' fields will be set by
2552 ;;the call to ses-relocate-all.
2553 (setq newrow (make-vector ses--numcols nil))
2554 (dotimes (col ses--numcols)
2555 (aset newrow col (ses-make-cell)))
2556 (setq ses--cells (ses-vector-insert ses--cells row newrow))
2557 (push `(apply ses-vector-delete ses--cells ,row 1) buffer-undo-list)
2558 (insert ses--blank-line))
2559 ;;Insert empty lines in cell data area (will be replaced by
2561 (ses-goto-data row 0)
2562 (insert (make-string (* (1+ ses--numcols) count) ?\n))
2563 (ses-relocate-all row 0 count 0)
2564 ;;If any cell printers insert constant text, insert that text
2566 (let ((cols (mapconcat #'ses-call-printer ses--col-printers nil))
2567 (global (ses-call-printer ses--default-printer)))
2568 (if (or (> (length cols) 0) (> (length global) 0))
2570 (dotimes (col ses--numcols)
2571 ;;These cells are always nil, only constant formatting printed
2572 (1value (ses-print-cell (+ x row) col))))))
2573 (when (> ses--header-row row)
2574 ;;Inserting before header
2575 (ses-set-parameter 'ses--header-row (+ ses--header-row count))
2576 (ses-reset-header-string)))
2577 ;;Reconstruct text attributes
2580 (push '(apply ses-widen) buffer-undo-list)
2581 ;;Return to current cell
2583 (ses-jump-safe ses--curcell)
2584 (ses-goto-print (1- ses--numrows) 0)))
2586 (defun ses-delete-row (count)
2587 "Delete the current row.
2588 With prefix, deletes COUNT rows starting from the current one."
2591 (or (> count 0) (signal 'args-out-of-range nil))
2592 (let ((inhibit-quit t)
2593 (inhibit-read-only t)
2594 (row (car (ses-sym-rowcol ses--curcell))))
2595 (setq count (min count (- ses--numrows row)))
2597 (ses-set-parameter 'ses--numrows (- ses--numrows count))
2598 ;;Delete lines from print area
2599 (ses-goto-print row 0)
2600 (ses-delete-line count)
2601 ;;Delete lines from cell data area
2602 (ses-goto-data row 0)
2603 (ses-delete-line (* count (1+ ses--numcols)))
2604 ;;Relocate variables and formulas
2605 (ses-set-with-undo 'ses--cells (ses-vector-delete ses--cells row count))
2606 (ses-relocate-all row 0 (- count) 0)
2607 (ses-destroy-cell-variable-range ses--numrows (+ ses--numrows count -1)
2608 0 (1- ses--numcols))
2609 (when (> ses--header-row row)
2610 (if (<= ses--header-row (+ row count))
2611 ;;Deleting the header row
2612 (ses-set-parameter 'ses--header-row 0)
2613 (ses-set-parameter 'ses--header-row (- ses--header-row count)))
2614 (ses-reset-header-string)))
2615 ;;Reconstruct attributes
2618 (push '(apply ses-widen) buffer-undo-list)
2619 (ses-jump-safe ses--curcell))
2621 (defun ses-insert-column (count &optional col width printer)
2622 "Insert a new column before COL (default is the current one).
2623 With prefix, insert COUNT columns before current one.
2624 If COL is specified, the new column(s) get the specified WIDTH and PRINTER
2625 \(otherwise they're taken from the current column)."
2628 (or (> count 0) (signal 'args-out-of-range nil))
2630 (setq col (cdr (ses-sym-rowcol ses--curcell))
2631 width (ses-col-width col)
2632 printer (ses-col-printer col)))
2634 (let ((inhibit-quit t)
2635 (inhibit-read-only t)
2636 (widths ses--col-widths)
2637 (printers ses--col-printers)
2639 ;;Create a new set of cell-variables
2640 (ses-create-cell-variable-range 0 (1- ses--numrows)
2641 ses--numcols (+ ses--numcols count -1))
2642 ;;Insert each column.
2643 (dotimes-with-progress-reporter (x count) "Inserting column..."
2644 ;;Create a column of empty cells. The `symbol' fields will be set by
2645 ;;the call to ses-relocate-all.
2646 (ses-adjust-print-width col (1+ width))
2647 (ses-set-parameter 'ses--numcols (1+ ses--numcols))
2648 (dotimes (row ses--numrows)
2649 (and (< (1+ col) ses--numcols) (eq (ses-cell-value row col) '*skip*)
2650 ;;Inserting in the middle of a spill-over
2652 (ses-aset-with-undo ses--cells row
2653 (ses-vector-insert (aref ses--cells row)
2654 col (ses-make-cell)))
2655 ;;Insert empty lines in cell data area (will be replaced by
2657 (ses-goto-data row col)
2659 ;; Insert column width and printer.
2660 (setq widths (ses-vector-insert widths col width)
2661 printers (ses-vector-insert printers col printer)))
2662 (ses-set-parameter 'ses--col-widths widths)
2663 (ses-set-parameter 'ses--col-printers printers)
2664 (ses-reset-header-string)
2665 (ses-relocate-all 0 col 0 count)
2668 (when (or (> (length (ses-call-printer printer)) 0)
2669 (> (length (ses-call-printer ses--default-printer)) 0))
2670 ;; Either column printer or global printer inserts some constant text.
2671 ;; Reprint the new columns to insert that text.
2672 (dotimes (x ses--numrows)
2674 ;; Always nil here --- this is a blank column.
2675 (1value (ses-print-cell-new-width x (+ y col))))))
2677 (ses-jump-safe ses--curcell))
2679 (defun ses-delete-column (count)
2680 "Delete the current column.
2681 With prefix, deletes COUNT columns starting from the current one."
2684 (or (> count 0) (signal 'args-out-of-range nil))
2685 (let ((inhibit-quit t)
2686 (inhibit-read-only t)
2687 (rowcol (ses-sym-rowcol ses--curcell))
2689 col origrow has-skip)
2690 (setq origrow (car rowcol)
2692 count (min count (- ses--numcols col)))
2693 (if (= count ses--numcols)
2694 (error "Can't delete all columns!"))
2695 ;;Determine width of column(s) being deleted
2697 (setq width (+ width (ses-col-width (+ col x)) 1)))
2699 (ses-set-parameter 'ses--numcols (- ses--numcols count))
2700 (ses-adjust-print-width col (- width))
2701 (dotimes-with-progress-reporter (row ses--numrows) "Deleting column..."
2702 ;;Delete lines from cell data area
2703 (ses-goto-data row col)
2704 (ses-delete-line count)
2705 ;;Delete cells. Check if deletion area begins or ends with a skip.
2706 (if (or (eq (ses-cell-value row col) '*skip*)
2707 (and (< col ses--numcols)
2708 (eq (ses-cell-value row (+ col count)) '*skip*)))
2710 (ses-aset-with-undo ses--cells row
2711 (ses-vector-delete (aref ses--cells row) col count)))
2713 (ses-set-parameter 'ses--col-widths
2714 (ses-vector-delete ses--col-widths col count))
2715 (ses-set-parameter 'ses--col-printers
2716 (ses-vector-delete ses--col-printers col count))
2717 (ses-reset-header-string)
2718 ;;Relocate variables and formulas
2719 (ses-relocate-all 0 col 0 (- count))
2720 (ses-destroy-cell-variable-range 0 (1- ses--numrows)
2721 ses--numcols (+ ses--numcols count -1))
2725 (if (>= col ses--numcols)
2726 (setq col (1- col)))
2727 (ses-goto-print origrow col)))
2729 (defun ses-forward-or-insert (&optional count)
2730 "Move to next cell in row, or inserts a new cell if already in last one, or
2731 inserts a new row if at bottom of print area. Repeat COUNT times."
2733 (ses-check-curcell 'end)
2734 (setq deactivate-mark t) ; Doesn't combine well with ranges.
2737 (if (not ses--curcell)
2738 (progn ; At bottom of print area.
2739 (barf-if-buffer-read-only)
2741 (let ((col (cdr (ses-sym-rowcol ses--curcell))))
2743 (char-before (next-single-property-change (point)
2745 ;; We're already in last nonskipped cell on line. Need to create a
2747 (barf-if-buffer-read-only)
2748 (ses-insert-column (- count x)
2751 (ses-col-printer col)))))
2754 (defun ses-append-row-jump-first-column ()
2755 "Insert a new row after current one and jump to its first column."
2759 (beginning-of-line 2)
2763 (defun ses-set-column-width (col newwidth)
2764 "Set the width of the current column."
2766 (let ((col (cdr (progn (ses-check-curcell) (ses-sym-rowcol ses--curcell)))))
2767 (barf-if-buffer-read-only)
2769 (if current-prefix-arg
2770 (prefix-numeric-value current-prefix-arg)
2771 (read-from-minibuffer (format "Column %s width (default %d): "
2772 (ses-column-letter col)
2773 (ses-col-width col))
2774 nil ; No initial contents.
2775 nil ; No override keymap.
2776 t ; Convert to Lisp object.
2779 (ses-col-width col))))))) ; Default value.
2781 (error "Invalid column width"))
2783 (ses-reset-header-string)
2785 (let ((inhibit-quit t))
2786 (ses-adjust-print-width col (- newwidth (ses-col-width col)))
2787 (ses-set-parameter 'ses--col-widths newwidth col))
2788 (dotimes (row ses--numrows)
2789 (ses-print-cell-new-width row col))))
2792 ;;----------------------------------------------------------------------------
2793 ;; Cut and paste, import and export
2794 ;;----------------------------------------------------------------------------
2796 (defun ses--advice-copy-region-as-kill (crak-fun beg end &rest args)
2797 ;; FIXME: Why doesn't it make sense to copy read-only or
2798 ;; intangible attributes? They're removed upon yank!
2799 "It doesn't make sense to copy read-only or intangible attributes into the
2800 kill ring. It probably doesn't make sense to copy keymap properties.
2801 We'll assume copying front-sticky properties doesn't make sense, either.
2803 This advice also includes some SES-specific code because otherwise it's too
2804 hard to override how mouse-1 works."
2809 (if (not (and (derived-mode-p 'ses-mode)
2810 (eq (get-text-property beg 'read-only) 'ses)
2811 (eq (get-text-property (1- end) 'read-only) 'ses)))
2812 (apply crak-fun beg end args) ; Normal copy-region-as-kill.
2813 (kill-new (ses-copy-region beg end))
2814 (if transient-mark-mode
2815 (setq deactivate-mark t))
2817 (advice-add 'copy-region-as-kill :around #'ses--advice-copy-region-as-kill)
2819 (defun ses-copy-region (beg end)
2820 "Treat the region as rectangular. Convert the intangible attributes to
2821 SES attributes recording the contents of the cell as of the time of copying."
2822 (when (= end ses--data-marker)
2823 ;;Avoid overflow situation
2824 (setq end (1- ses--data-marker)))
2825 (let* ((inhibit-point-motion-hooks t)
2826 (x (mapconcat 'ses-copy-region-helper
2827 (extract-rectangle beg (1- end)) "\n")))
2828 (remove-text-properties 0 (length x)
2836 (defun ses-copy-region-helper (line)
2837 "Converts one line (of a rectangle being extracted from a spreadsheet) to
2838 external form by attaching to each print cell a 'ses attribute that records
2839 the corresponding data cell."
2840 (or (> (length line) 1)
2841 (error "Empty range"))
2842 (let ((inhibit-read-only t)
2844 mycell next sym rowcol)
2846 (setq sym (get-text-property pos 'intangible line)
2847 next (next-single-property-change pos 'intangible line)
2848 rowcol (ses-sym-rowcol sym)
2849 mycell (ses-get-cell (car rowcol) (cdr rowcol)))
2850 (put-text-property pos (or next (length line))
2852 (list (ses-cell-symbol mycell)
2853 (ses-cell-formula mycell)
2854 (ses-cell-printer mycell))
2859 (defun ses-kill-override (beg end)
2860 "Generic override for any commands that kill text.
2861 We clear the killed cells instead of deleting them."
2863 (ses-check-curcell 'needrange)
2864 ;; For some reason, the text-read-only error is not caught by `delete-region',
2865 ;; so we have to use subterfuge.
2866 (let ((buffer-read-only t))
2867 (1value (condition-case nil
2868 (noreturn (funcall (lookup-key (current-global-map)
2869 (this-command-keys))
2871 (buffer-read-only nil)))) ; The expected error.
2872 ;; Because the buffer was marked read-only, the kill command turned itself
2873 ;; into a copy. Now we clear the cells or signal the error. First we check
2874 ;; whether the buffer really is read-only.
2875 (barf-if-buffer-read-only)
2877 (ses-dorange ses--curcell
2878 (ses-clear-cell row col))
2879 (ses-jump (car ses--curcell)))
2881 (defun ses--advice-yank (yank-fun &optional arg &rest args)
2882 "In SES mode, the yanked text is inserted as cells.
2884 If the text contains 'ses attributes (meaning it went to the kill-ring from a
2885 SES buffer), the formulas and print functions are restored for the cells. If
2886 the text contains tabs, this is an insertion of tab-separated formulas.
2887 Otherwise the text is inserted as the formula for the current cell.
2889 When inserting cells, the formulas are usually relocated to keep the same
2890 relative references to neighboring cells. This is best if the formulas
2891 generally refer to other cells within the yanked text. You can use the C-u
2892 prefix to specify insertion without relocation, which is best when the
2893 formulas refer to cells outside the yanked text.
2895 When inserting formulas, the text is treated as a string constant if it doesn't
2896 make sense as a sexp or would otherwise be considered a symbol. Use 'sym to
2897 explicitly insert a symbol, or use the C-u prefix to treat all unmarked words
2899 (if (not (and (derived-mode-p 'ses-mode)
2900 (eq (get-text-property (point) 'keymap) 'ses-mode-print-map)))
2901 (apply yank-fun arg args) ; Normal non-SES yank.
2902 (ses-check-curcell 'end)
2904 (let ((text (current-kill (cond
2908 (or (ses-yank-cells text arg)
2909 (ses-yank-tsf text arg)
2910 (ses-yank-one (ses-yank-resize 1 1)
2913 (if (memq (aref text (1- (length text))) '(?\t ?\n))
2914 ;; Just one cell --- delete final tab or newline.
2918 (exchange-point-and-mark))))
2919 (advice-add 'yank :around #'ses--advice-yank)
2921 (defun ses-yank-pop (arg)
2922 "Replace just-yanked stretch of killed text with a different stretch.
2923 This command is allowed only immediately after a `yank' or a `yank-pop',
2924 when the region contains a stretch of reinserted previously-killed text.
2925 We replace it with a different stretch of killed text.
2926 Unlike standard `yank-pop', this function uses `undo' to delete the
2927 previous insertion."
2929 (or (eq last-command 'yank)
2930 ;;Use noreturn here just to avoid a "poor-coverage" warning in its
2932 (noreturn (error "Previous command was not a yank")))
2935 (yank (1+ (or arg 1)))
2936 (setq this-command 'yank))
2938 (defun ses-yank-cells (text arg)
2939 "If the TEXT has a proper set of 'ses attributes, insert the text as
2940 cells, else return nil. The cells are reprinted--the supplied text is
2941 ignored because the column widths, default printer, etc. at yank time might
2942 be different from those at kill-time. ARG is a list to indicate that
2943 formulas are to be inserted without relocation."
2944 (let ((first (get-text-property 0 'ses text))
2945 (last (get-text-property (1- (length text)) 'ses text)))
2946 (when (and first last) ;;Otherwise not proper set of attributes
2947 (setq first (ses-sym-rowcol (car first))
2948 last (ses-sym-rowcol (car last)))
2949 (let* ((needrows (- (car last) (car first) -1))
2950 (needcols (- (cdr last) (cdr first) -1))
2951 (rowcol (ses-yank-resize needrows needcols))
2952 (rowincr (- (car rowcol) (car first)))
2953 (colincr (- (cdr rowcol) (cdr first)))
2956 (dotimes-with-progress-reporter (row needrows) "Yanking..."
2957 (setq myrow (+ row (car rowcol)))
2958 (dotimes (col needcols)
2959 (setq mycol (+ col (cdr rowcol))
2960 last (get-text-property pos 'ses text)
2961 pos (next-single-property-change pos 'ses text)
2962 x (ses-sym-rowcol (car last)))
2964 ;; Newline --- all remaining cells on row are skipped.
2965 (setq x (cons (- myrow rowincr) (+ needcols colincr -1))
2966 last (list nil nil nil)
2968 (if (/= (car x) (- myrow rowincr))
2969 (error "Cell row error"))
2970 (if (< (- mycol colincr) (cdr x))
2971 ;; Some columns were skipped.
2972 (let ((oldcol mycol))
2973 (while (< (- mycol colincr) (cdr x))
2974 (ses-clear-cell myrow mycol)
2977 (ses-print-cell myrow (1- oldcol)))) ;; This inserts *skip*.
2978 (when (car last) ; Skip this for *skip* cells.
2979 (setq x (nth 2 last))
2980 (unless (equal x (ses-cell-printer myrow mycol))
2983 (eq (car-safe x) 'ses-safe-printer)
2984 (setq x `(ses-safe-printer ,x)))
2985 (ses-set-cell myrow mycol 'printer x))
2986 (setq x (cadr last))
2988 (setq x (ses-relocate-formula x 0 0 rowincr colincr)))
2990 (eq (car-safe x) 'ses-safe-formula)
2991 (setq x `(ses-safe-formula ,x)))
2992 (ses-cell-set-formula myrow mycol x)))
2994 (if (get-text-property pos 'ses text)
2995 (error "Missing newline between rows"))
2996 (setq pos (next-single-property-change pos 'ses text))))
2999 (defun ses-yank-one (rowcol text from to arg)
3000 "Insert the substring [FROM,TO] of TEXT as the formula for cell ROWCOL (a
3001 cons of ROW and COL). Treat plain symbols as strings unless ARG is a list."
3002 (let ((val (condition-case nil
3003 (read-from-string text from to)
3004 (error (cons nil from)))))
3006 ((< (cdr val) (or to (length text)))
3007 ;; Invalid sexp --- leave it as a string.
3008 (setq val (substring text from to)))
3009 ((and (car val) (symbolp (car val)))
3010 (setq val (if (consp arg)
3011 (list 'quote (car val)) ; Keep symbol.
3012 (substring text from to)))) ; Treat symbol as text.
3014 (setq val (car val))))
3015 (let ((row (car rowcol))
3018 (setq val `(ses-safe-formula ,val)))
3019 (ses-cell-set-formula row col val))))
3021 (defun ses-yank-tsf (text arg)
3022 "If TEXT contains tabs and/or newlines, treat the tabs as
3023 column-separators and the newlines as row-separators and insert the text as
3024 cell formulas--else return nil. Treat plain symbols as strings unless ARG
3025 is a list. Ignore a final newline."
3026 (if (or (not (string-match "[\t\n]" text))
3027 (= (match-end 0) (length text)))
3030 (if (/= (aref text (1- (length text))) ?\n)
3031 (setq text (concat text "\n")))
3037 ;;Find all the tabs and newlines
3038 (while (setq pos (string-match "[\t\n]" text (1+ pos)))
3040 (setq cols (1+ cols))
3041 (when (eq (aref text pos) ?\n)
3043 (setq needcols cols)
3044 (or (= needcols cols)
3045 (error "Inconsistent row lengths")))
3047 needrows (1+ needrows))))
3048 ;;Insert the formulas
3049 (setq rowcol (ses-yank-resize needrows needcols))
3050 (dotimes (row needrows)
3051 (dotimes (col needcols)
3052 (ses-yank-one (cons (+ (car rowcol) needrows (- row) -1)
3053 (+ (cdr rowcol) needcols (- col) -1))
3054 text (1+ (cadr spots)) (car spots) arg)
3055 (setq spots (cdr spots))))
3056 (ses-goto-print (+ (car rowcol) needrows -1)
3057 (+ (cdr rowcol) needcols -1))
3060 (defun ses-yank-resize (needrows needcols)
3061 "If this yank will require inserting rows and/or columns, ask for
3062 confirmation and then insert them. Result is (row,col) for top left of yank
3063 spot, or error signal if user requests cancel."
3065 (let ((rowcol (if ses--curcell
3066 (ses-sym-rowcol ses--curcell)
3067 (cons ses--numrows 0)))
3069 (setq needrows (- (+ (car rowcol) needrows) ses--numrows)
3070 needcols (- (+ (cdr rowcol) needcols) ses--numcols)
3071 rowbool (> needrows 0)
3072 colbool (> needcols 0))
3073 (when (or rowbool colbool)
3074 ;;Need to insert. Get confirm
3075 (or (y-or-n-p (format "Yank will insert %s%s%s. Continue? "
3076 (if rowbool (format "%d rows" needrows) "")
3077 (if (and rowbool colbool) " and " "")
3078 (if colbool (format "%d columns" needcols) "")))
3083 (ses-goto-print ses--numrows 0)
3084 (ses-insert-row needrows))))
3086 (ses-insert-column needcols
3088 (ses-col-width (1- ses--numcols))
3089 (ses-col-printer (1- ses--numcols)))))
3092 (defun ses-export-tsv (_beg _end)
3093 "Export values from the current range, with tabs between columns and
3094 newlines between rows. Result is placed in kill ring."
3096 (ses-export-tab nil))
3098 (defun ses-export-tsf (_beg _end)
3099 "Export formulas from the current range, with tabs between columns and
3100 newlines between rows. Result is placed in kill ring."
3104 (defun ses-export-tab (want-formulas)
3105 "Export the current range with tabs between columns and newlines between rows.
3106 Result is placed in kill ring. The export is values unless WANT-FORMULAS
3107 is non-nil. Newlines and tabs in the export text are escaped."
3108 (ses-check-curcell 'needrange)
3109 (let ((print-escape-newlines t)
3111 (ses-dorange ses--curcell
3112 (setq item (if want-formulas
3113 (ses-cell-formula row col)
3114 (ses-cell-value row col)))
3115 (if (eq (car-safe item) 'ses-safe-formula)
3116 ;;Hide our deferred safety-check marker
3117 (setq item (cadr item)))
3118 (if (or (not item) (eq item '*skip*))
3120 (when (eq (car-safe item) 'quote)
3122 (setq item (cadr item)))
3123 (setq item (prin1-to-string item t))
3124 (setq item (replace-regexp-in-string "\t" "\\\\t" item))
3130 (push "\n" result))))
3131 (setq result (apply 'concat (nreverse result)))
3135 ;;----------------------------------------------------------------------------
3136 ;; Other user commands
3137 ;;----------------------------------------------------------------------------
3139 (defun ses-unset-header-row ()
3140 "Select the default header row."
3142 (ses-set-header-row 0))
3144 (defun ses-set-header-row (row)
3145 "Set the ROW to display in the header-line.
3146 With a numerical prefix arg, use that row.
3147 With no prefix arg, use the current row.
3148 With a \\[universal-argument] prefix arg, prompt the user.
3149 The top row is row 1. Selecting row 0 displays the default header row."
3151 (list (if (numberp current-prefix-arg) current-prefix-arg
3152 (let ((currow (1+ (car (ses-sym-rowcol ses--curcell)))))
3153 (if current-prefix-arg
3154 (read-number "Header row: " currow)
3156 (if (or (< row 0) (> row ses--numrows))
3157 (error "Invalid header-row"))
3159 (let ((oldval ses--header-row))
3160 (let (buffer-undo-list)
3161 (ses-set-parameter 'ses--header-row row))
3162 (push `(apply ses-set-header-row ,oldval) buffer-undo-list))
3163 (ses-reset-header-string))
3165 (defun ses-mark-row ()
3166 "Mark the entirety of current row as a range."
3168 (ses-check-curcell 'range)
3169 (let ((row (car (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell)))))
3171 (ses-goto-print (1+ row) 0)
3172 (push-mark (point) nil t)
3173 (ses-goto-print row 0)))
3175 (defun ses-mark-column ()
3176 "Mark the entirety of current column as a range."
3178 (ses-check-curcell 'range)
3179 (let ((col (cdr (ses-sym-rowcol (or (car-safe ses--curcell) ses--curcell))))
3182 (ses-goto-print (1- ses--numrows) col)
3184 (push-mark (point) nil t)
3185 (while (eq '*skip* (ses-cell-value row col))
3186 ;;Skip over initial cells in column that can't be selected
3187 (setq row (1+ row)))
3188 (ses-goto-print row col)))
3190 (defun ses-end-of-line ()
3191 "Move point to last cell on line."
3193 (ses-check-curcell 'end 'range)
3194 (when ses--curcell ; Otherwise we're at the bottom row, which is empty
3196 (let ((col (1- ses--numcols))
3198 (if (symbolp ses--curcell)
3200 (setq row (car (ses-sym-rowcol ses--curcell)))
3201 ;; Range --- use whichever end of the range the point is at.
3202 (setq rowcol (ses-sym-rowcol (if (< (point) (mark))
3204 (cdr ses--curcell))))
3205 ;; If range already includes the last cell in a row, point is actually
3206 ;; in the following row.
3207 (if (<= (cdr rowcol) (1- col))
3208 (setq row (car rowcol))
3209 (setq row (1+ (car rowcol)))
3210 (if (= row ses--numrows)
3211 ;;Already at end - can't go anywhere
3213 (when (< row ses--numrows) ; Otherwise it's a range that includes last cell.
3214 (while (eq (ses-cell-value row col) '*skip*)
3215 ;; Back to beginning of multi-column cell.
3216 (setq col (1- col)))
3217 (ses-goto-print row col)))))
3219 (defun ses-renarrow-buffer ()
3220 "Narrow the buffer so only the print area is visible.
3221 Use after \\[widen]."
3223 (setq ses--deferred-narrow t))
3225 (defun ses-sort-column (sorter &optional reverse)
3226 "Sort the range by a specified column.
3227 With prefix, sorts in REVERSE order."
3228 (interactive "*sSort column: \nP")
3229 (ses-check-curcell 'needrange)
3230 (let ((min (ses-sym-rowcol (car ses--curcell)))
3231 (max (ses-sym-rowcol (cdr ses--curcell))))
3232 (let ((minrow (car min))
3237 (setq sorter (cdr (ses-sym-rowcol (intern (concat sorter "1")))))
3238 (or (and sorter (>= sorter mincol) (<= sorter maxcol))
3239 (error "Invalid sort column"))
3240 ;;Get key columns and sort them
3241 (dotimes (x (- maxrow minrow -1))
3242 (ses-goto-print (+ minrow x) sorter)
3243 (setq end (next-single-property-change (point) 'intangible))
3244 (push (cons (buffer-substring-no-properties (point) end)
3247 (setq keys (sort keys #'(lambda (x y) (string< (car x) (car y)))))
3248 ;;Extract the lines in reverse sorted order
3250 (setq keys (nreverse keys)))
3252 (ses-goto-print (cdr x) (1+ maxcol))
3254 (ses-goto-print (cdr x) mincol)
3255 (push (ses-copy-region (point) end) extracts))
3257 ;;Paste the lines sequentially
3258 (dotimes (x (- maxrow minrow -1))
3259 (ses-goto-print (+ minrow x) mincol)
3261 (ses-yank-cells (pop extracts) nil)))))
3263 (defun ses-sort-column-click (event reverse)
3264 "Mouse version of `ses-sort-column'."
3265 (interactive "*e\nP")
3266 (setq event (event-end event))
3267 (select-window (posn-window event))
3268 (setq event (car (posn-col-row event))) ; Click column.
3270 (while (and (< col ses--numcols) (> event (ses-col-width col)))
3271 (setq event (- event (ses-col-width col) 1)
3273 (if (>= col ses--numcols)
3275 (ses-sort-column (ses-column-letter col) reverse))))
3277 (defun ses-insert-range ()
3278 "Insert into minibuffer the list of cells currently highlighted in the
3282 (with-current-buffer (window-buffer minibuffer-scroll-window)
3283 (ses-command-hook) ; For ses-coverage.
3284 (ses-check-curcell 'needrange)
3285 (setq x (cdr (macroexpand `(ses-range ,(car ses--curcell)
3286 ,(cdr ses--curcell))))))
3287 (insert (substring (prin1-to-string (nreverse x)) 1 -1))))
3289 (defun ses-insert-ses-range ()
3290 "Insert \"(ses-range x y)\" in the minibuffer to represent the currently
3291 highlighted range in the spreadsheet."
3294 (with-current-buffer (window-buffer minibuffer-scroll-window)
3295 (ses-command-hook) ; For ses-coverage.
3296 (ses-check-curcell 'needrange)
3297 (setq x (format "(ses-range %S %S)"
3299 (cdr ses--curcell))))
3302 (defun ses-insert-range-click (event)
3303 "Mouse version of `ses-insert-range'."
3305 (mouse-set-point event)
3308 (defun ses-insert-ses-range-click (event)
3309 "Mouse version of `ses-insert-ses-range'."
3311 (mouse-set-point event)
3312 (ses-insert-ses-range))
3314 (defun ses-replace-name-in-formula (formula old-name new-name)
3315 (let ((new-formula formula))
3316 (unless (and (consp formula)
3317 (eq (car-safe formula) 'quote))
3319 (let ((elt (car-safe formula)))
3322 (setcar formula (ses-replace-name-in-formula elt old-name new-name)))
3324 (eq (car-safe formula) old-name))
3325 (setcar formula new-name))))
3326 (setq formula (cdr formula))))
3329 (defun ses-rename-cell (new-name &optional cell)
3330 "Rename current cell."
3331 (interactive "*SEnter new name: ")
3333 (and (local-variable-p new-name)
3334 (ses-is-cell-sym-p new-name)
3335 (error "Already a cell name"))
3336 (and (boundp new-name)
3337 (null (yes-or-no-p (format "`%S' is already bound outside this buffer, continue? "
3339 (error "Already a bound cell name")))
3341 (sym (if (ses-cell-p cell)
3342 (ses-cell-symbol cell)
3347 (rowcol (ses-sym-rowcol sym))
3350 new-rowcol old-name)
3351 (setq cell (or cell (ses-get-cell row col))
3352 old-name (ses-cell-symbol cell)
3353 new-rowcol (ses-decode-cell-symbol (symbol-name new-name)))
3355 (if (equal new-rowcol rowcol)
3356 (put new-name 'ses-cell rowcol)
3357 (error "Not a valid name for this cell location"))
3358 (setq ses--named-cell-hashmap
3359 (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
3360 (put new-name 'ses-cell :ses-named)
3361 (puthash new-name rowcol ses--named-cell-hashmap))
3362 (push `(ses-rename-cell ,old-name ,cell) buffer-undo-list)
3363 ;; Replace name by new name in formula of cells refering to renamed cell.
3364 (dolist (ref (ses-cell-references cell))
3365 (let* ((x (ses-sym-rowcol ref))
3366 (xcell (ses-get-cell (car x) (cdr x))))
3367 (setf (ses-cell-formula xcell)
3368 (ses-replace-name-in-formula
3369 (ses-cell-formula xcell)
3372 ;; Replace name by new name in reference list of cells to which renamed
3374 (dolist (ref (ses-formula-references (ses-cell-formula cell)))
3375 (let* ((x (ses-sym-rowcol ref))
3376 (xcell (ses-get-cell (car x) (cdr x))))
3377 (setf (ses-cell-references xcell)
3378 (cons new-name (delq sym
3379 (ses-cell-references xcell))))))
3380 (push new-name ses--renamed-cell-symb-list)
3381 (set new-name (symbol-value sym))
3382 (setf (ses-cell--symbol cell) new-name)
3384 (and curcell (setq ses--curcell new-name))
3385 (let* ((pos (point))
3386 (inhibit-read-only t)
3387 (col (current-column))
3388 (end (save-excursion
3389 (move-to-column (1+ col))
3391 (+ pos (ses-col-width col) 1)
3393 (put-text-property pos end 'intangible new-name))
3395 (setq mode-line-process (list " cell "
3396 (symbol-name new-name)))
3397 (force-mode-line-update)))
3399 (defun ses-refresh-local-printer (name compiled-value)
3400 "Refresh printout for all cells which use printer NAME.
3401 NAME should be the name of a locally defined printer.
3402 Uses the value COMPILED-VALUE for this printer."
3403 (message "Refreshing cells using printer %S" name)
3405 (dotimes (row ses--numrows)
3406 (dotimes (col ses--numcols)
3407 (let ((cell-printer (ses-cell-printer row col)))
3408 (when (eq cell-printer name)
3412 (ses-print-cell row col)))))))
3414 (defun ses-define-local-printer (name)
3415 "Define a local printer with name NAME."
3416 (interactive "*SEnter printer name: ")
3417 (let* ((cur-printer (gethash name ses--local-printer-hashmap))
3418 (default (and (vectorp cur-printer) (ses--locprn-def cur-printer)))
3421 (ses-read-printer (format "Enter definition of printer %S: " name)
3424 ;; cancelled operation => do nothing
3426 ;; no change => do nothing
3427 ((and (vectorp cur-printer) (equal new-def default)))
3428 ;; re-defined printer
3429 ((vectorp cur-printer)
3430 (setq create-printer 0)
3431 (setf (ses--locprn-def cur-printer) new-def)
3432 (ses-refresh-local-printer
3434 (setf (ses--locprn-compiled cur-printer)
3435 (ses-local-printer-compile new-def))))
3438 (setq create-printer 1)
3441 (ses-make-local-printer-info new-def))
3442 ses--local-printer-hashmap)))
3443 (when create-printer
3444 (let ((printer-def-text
3446 "(ses-local-printer "
3449 (prin1-to-string (ses--locprn-def cur-printer))
3452 (ses-goto-data ses--numrows
3453 (ses--locprn-number cur-printer))
3454 (let ((inhibit-read-only t))
3455 ;; Special undo since it's outside the narrowed buffer.
3456 (let (buffer-undo-list)
3457 (if (= create-printer 0)
3458 (delete-region (point) (line-end-position))
3461 (insert printer-def-text)
3462 (when (= create-printer 1)
3463 (ses-file-format-extend-paramter-list 3)
3464 (ses-set-parameter 'ses--numlocprn
3465 (+ ses--numlocprn create-printer))))))))))
3468 ;;----------------------------------------------------------------------------
3469 ;; Checking formulas for safety
3470 ;;----------------------------------------------------------------------------
3472 (defun ses-safe-printer (printer)
3473 "Return PRINTER if safe, or the substitute printer `ses-unsafe' otherwise."
3474 (if (or (stringp printer)
3475 (stringp (car-safe printer))
3477 (and (symbolp printer) (gethash printer ses--local-printer-hashmap))
3478 (ses-warn-unsafe printer 'unsafep-function))
3482 (defun ses-safe-formula (formula)
3483 "Return FORMULA if safe, or the substitute formula *unsafe* otherwise."
3484 (if (ses-warn-unsafe formula 'unsafep)
3486 `(ses-unsafe ',formula)))
3488 (defun ses-warn-unsafe (formula checker)
3489 "Apply CHECKER to FORMULA.
3490 If result is non-nil, asks user for confirmation about FORMULA,
3491 which might be unsafe. Returns t if formula is safe or user allows
3492 execution anyway. Always returns t if `safe-functions' is t."
3493 (if (eq safe-functions t)
3495 (setq checker (funcall checker formula))
3498 (y-or-n-p (format "Formula %S\nmight be unsafe %S. Process it? "
3499 formula checker)))))
3502 ;;----------------------------------------------------------------------------
3503 ;; Standard formulas
3504 ;;----------------------------------------------------------------------------
3506 (defun ses--clean-! (&rest x)
3507 "Clean by `delq' list X from any occurrence of `nil' or `*skip*'."
3508 (delq nil (delq '*skip* x)))
3510 (defun ses--clean-_ (x y)
3511 "Clean list X by replacing by Y any occurrence of `nil' or `*skip*'.
3513 This will change X by making `setcar' on its cons cells."
3514 (let ((ret x) ret-elt)
3516 (setq ret-elt (car ret))
3517 (when (memq ret-elt '(nil *skip*))
3519 (setq ret (cdr ret))))
3522 (defmacro ses-range (from to &rest rest)
3523 "Expand to a list of cell-symbols for the range going from
3524 FROM up to TO. The range automatically expands to include any
3525 new row or column inserted into its middle. The SES library code
3526 specifically looks for the symbol `ses-range', so don't create an
3527 alias for this macro!
3529 By passing in REST some flags one can configure the way the range
3530 is read and how it is formatted.
3532 In the sequel we assume that cells A1, B1, A2 B2 have respective values
3535 Readout direction is specified by a `>v', '`>^', `<v', `<^',
3536 `v>', `v<', `^>', `^<' flag. For historical reasons, in absence
3537 of such a flag, a default direction of `^<' is assumed. This
3538 way `(ses-range A1 B2 ^>)' will evaluate to `(1 3 2 4)',
3539 while `(ses-range A1 B2 >^)' will evaluate to (3 4 1 2).
3541 If the range is one row, then `>' can be used as a shorthand to
3542 `>v' or `>^', and `<' to `<v' or `<^'.
3544 If the range is one column, then `v' can be used as a shorthand to
3545 `v>' or `v<', and `^' to `^>' or `v<'.
3547 A `!' flag will remove all cells whose value is nil or `*skip*'.
3549 A `_' flag will replace nil or `*skip*' by the value following
3550 the `_' flag. If the `_' flag is the last argument, then they are
3551 replaced by integer 0.
3553 A `*', `*1' or `*2' flag will vectorize the range in the sense of
3554 Calc. See info node `(Calc) Top'. Flag `*' will output either a
3555 vector or a matrix depending on the number of rows, `*1' will
3556 flatten the result to a one row vector, and `*2' will make a
3557 matrix whatever the number of rows.
3559 Warning: interaction with Calc is experimental and may produce
3560 confusing results if you are not aware of Calc data format.
3561 Use `math-format-value' as a printer for Calc objects."
3569 (ses-dorange (cons from to)
3570 (when (/= prev-row row)
3571 (push result-row result)
3572 (setq result-row nil))
3573 (push (ses-cell-symbol row col) result-row)
3574 (setq prev-row row))
3575 (push result-row result)
3577 (let ((x (pop rest)))
3579 (`>v (setq transpose nil reorient-x nil reorient-y nil))
3580 (`>^ (setq transpose nil reorient-x nil reorient-y t))
3581 (`<^ (setq transpose nil reorient-x t reorient-y t))
3582 (`<v (setq transpose nil reorient-x t reorient-y nil))
3583 (`v> (setq transpose t reorient-x nil reorient-y t))
3584 (`^> (setq transpose t reorient-x nil reorient-y nil))
3585 (`^< (setq transpose t reorient-x t reorient-y nil))
3586 (`v< (setq transpose t reorient-x t reorient-y t))
3587 ((or `* `*2 `*1) (setq vectorize x))
3588 (`! (setq clean 'ses--clean-!))
3589 (`_ (setq clean `(lambda (&rest x)
3590 (ses--clean-_ x ,(if rest (pop rest) 0)))))
3593 ; shorthands one row
3594 ((and (null (cddr result)) (memq x '(> <)))
3595 (push (intern (concat (symbol-name x) "v")) rest))
3596 ; shorthands one col
3597 ((and (null (cdar result)) (memq x '(v ^)))
3598 (push (intern (concat (symbol-name x) ">")) rest))
3599 (t (error "Unexpected flag `%S' in ses-range" x)))))))
3601 (setcdr (last result 2) nil)
3602 (setq result (cdr (nreverse result))))
3604 (setq result (mapcar 'nreverse result)))
3606 (let ((ret (mapcar (lambda (x) (list x)) (pop result))) iter)
3609 (dolist (elt (pop result))
3610 (setcar iter (cons elt (car iter)))
3611 (setq iter (cdr iter))))
3614 (cl-flet ((vectorize-*1
3616 (cons clean (cons (quote 'vec) (apply 'append result))))
3619 (cons clean (cons (quote 'vec)
3621 (cons clean (cons (quote 'vec) x)))
3624 (`nil (cons clean (apply 'append result)))
3625 (`*1 (vectorize-*1 clean result))
3626 (`*2 (vectorize-*2 clean result))
3627 (`* (funcall (if (cdr result)
3632 (defun ses-delete-blanks (&rest args)
3633 "Return ARGS reversed, with the blank elements (nil and *skip*) removed."
3636 (unless (memq cur '(nil *skip*))
3640 (defun ses+ (&rest args)
3641 "Compute the sum of the arguments, ignoring blanks."
3642 (apply '+ (apply 'ses-delete-blanks args)))
3644 (defun ses-average (list)
3645 "Computes the sum of the numbers in LIST, divided by their length. Blanks
3646 are ignored. Result is always floating-point, even if all args are integers."
3647 (setq list (apply 'ses-delete-blanks list))
3648 (/ (float (apply '+ list)) (length list)))
3650 (defmacro ses-select (fromrange test torange)
3651 "Select cells in FROMRANGE that are `equal' to TEST.
3652 For each match, return the corresponding cell from TORANGE.
3653 The ranges are macroexpanded but not evaluated so they should be
3654 either (ses-range BEG END) or (list ...). The TEST is evaluated."
3655 (setq fromrange (cdr (macroexpand fromrange))
3656 torange (cdr (macroexpand torange))
3658 (or (= (length fromrange) (length torange))
3659 (error "ses-select: Ranges not same length"))
3661 (dolist (x fromrange)
3662 (if (equal test (symbol-value x))
3663 (push (car torange) result))
3664 (setq torange (cdr torange)))
3665 (cons 'list result)))
3667 ;;All standard formulas are safe
3668 (dolist (x '(ses-cell-value ses-range ses-delete-blanks ses+ ses-average
3670 (put x 'side-effect-free t))
3673 ;;----------------------------------------------------------------------------
3674 ;; Standard print functions
3675 ;;----------------------------------------------------------------------------
3677 ;; These functions use the variables 'row' and 'col' that are dynamically bound
3678 ;; by ses-print-cell. We define these variables at compile-time to make the
3683 (defun ses-center (value &optional span fill)
3684 "Print VALUE, centered within column.
3685 FILL is the fill character for centering (default = space).
3686 SPAN indicates how many additional rightward columns to include
3687 in width (default = 0)."
3688 (let ((printer (or (ses-col-printer col) ses--default-printer))
3689 (width (ses-col-width col))
3691 (or fill (setq fill ?\s))
3692 (or span (setq span 0))
3693 (setq value (ses-call-printer printer value))
3695 (setq width (+ width 1 (ses-col-width (+ col span (- x))))))
3696 ;; Set column width.
3697 (setq width (- width (string-width value)))
3699 value ; Too large for field, anyway.
3700 (setq half (make-string (/ width 2) fill))
3701 (concat half value half
3702 (if (> (% width 2) 0) (char-to-string fill))))))
3704 (defun ses-center-span (value &optional fill)
3705 "Print VALUE, centered within the span that starts in the current column
3706 and continues until the next nonblank column.
3707 FILL specifies the fill character (default = space)."
3708 (let ((end (1+ col)))
3709 (while (and (< end ses--numcols)
3710 (memq (ses-cell-value row end) '(nil *skip*)))
3711 (setq end (1+ end)))
3712 (ses-center value (- end col 1) fill)))
3714 (defun ses-dashfill (value &optional span)
3715 "Print VALUE centered using dashes.
3716 SPAN indicates how many rightward columns to include in width (default = 0)."
3717 (ses-center value span ?-))
3719 (defun ses-dashfill-span (value)
3720 "Print VALUE, centered using dashes within the span that starts in the
3721 current column and continues until the next nonblank column."
3722 (ses-center-span value ?-))
3724 (defun ses-tildefill-span (value)
3725 "Print VALUE, centered using tildes within the span that starts in the
3726 current column and continues until the next nonblank column."
3727 (ses-center-span value ?~))
3729 (defun ses-unsafe (_value)
3730 "Substitute for an unsafe formula or printer."
3731 (error "Unsafe formula or printer"))
3733 ;;All standard printers are safe, including ses-unsafe!
3734 (dolist (x (cons 'ses-unsafe ses-standard-printer-functions))
3735 (put x 'side-effect-free t))
3737 (defun ses-unload-function ()
3738 "Unload the Simple Emacs Spreadsheet."
3739 (advice-remove 'yank #'ses--advice-yank)
3740 (advice-remove 'copy-region-as-kill #'ses--advice-copy-region-as-kill)
3741 ;; Continue standard unloading.
3746 ;;; ses.el ends here