ses.el 134 KB
Newer Older
1
;;; ses.el -- Simple Emacs Spreadsheet  -*- coding: utf-8 -*-
2

3
;; Copyright (C) 2002-2014 Free Software Foundation, Inc.
4

Jonathan Yavner's avatar
Jonathan Yavner committed
5
;; Author: Jonathan Yavner <jyavner@member.fsf.org>
6 7
;; Maintainer: Vincent Belaïche  <vincentb1@users.sourceforge.net>
;; Keywords: spreadsheet Dijkstra
8 9 10

;; 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 14
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
15 16 17 18 19 20 21

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23

24 25
;;; Commentary:

26
;;; To-do list:
27

28
;; * split (catch 'cycle ...) call back into one or more functions
29 30 31
;; * Use $ or … for truncated fields
;; * Add command to make a range of columns be temporarily invisible.
;; * 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 35 36 37 38 39
;; * Input validation functions.  How specified?
;; * Faces (colors & styles) in print cells.
;; * Move a column by dragging its letter in the header line.
;; * Left-margin column for row number.
;; * Move a row by dragging its number in the left-margin.

40 41 42 43 44 45
;;; Cycle detection

;; Cycles used to be detected by stationarity of ses--deferred-recalc.  This was
;; working fine in most cases, however failed in some cases of several path
;; racing together.
;;
46
;; The current algorithm is based on Dijkstra's algorithm.  The cycle length is
47 48 49 50 51 52 53 54
;; stored in some cell property. In order not to reset in all cells such
;; property at each update, the cycle length is stored in this property along
;; with some update attempt id that is incremented at each update. The current
;; update id is ses--Dijkstra-attempt-nb. In case there is a cycle the cycle
;; length diverge to infinite so it will exceed ses--Dijkstra-weight-bound at
;; some point of time that allows detection. Otherwise it converges to the
;; longest path length in the update tree.

55 56 57

;;; Code:

58
(require 'unsafep)
59
(eval-when-compile (require 'cl-lib))
60 61


62 63 64
;;----------------------------------------------------------------------------
;; User-customizable variables
;;----------------------------------------------------------------------------
65 66

(defgroup ses nil
67
  "Simple Emacs Spreadsheet."
68
  :tag "SES"
69 70 71 72 73 74 75 76 77
  :group  'applications
  :prefix "ses-"
  :version "21.1")

(defcustom ses-initial-size '(1 . 1)
  "Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
  :group 'ses
  :type '(cons (integer :tag "numrows") (integer :tag "numcols")))

78
(defcustom ses-initial-column-width 7
79 80 81 82 83 84 85 86 87 88 89 90
  "Initial width of columns in a new spreadsheet."
  :group 'ses
  :type '(integer :match (lambda (widget value) (> value 0))))

(defcustom ses-initial-default-printer "%.7g"
  "Initial default printer for a new spreadsheet."
  :group 'ses
  :type  '(choice string
		  (list :tag "Parenthesized string" string)
		  function))

(defcustom ses-after-entry-functions '(forward-char)
91 92 93
  "Things to do after entering a value into a cell.
An abnormal hook that usually runs a cursor-movement function.
Each function is called with ARG=1."
94 95 96 97 98 99 100 101 102 103
  :group 'ses
  :type 'hook
  :options '(forward-char backward-char next-line previous-line))

(defcustom ses-mode-hook nil
  "Hook functions to be run upon entering SES mode."
  :group 'ses
  :type 'hook)


104 105 106
;;----------------------------------------------------------------------------
;; Global variables and constants
;;----------------------------------------------------------------------------
107 108 109 110 111 112 113

(defvar ses-read-cell-history nil
  "List of formulas that have been typed in.")

(defvar ses-read-printer-history nil
  "List of printer functions that have been typed in.")

114 115 116 117
(easy-menu-define ses-header-line-menu nil
  "Context menu when mouse-3 is used on the header-line in an SES buffer."
  '("SES header row"
    ["Set current row" ses-set-header-row t]
118
    ["Unset row" ses-unset-header-row (> ses--header-row 0)]))
119

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
(defconst ses-mode-map
  (let ((keys `("\C-c\M-\C-l" ses-reconstruct-all
		"\C-c\C-l"    ses-recalculate-all
		"\C-c\C-n"    ses-renarrow-buffer
		"\C-c\C-c"    ses-recalculate-cell
		"\C-c\M-\C-s" ses-sort-column
		"\C-c\M-\C-h" ses-set-header-row
		"\C-c\C-t"    ses-truncate-cell
		"\C-c\C-j"    ses-jump
		"\C-c\C-p"    ses-read-default-printer
		"\M-\C-l"     ses-reprint-all
		[?\S-\C-l]    ses-reprint-all
		[header-line down-mouse-3] ,ses-header-line-menu
		[header-line mouse-2] ses-sort-column-click))
	(newmap (make-sparse-keymap)))
    (while keys
      (define-key (1value newmap) (car keys) (cadr keys))
      (setq keys (cddr keys)))
    newmap)
  "Local keymap for Simple Emacs Spreadsheet.")
140

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
(easy-menu-define ses-menu ses-mode-map
  "Menu bar menu for SES."
  '("SES"
    ["Insert row" ses-insert-row (ses-in-print-area)]
    ["Delete row" ses-delete-row (ses-in-print-area)]
    ["Insert column" ses-insert-column (ses-in-print-area)]
    ["Delete column" ses-delete-column (ses-in-print-area)]
    ["Set column printer" ses-read-column-printer t]
    ["Set column width" ses-set-column-width t]
    ["Set default printer" ses-read-default-printer t]
    ["Jump to cell" ses-jump t]
    ["Set cell printer" ses-read-cell-printer t]
    ["Recalculate cell" ses-recalculate-cell t]
    ["Truncate cell display" ses-truncate-cell t]
    ["Export values" ses-export-tsv t]
    ["Export formulas" ses-export-tsf t]))

(defconst ses-mode-edit-map
  (let ((keys '("\C-c\C-r"    ses-insert-range
		"\C-c\C-s"    ses-insert-ses-range
		[S-mouse-3]   ses-insert-range-click
		[C-S-mouse-3] ses-insert-ses-range-click
		"\M-\C-i"     lisp-complete-symbol))
	(newmap (make-sparse-keymap)))
    (set-keymap-parent newmap minibuffer-local-map)
    (while keys
167
      (define-key newmap (pop keys) (pop keys)))
168
    newmap)
169 170
  "Local keymap for SES minibuffer cell-editing.")

171 172 173 174
;Local keymap for SES print area
(defalias 'ses-mode-print-map
  (let ((keys '([backtab] backward-char
		[tab]     ses-forward-or-insert
175
		"\C-i"	  ses-forward-or-insert  ; Needed for ses-coverage.el?
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
		"\M-o"    ses-insert-column
		"\C-o"	  ses-insert-row
		"\C-m"    ses-edit-cell
		"\M-k"    ses-delete-column
		"\M-y"	  ses-yank-pop
		"\C-k"    ses-delete-row
		"\C-j"    ses-append-row-jump-first-column
		"\M-h"    ses-mark-row
		"\M-H"	  ses-mark-column
		"\C-d"	  ses-clear-cell-forward
		"\C-?"	  ses-clear-cell-backward
		"("       ses-read-cell
		"\""      ses-read-cell
		"'"       ses-read-symbol
		"="	  ses-edit-cell
191
		"c"	  ses-recalculate-cell
192 193
		"j"	  ses-jump
		"p"	  ses-read-cell-printer
194
		"t"	  ses-truncate-cell
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
		"w"	  ses-set-column-width
		"x"	  ses-export-keymap
		"\M-p"	  ses-read-column-printer))
	(repl '(;;We'll replace these wherever they appear in the keymap
		clipboard-kill-region ses-kill-override
		end-of-line	      ses-end-of-line
		kill-line	      ses-delete-row
		kill-region           ses-kill-override
		open-line	      ses-insert-row))
	(numeric "0123456789.-")
	(newmap (make-keymap)))
    ;;Get rid of printables
    (suppress-keymap newmap t)
    ;;These keys insert themselves as the beginning of a numeric value
    (dotimes (x (length numeric))
      (define-key newmap (substring numeric x (1+ x)) 'ses-read-cell))
    ;;Override these global functions wherever they're bound
    (while repl
      (substitute-key-definition (car repl) (cadr repl) newmap
				 (current-global-map))
      (setq repl (cddr repl)))
    ;;Apparently substitute-key-definition doesn't catch this?
    (define-key newmap [(menu-bar) edit cut] 'ses-kill-override)
    ;;Define our other local keys
    (while keys
      (define-key newmap (car keys) (cadr keys))
      (setq keys (cddr keys)))
    newmap))

;;Helptext for ses-mode wants keymap as variable, not function
(defconst ses-mode-print-map (symbol-function 'ses-mode-print-map))

;;Key map used for 'x' key.
228 229 230 231 232 233 234
(defalias 'ses-export-keymap
  (let ((map (make-sparse-keymap "SES export")))
    (define-key map "T" (cons " tab-formulas" 'ses-export-tsf))
    (define-key map "t" (cons " tab-values" 'ses-export-tsv))
    map))

(defconst ses-print-data-boundary "\n\014\n"
235
  "Marker string denoting the boundary between print area and data area.")
236 237 238

(defconst ses-initial-global-parameters
  "\n( ;Global parameters (these are read first)\n 2 ;SES file-format\n 1 ;numrows\n 1 ;numcols\n)\n\n"
239
  "Initial contents for the three-element list at the bottom of the data area.")
240 241

(defconst ses-initial-file-trailer
242
  ";; Local Variables:\n;; mode: ses\n;; End:\n"
243 244 245
  "Initial contents for the file-trailer area at the bottom of the file.")

(defconst ses-initial-file-contents
246
  (concat "       \n" ; One blank cell in print area.
247
	  ses-print-data-boundary
248 249
	  "(ses-cell A1 nil nil nil nil)\n" ; One blank cell in data area.
	  "\n" ; End-of-row terminator for the one row in data area.
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
	  "(ses-column-widths [7])\n"
	  "(ses-column-printers [nil])\n"
	  "(ses-default-printer \"%.7g\")\n"
	  "(ses-header-row 0)\n"
	  ses-initial-global-parameters
	  ses-initial-file-trailer)
  "The initial contents of an empty spreadsheet.")

(defconst ses-box-prop '(:box (:line-width 2 :style released-button))
  "Display properties to create a raised box for cells in the header line.")

(defconst ses-standard-printer-functions
  '(ses-center ses-center-span ses-dashfill ses-dashfill-span
    ses-tildefill-span)
  "List of print functions to be included in initial history of printer
functions.  None of these standard-printer functions is suitable for use as a
column printer or a global-default printer because they invoke the column or
default printer and then modify its output.")

269 270 271 272 273

;;----------------------------------------------------------------------------
;; Local variables and constants
;;----------------------------------------------------------------------------

274
(eval-and-compile
275
  (defconst ses-localvars
276
    '(ses--blank-line ses--cells ses--col-printers
Glenn Morris's avatar
Glenn Morris committed
277
      ses--col-widths ses--curcell ses--curcell-overlay
278
      ses--default-printer
Glenn Morris's avatar
Glenn Morris committed
279 280
      ses--deferred-narrow ses--deferred-recalc
      ses--deferred-write ses--file-format
281
      ses--named-cell-hashmap
282 283 284
      (ses--header-hscroll . -1) ; Flag for "initial recalc needed"
      ses--header-row ses--header-string ses--linewidth
      ses--numcols ses--numrows ses--symbolic-formulas
Glenn Morris's avatar
Glenn Morris committed
285 286
      ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
      ses--Dijkstra-weight-bound
287 288 289
      ;; This list is useful to speed-up clean-up of symbols when
      ;; an area containing renamed cell is deleted.
      ses--renamed-cell-symb-list
290
      ;; Global variables that we override
291
      mode-line-process next-line-add-newlines transient-mark-mode)
Glenn Morris's avatar
Glenn Morris committed
292
    "Buffer-local variables used by SES.")
293

294 295
(defun ses-set-localvars ()
  "Set buffer-local and initialize some SES variables."
296
  (dolist (x ses-localvars)
297 298 299 300
    (cond
     ((symbolp x)
      (set (make-local-variable x) nil))
     ((consp x)
301
      (set (make-local-variable (car x)) (cdr x)))
Glenn Morris's avatar
Glenn Morris committed
302 303 304 305
     (t (error "Unexpected elements `%S' in list `ses-localvars'" x))))))

(eval-when-compile			; silence compiler
  (ses-set-localvars))
306

307
;;; This variable is documented as being permitted in file-locals:
308 309
(put 'ses--symbolic-formulas 'safe-local-variable 'consp)

310 311 312
(defconst ses-paramlines-plist
  '(ses--col-widths  -5 ses--col-printers -4 ses--default-printer -3
    ses--header-row  -2 ses--file-format   1 ses--numrows          2
313
    ses--numcols      3)
314 315 316
  "Offsets from 'Global parameters' line to various parameter lines in the
data area of a spreadsheet.")

317

318 319 320 321 322 323 324
;;
;;  "Side-effect variables".  They are set in one function, altered in
;;  another as a side effect, then read back by the first, as a way of
;;  passing back more than one value.  These declarations are just to make
;;  the compiler happy, and to conform to standard Emacs-Lisp practice (I
;;  think the make-local-variable trick above is cleaner).
;;
325 326 327 328 329 330 331 332 333 334

(defvar ses-relocate-return nil
  "Set by `ses-relocate-formula' and `ses-relocate-range', read by
`ses-relocate-all'.  Set to 'delete if a cell-reference was deleted from a
formula--so the formula needs recalculation.  Set to 'range if the size of a
`ses-range' was changed--so both the formula's value and list of dependents
need to be recalculated.")

(defvar ses-call-printer-return nil
  "Set to t if last cell printer invoked by `ses-call-printer' requested
335
left-justification of the result.  Set to error-signal if `ses-call-printer'
336
encountered an error during printing.  Otherwise nil.")
337 338 339 340 341 342

(defvar ses-start-time nil
  "Time when current operation started.  Used by `ses-time-check' to decide
when to emit a progress message.")


343 344 345
;;----------------------------------------------------------------------------
;; Macros
;;----------------------------------------------------------------------------
346 347 348

(defmacro ses-get-cell (row col)
  "Return the cell structure that stores information about cell (ROW,COL)."
349
  `(aref (aref ses--cells ,row) ,col))
350

351 352
;; We might want to use defstruct here, but cells are explicitly used as
;; arrays in ses-set-cell, so we'd need to fix this first.  --Stef
353 354 355
(defsubst ses-make-cell (&optional symbol formula printer references
				   property-list)
  (vector symbol formula printer references property-list))
356

357 358 359
(defmacro ses-cell-symbol (row &optional col)
  "From a CELL or a pair (ROW,COL), get the symbol that names the local-variable holding its value.  (0,0) => A1."
  `(aref ,(if col `(ses-get-cell ,row ,col) row) 0))
360
(put 'ses-cell-symbol 'safe-function t)
361 362 363 364 365

(defmacro ses-cell-formula (row &optional col)
  "From a CELL or a pair (ROW,COL), get the function that computes its value."
  `(aref ,(if col `(ses-get-cell ,row ,col) row) 1))

366 367 368 369
(defmacro ses-cell-formula-aset (cell formula)
  "From a CELL set the function that computes its value."
  `(aset ,cell 1 ,formula))

370 371 372 373 374 375 376 377 378
(defmacro ses-cell-printer (row &optional col)
  "From a CELL or a pair (ROW,COL), get the function that prints its value."
  `(aref ,(if col `(ses-get-cell ,row ,col) row) 2))

(defmacro ses-cell-references (row &optional col)
  "From a CELL or a pair (ROW,COL), get the list of symbols for cells whose
functions refer to its value."
  `(aref ,(if col `(ses-get-cell ,row ,col) row) 3))

379 380 381 382 383 384 385 386 387 388 389 390 391
(defmacro ses-cell-references-aset (cell references)
  "From a CELL set the list REFERENCES of symbols for cells the
function of which refer to its value."
  `(aset ,cell 3 ,references))

(defun ses-cell-p (cell)
  "Return non `nil' is CELL is a cell of current buffer."
  (and (vectorp cell)
       (= (length cell) 5)
       (eq cell (let ((rowcol (ses-sym-rowcol (ses-cell-symbol cell))))
		  (and (consp rowcol)
		       (ses-get-cell (car rowcol) (cdr rowcol)))))))

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
(defun ses-cell-property-get-fun (property-name cell)
  ;; To speed up property fetching, each time a property is found it is placed
  ;; in the first position.  This way, after the first get, the full property
  ;; list needs to be scanned only when the property does not exist for that
  ;; cell.
  (let* ((plist  (aref cell 4))
	 (ret (plist-member plist property-name)))
    (if ret
	;; Property was found.
	(let ((val (cadr ret)))
	  (if (eq ret plist)
	      ;; Property found is already in the first position, so just return
	      ;; its value.
	      val
	    ;; Property is not in the first position, the following will move it
	    ;; there before returning its value.
	    (let ((next (cddr ret)))
	      (if next
		  (progn
		    (setcdr ret (cdr next))
		    (setcar ret (car next)))
		(setcdr (last plist 1) nil)))
	    (aset cell 4
		  `(,property-name ,val ,@plist))
	    val)))))

(defmacro ses-cell-property-get (property-name row &optional col)
419
   "Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501

When COL is omitted, CELL=ROW is a cell object.  When COL is
present ROW and COL are the integer coordinates of the cell of
interest."
   (declare (debug t))
   `(ses-cell-property-get-fun
     ,property-name
     ,(if col `(ses-get-cell ,row ,col) row)))

(defun ses-cell-property-delq-fun (property-name cell)
  (let	((ret (plist-get (aref cell 4) property-name)))
    (if ret
      (setcdr ret (cddr ret)))))

(defun ses-cell-property-set-fun (property-name property-val cell)
  (let*	((plist  (aref cell 4))
	 (ret (plist-member plist property-name)))
    (if ret
	(setcar (cdr ret) property-val)
      (aset cell 4 `(,property-name ,property-val ,@plist)))))

(defmacro ses-cell-property-set (property-name property-value row &optional col)
   "From a CELL or a pair (ROW,COL), set the property value of
the corresponding cell with name PROPERTY-NAME to PROPERTY-VALUE."
   (if property-value
       `(ses-cell-property-set-fun ,property-name ,property-value
				   ,(if col `(ses-get-cell ,row ,col) row))
       `(ses-cell-property-delq-fun ,property-name
				    ,(if col `(ses-get-cell ,row ,col) row))))

(defun ses-cell-property-pop-fun (property-name cell)
  (let* ((plist  (aref cell 4))
	 (ret (plist-member plist property-name)))
    (if ret
	(prog1 (cadr ret)
	  (let ((next (cddr ret)))
	    (if next
		(progn
		  (setcdr ret (cdr next))
		  (setcar ret (car next)))
	      (if (eq plist ret)
		  (aset cell 4 nil)
		(setcdr (last plist 2) nil))))))))


(defmacro ses-cell-property-pop (property-name row &optional col)
   "From a CELL or a pair (ROW,COL), get and remove the property value of
the corresponding cell with name PROPERTY-NAME."
   `(ses-cell-property-pop-fun  ,property-name
				,(if col `(ses-get-cell ,row ,col) row)))

(defun ses-cell-property-get-handle-fun (property-name cell)
  (let*	((plist  (aref cell 4))
	 (ret (plist-member plist property-name)))
    (if ret
	(if (eq ret plist)
	    (cdr ret)
	  (let ((val (cadr ret))
		(next (cddr ret)))
	    (if next
		(progn
		  (setcdr ret (cdr next))
		  (setcar ret (car next)))
	      (setcdr (last plist 2) nil))
	    (setq ret (cons val plist))
	    (aset cell 4 (cons property-name ret))
	    ret))
      (setq ret (cons nil plist))
      (aset cell 4 (cons property-name ret))
      ret)))

(defmacro ses-cell-property-get-handle (property-name row &optional col)
   "From a CELL or a pair (ROW,COL), get a cons cell whose car is
the property value of the corresponding cell property with name
PROPERTY-NAME."
   `(ses-cell-property-get-handle-fun  ,property-name
				,(if col `(ses-get-cell ,row ,col) row)))


(defalias 'ses-cell-property-handle-car 'car)
(defalias 'ses-cell-property-handle-setcar 'setcar)

502 503 504 505 506 507
(defmacro ses-cell-value (row &optional col)
  "From a CELL or a pair (ROW,COL), get the current value for that cell."
  `(symbol-value (ses-cell-symbol ,row ,col)))

(defmacro ses-col-width (col)
  "Return the width for column COL."
508
  `(aref ses--col-widths ,col))
509 510 511

(defmacro ses-col-printer (col)
  "Return the default printer for column COL."
512
  `(aref ses--col-printers ,col))
513 514

(defmacro ses-sym-rowcol (sym)
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
  "From a cell-symbol SYM, gets the cons (row . col).  A1 => (0 . 0).  Result
is nil if SYM is not a symbol that names a cell."
  `(let ((rc (and (symbolp ,sym) (get ,sym 'ses-cell))))
     (if (eq rc :ses-named)
	 (gethash ,sym ses--named-cell-hashmap)
       rc)))

(defun ses-is-cell-sym-p (sym)
  "Check whether SYM point at a cell of this spread sheet."
  (let ((rowcol (get sym 'ses-cell)))
    (and rowcol
	 (if (eq rowcol :ses-named)
	     (and ses--named-cell-hashmap (gethash sym ses--named-cell-hashmap))
	   (and (< (car rowcol) ses--numrows)
		(< (cdr rowcol) ses--numcols)
		(eq (ses-cell-symbol (car rowcol) (cdr rowcol)) sym))))))
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

(defmacro ses-cell (sym value formula printer references)
  "Load a cell SYM from the spreadsheet file.  Does not recompute VALUE from
FORMULA, does not reprint using PRINTER, does not check REFERENCES.  This is a
macro to prevent propagate-on-load viruses.  Safety-checking for FORMULA and
PRINTER are deferred until first use."
  (let ((rowcol (ses-sym-rowcol sym)))
    (ses-formula-record formula)
    (ses-printer-record printer)
    (or (atom formula)
	(eq safe-functions t)
	(setq formula `(ses-safe-formula ,formula)))
    (or (not printer)
	(stringp printer)
	(eq safe-functions t)
	(setq printer `(ses-safe-printer ,printer)))
547
    (aset (aref ses--cells (car rowcol))
548
	  (cdr rowcol)
549
	  (ses-make-cell sym formula printer references)))
550 551 552 553 554 555
  (set sym value)
  sym)

(defmacro ses-column-widths (widths)
  "Load the vector of column widths from the spreadsheet file.  This is a
macro to prevent propagate-on-load viruses."
556
  (or (and (vectorp widths) (= (length widths) ses--numcols))
557 558 559
      (error "Bad column-width vector"))
  ;;To save time later, we also calculate the total width of each line in the
  ;;print area (excluding the terminating newline)
560 561
  (setq ses--col-widths widths
	ses--linewidth  (apply '+ -1 (mapcar '1+ widths))
562
	ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
563 564 565 566 567
  t)

(defmacro ses-column-printers (printers)
  "Load the vector of column printers from the spreadsheet file and checks
them for safety.  This is a macro to prevent propagate-on-load viruses."
568
  (or (and (vectorp printers) (= (length printers) ses--numcols))
569
      (error "Bad column-printers vector"))
570
  (dotimes (x ses--numcols)
571
    (aset printers x (ses-safe-printer (aref printers x))))
572
  (setq ses--col-printers printers)
573 574 575 576 577 578
  (mapc 'ses-printer-record printers)
  t)

(defmacro ses-default-printer (def)
  "Load the global default printer from the spreadsheet file and checks it
for safety.  This is a macro to prevent propagate-on-load viruses."
579
  (setq ses--default-printer (ses-safe-printer def))
580 581 582 583 584 585
  (ses-printer-record def)
  t)

(defmacro ses-header-row (row)
  "Load the header row from the spreadsheet file and checks it
for safety.  This is a macro to prevent propagate-on-load viruses."
586
  (or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
587
      (error "Bad header-row"))
588
  (setq ses--header-row row)
589 590 591 592 593 594
  t)

(defmacro ses-dorange (curcell &rest body)
  "Execute BODY repeatedly, with the variables `row' and `col' set to each
cell in the range specified by CURCELL.  The range is available in the
variables `minrow', `maxrow', `mincol', and `maxcol'."
595
  (declare (indent defun) (debug (form body)))
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
  (let ((cur (make-symbol "cur"))
	(min (make-symbol "min"))
	(max (make-symbol "max"))
	(r   (make-symbol "r"))
	(c   (make-symbol "c")))
    `(let* ((,cur ,curcell)
	    (,min (ses-sym-rowcol (if (consp ,cur) (car ,cur) ,cur)))
	    (,max (ses-sym-rowcol (if (consp ,cur) (cdr ,cur) ,cur))))
       (let ((minrow (car ,min))
	     (maxrow (car ,max))
	     (mincol (cdr ,min))
	     (maxcol (cdr ,max))
	     row col)
	 (if (or (> minrow maxrow) (> mincol maxcol))
	     (error "Empty range"))
	 (dotimes (,r (- maxrow minrow -1))
	   (setq row (+ ,r minrow))
	   (dotimes (,c (- maxcol mincol -1))
	     (setq col (+ ,c mincol))
	     ,@body))))))

;;Support for coverage testing.
(defmacro 1value (form)
  "For code-coverage testing, indicate that FORM is expected to always have
the same value."
  form)
(defmacro noreturn (form)
  "For code-coverage testing, indicate that FORM will always signal an error."
  form)


627 628 629
;;----------------------------------------------------------------------------
;; Utility functions
;;----------------------------------------------------------------------------
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662

(defun ses-vector-insert (array idx new)
  "Create a new vector which is one larger than ARRAY and has NEW inserted
before element IDX."
  (let* ((len    (length array))
	 (result (make-vector (1+ len) new)))
    (dotimes (x len)
      (aset result
	    (if (< x idx) x (1+ x))
	    (aref array x)))
    result))

;;Allow ARRAY to be a symbol for use in buffer-undo-list
(defun ses-vector-delete (array idx count)
  "Create a new vector which is a copy of ARRAY with COUNT objects removed
starting at element IDX.  ARRAY is either a vector or a symbol whose value
is a vector--if a symbol, the new vector is assigned as the symbol's value."
  (let* ((a      (if (arrayp array) array (symbol-value array)))
	 (len    (- (length a) count))
	 (result (make-vector len nil)))
    (dotimes (x len)
      (aset result x (aref a (if (< x idx) x (+ x count)))))
    (if (symbolp array)
	(set array result))
    result))

(defun ses-delete-line (count)
  "Like `kill-line', but no kill ring."
  (let ((pos (point)))
    (forward-line count)
    (delete-region pos (point))))

(defun ses-printer-validate (printer)
663
  "Signal an error if PRINTER is not a valid SES cell printer."
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
  (or (not printer)
      (stringp printer)
      (functionp printer)
      (and (stringp (car-safe printer)) (not (cdr printer)))
      (error "Invalid printer function"))
  printer)

(defun ses-printer-record (printer)
  "Add PRINTER to `ses-read-printer-history' if not already there, after first
checking that it is a valid printer function."
  (ses-printer-validate printer)
  ;;To speed things up, we avoid calling prin1 for the very common "nil" case.
  (if printer
      (add-to-list 'ses-read-printer-history (prin1-to-string printer))))

(defun ses-formula-record (formula)
680
  "If FORMULA is of the form 'symbol, add it to the list of symbolic formulas
681 682 683
for this spreadsheet."
  (when (and (eq (car-safe formula) 'quote)
	     (symbolp (cadr formula)))
684
    (add-to-list 'ses--symbolic-formulas
685 686 687
		 (list (symbol-name (cadr formula))))))

(defun ses-column-letter (col)
688 689 690 691
  "Return the alphabetic name of column number COL.
0-25 become A-Z; 26-701 become AA-ZZ, and so on."
  (let ((units (char-to-string (+ ?A (% col 26)))))
    (if (< col 26)
692
	units
693
      (concat (ses-column-letter (1- (/ col 26))) units))))
694 695 696 697 698

(defun ses-create-cell-symbol (row col)
  "Produce a symbol that names the cell (ROW,COL).  (0,0) => 'A1."
  (intern (concat (ses-column-letter col) (number-to-string (1+ row)))))

699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
(defun ses-decode-cell-symbol (str)
  "Decode a symbol \"A1\" => (0,0). Returns `nil' if STR is not a
  canonical cell name. Does not save match data."
  (let (case-fold-search)
    (and (string-match "\\`\\([A-Z]+\\)\\([0-9]+\\)\\'" str)
	 (let* ((col-str (match-string-no-properties 1 str))
	       (col 0)
	       (col-base 1)
	       (col-idx (1- (length col-str)))
	       (row (1- (string-to-number (match-string-no-properties 2 str)))))
	   (and (>= row 0)
		(progn
		  (while
		      (progn
			(setq col (+ col (* (- (aref col-str col-idx) ?A) col-base))
			      col-base (* col-base 26)
			      col-idx (1- col-idx))
			(and (>= col-idx 0)
			     (setq col (+ col col-base)))))
		  (cons row col)))))))

720 721
(defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
  "Create buffer-local variables for cells.  This is undoable."
722
  (push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
723 724 725 726 727 728 729 730 731 732
	buffer-undo-list)
  (let (sym xrow xcol)
    (dotimes (row (1+ (- maxrow minrow)))
      (dotimes (col (1+ (- maxcol mincol)))
	(setq xrow (+ row minrow)
	      xcol (+ col mincol)
	      sym  (ses-create-cell-symbol xrow xcol))
	(put sym 'ses-cell (cons xrow xcol))
	(make-local-variable sym)))))

733 734 735 736 737 738 739 740 741
(defun ses-create-cell-variable (sym row col)
  "Create a buffer-local variable `SYM' for cell at position (ROW, COL).

SYM is the symbol for that variable, ROW and COL are integers for
row and column of the cell, with numbering starting from 0.

Return nil in case of failure."
  (unless (local-variable-p sym)
    (make-local-variable  sym)
742
    (if (let (case-fold-search) (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name sym)))
743 744 745 746
	(put sym 'ses-cell (cons row col))
      (put sym 'ses-cell :ses-named)
      (setq ses--named-cell-hashmap (or ses--named-cell-hashmap (make-hash-table :test 'eq)))
      (puthash sym (cons row col) ses--named-cell-hashmap))))
747

748 749 750
;; We do not delete the ses-cell properties for the cell-variables, in
;; case a formula that refers to this cell is in the kill-ring and is
;; later pasted back in.
751 752 753 754 755
(defun ses-destroy-cell-variable-range (minrow maxrow mincol maxcol)
  "Destroy buffer-local variables for cells.  This is undoable."
  (let (sym)
    (dotimes (row (1+ (- maxrow minrow)))
      (dotimes (col (1+ (- maxcol mincol)))
756 757 758 759
	(let ((xrow  (+ row minrow)) (xcol (+ col mincol)))
	  (setq sym (if (and (< xrow ses--numrows) (< xcol ses--numcols))
			(ses-cell-symbol xrow xcol)
			(ses-create-cell-symbol xrow xcol))))
760
	(if (boundp sym)
761
	    (push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
762 763
		  buffer-undo-list))
	(kill-local-variable sym))))
764
  (push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
765 766 767
	buffer-undo-list))

(defun ses-reset-header-string ()
768
  "Flag the header string for update.  Upon undo, the header string will be
769
updated again."
770
  (push '(apply ses-reset-header-string) buffer-undo-list)
771
  (setq ses--header-hscroll -1))
772 773 774 775 776 777 778 779 780 781 782

;;Split this code off into a function to avoid coverage-testing difficulties
(defun ses-time-check (format arg)
  "If `ses-start-time' is more than a second ago, call `message' with FORMAT
and (eval ARG) and reset `ses-start-time' to the current time."
  (when (> (- (float-time) ses-start-time) 1.0)
    (message format (eval arg))
    (setq ses-start-time (float-time)))
  nil)


783 784 785
;;----------------------------------------------------------------------------
;; The cells
;;----------------------------------------------------------------------------
786 787 788 789 790 791 792 793 794 795 796 797 798 799

(defun ses-set-cell (row col field val)
  "Install VAL as the contents for field FIELD (named by a quoted symbol) of
cell (ROW,COL).  This is undoable.  The cell's data will be updated through
`post-command-hook'."
  (let ((cell (ses-get-cell row col))
	(elt  (plist-get '(value t symbol 0 formula 1 printer 2 references 3)
			 field))
	change)
    (or elt (signal 'args-out-of-range nil))
    (setq change (if (eq elt t)
		     (ses-set-with-undo (ses-cell-symbol cell) val)
		   (ses-aset-with-undo cell elt val)))
    (if change
800
	(add-to-list 'ses--deferred-write (cons row col))))
801
  nil) ; Make coverage-tester happy.
802 803

(defun ses-cell-set-formula (row col formula)
804
  "Store a new formula for (ROW . COL) and enqueue the cell for
805 806 807 808 809 810 811 812 813 814 815
recalculation via `post-command-hook'.  Updates the reference lists for the
cells that this cell refers to.  Does not update cell value or reprint the
cell.  To avoid inconsistencies, this function is not interruptible, which
means Emacs will crash if FORMULA contains a circular list."
  (let* ((cell (ses-get-cell row col))
	 (old  (ses-cell-formula cell)))
    (let ((sym    (ses-cell-symbol cell))
	  (oldref (ses-formula-references old))
	  (newref (ses-formula-references formula))
	  (inhibit-quit t)
	  x xrow xcol)
816
      (add-to-list 'ses--deferred-recalc sym)
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
      ;;Delete old references from this cell.  Skip the ones that are also
      ;;in the new list.
      (dolist (ref oldref)
	(unless (memq ref newref)
	  (setq x    (ses-sym-rowcol ref)
		xrow (car x)
		xcol (cdr x))
	  (ses-set-cell xrow xcol 'references
			(delq sym (ses-cell-references xrow xcol)))))
      ;;Add new ones.  Skip ones left over from old list
      (dolist (ref newref)
	(setq x    (ses-sym-rowcol ref)
	      xrow (car x)
	      xcol (cdr x)
	      x    (ses-cell-references xrow xcol))
	(or (memq sym x)
	    (ses-set-cell xrow xcol 'references (cons sym x))))
      (ses-formula-record formula)
      (ses-set-cell row col 'formula formula))))

837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888

(defun ses-repair-cell-reference-all ()
  "Repair cell reference and warn if there was some reference corruption."
  (interactive "*")
  (let (errors)
    ;; Step 1, reset  :ses-repair-reference cell property in the whole sheet.
    (dotimes (row ses--numrows)
      (dotimes (col ses--numcols)
	(let ((references  (ses-cell-property-pop :ses-repair-reference
						  row col)))
	(when references
	  (push (list
		 (ses-cell-symbol row col)
		 :corrupt-property
		 references) errors)))))

    ;; Step 2, build new.
    (dotimes (row ses--numrows)
      (dotimes (col ses--numcols)
	(let* ((cell (ses-get-cell row col))
	       (sym (ses-cell-symbol cell))
	       (formula (ses-cell-formula cell))
	       (new-ref (ses-formula-references formula)))
	  (dolist (ref new-ref)
	    (let* ((rowcol (ses-sym-rowcol ref))
		  (h (ses-cell-property-get-handle :ses-repair-reference
						  (car rowcol) (cdr rowcol))))
	      (unless (memq ref (ses-cell-property-handle-car h))
		(ses-cell-property-handle-setcar
		 h
		 (cons sym
		       (ses-cell-property-handle-car h)))))))))

    ;; Step 3, overwrite with check.
    (dotimes (row ses--numrows)
      (dotimes (col ses--numcols)
	(let* ((cell (ses-get-cell row col))
	       (irrelevant (ses-cell-references cell))
	       (new-ref (ses-cell-property-pop  :ses-repair-reference cell))
	       missing)
	  (dolist (ref new-ref)
	    (if (memq ref irrelevant)
		(setq irrelevant (delq ref irrelevant))
	      (push ref missing)))
	  (ses-set-cell row col 'references new-ref)
	  (when (or missing irrelevant)
	    (push `( ,(ses-cell-symbol cell)
		     ,@(and missing (list :missing missing))
		     ,@(and irrelevant  (list :irrelevant irrelevant)))
		  errors)))))
    (if errors
      (warn "----------------------------------------------------------------
889
Some references were corrupted.
890

891
The following is a list where each element ELT is such
892 893 894 895 896 897 898 899 900 901 902 903 904 905
that (car ELT) is the reference of cell CELL with corruption,
and (cdr ELT) is a property list where

* property `:corrupt-property' means that
  property `:ses-repair-reference' of cell CELL was initially non
  nil,

* property `:missing' is a list of missing references

* property `:irrelevant' is a list of non needed references

%S" errors)
      (message "No reference corruption found"))))

906 907 908 909 910 911 912 913 914
(defun ses-calculate-cell (row col force)
  "Calculate and print the value for cell (ROW,COL) using the cell's formula
function and print functions, if any.  Result is nil for normal operation, or
the error signal if the formula or print function failed.  The old value is
left unchanged if it was *skip* and the new value is nil.
  Any cells that depend on this cell are queued for update after the end of
processing for the current keystroke, unless the new value is the same as
the old and FORCE is nil."
  (let ((cell (ses-get-cell row col))
915
	cycle-error formula-error printer-error)
916
    (let ((oldval  (ses-cell-value   cell))
917
	  (formula (ses-cell-formula cell))
918 919 920 921 922 923 924
	  newval
	  this-cell-Dijkstra-attempt-h
	  this-cell-Dijkstra-attempt
	  this-cell-Dijkstra-attempt+1
	  ref-cell-Dijkstra-attempt-h
	  ref-cell-Dijkstra-attempt
	  ref-rowcol)
925 926 927
      (when (eq (car-safe formula) 'ses-safe-formula)
	(setq formula (ses-safe-formula (cadr formula)))
	(ses-set-cell row col 'formula formula))
928 929 930
      (condition-case sig
	  (setq newval (eval formula))
	(error
931 932
	 ;; Variable `sig' can't be nil.
	 (nconc sig (list (ses-cell-symbol cell)))
933 934 935
	 (setq formula-error sig
	       newval        '*error*)))
      (if (and (not newval) (eq oldval '*skip*))
936
	  ;; Don't lose the *skip* --- previous field spans this one.
937
	  (setq newval '*skip*))
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
      (catch 'cycle
	(when (or force (not (eq newval oldval)))
	  (add-to-list 'ses--deferred-write (cons row col)) ; In case force=t.
	  (setq this-cell-Dijkstra-attempt-h
		(ses-cell-property-get-handle :ses-Dijkstra-attempt cell);
		this-cell-Dijkstra-attempt
		(ses-cell-property-handle-car this-cell-Dijkstra-attempt-h))
	  (if (null this-cell-Dijkstra-attempt)
	      (ses-cell-property-handle-setcar
	       this-cell-Dijkstra-attempt-h
	       (setq this-cell-Dijkstra-attempt
		     (cons ses--Dijkstra-attempt-nb 0)))
	    (unless (= ses--Dijkstra-attempt-nb
		       (car this-cell-Dijkstra-attempt))
		(setcar this-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
		(setcdr this-cell-Dijkstra-attempt 0)))
	  (setq this-cell-Dijkstra-attempt+1
		(1+ (cdr this-cell-Dijkstra-attempt)))
	  (ses-set-cell row col 'value newval)
	  (dolist (ref (ses-cell-references cell))
	    (add-to-list 'ses--deferred-recalc ref)
	    (setq ref-rowcol (ses-sym-rowcol ref)
		  ref-cell-Dijkstra-attempt-h
		  (ses-cell-property-get-handle
		   :ses-Dijkstra-attempt
		   (car ref-rowcol) (cdr ref-rowcol))
		  ref-cell-Dijkstra-attempt
		  (ses-cell-property-handle-car ref-cell-Dijkstra-attempt-h))

	    (if (null ref-cell-Dijkstra-attempt)
	      (ses-cell-property-handle-setcar
	       ref-cell-Dijkstra-attempt-h
	       (setq ref-cell-Dijkstra-attempt
		      (cons ses--Dijkstra-attempt-nb
			    this-cell-Dijkstra-attempt+1)))
	      (if (= (car ref-cell-Dijkstra-attempt) ses--Dijkstra-attempt-nb)
		  (setcdr ref-cell-Dijkstra-attempt
			  (max (cdr ref-cell-Dijkstra-attempt)
			       this-cell-Dijkstra-attempt+1))
		(setcar ref-cell-Dijkstra-attempt ses--Dijkstra-attempt-nb)
		(setcdr ref-cell-Dijkstra-attempt
			this-cell-Dijkstra-attempt+1)))

	    (when (> this-cell-Dijkstra-attempt+1 ses--Dijkstra-weight-bound)
	      ;; Update print of this cell.
	      (throw 'cycle (setq formula-error
				  `(error ,(format "Found cycle on cells %S"
						   (ses-cell-symbol cell)))
				  cycle-error formula-error)))))))
987
    (setq printer-error (ses-print-cell row col))
988 989 990 991
    (or
     (and cycle-error
	  (error (error-message-string cycle-error)))
     formula-error printer-error)))
992 993 994 995 996 997

(defun ses-clear-cell (row col)
  "Delete formula and printer for cell (ROW,COL)."
  (ses-set-cell row col 'printer nil)
  (ses-cell-set-formula row col nil))

998
(defcustom ses-self-reference-early-detection nil
999
  "True if cycle detection is early for cells that refer to themselves."
1000
  :version "24.1"
1001 1002 1003
  :type 'boolean
  :group 'ses)

1004 1005 1006
(defun ses-update-cells (list &optional force)
  "Recalculate cells in LIST, checking for dependency loops.  Prints
progress messages every second.  Dependent cells are not recalculated
1007
if the cell's value is unchanged and FORCE is nil."
1008 1009 1010
  (let ((ses--deferred-recalc list)
	(nextlist             list)
	(pos		      (point))
1011
	curlist prevlist this-sym this-rowcol formula)
1012
    (with-temp-message " "
1013 1014 1015 1016 1017
      (while ses--deferred-recalc
	;; In each loop, recalculate cells that refer only to other cells that
	;; have already been recalculated or aren't in the recalculation region.
	;; Repeat until all cells have been processed or until the set of cells
	;; being worked on stops changing.
1018 1019
	(if prevlist
	    (message "Recalculating... (%d cells left)"
1020 1021 1022 1023
		     (length ses--deferred-recalc)))
	(setq curlist              ses--deferred-recalc
	      ses--deferred-recalc nil
	      prevlist             nextlist)
1024
	(while curlist
1025 1026 1027 1028 1029 1030
	  ;; this-sym has to be popped from curlist *BEFORE* the check, and not
	  ;; after because of the case of cells referring to themselves.
	  (setq this-sym   (pop curlist)
		this-rowcol (ses-sym-rowcol this-sym)
		formula     (ses-cell-formula (car this-rowcol)
					      (cdr this-rowcol)))
1031 1032
	  (or (catch 'ref
		(dolist (ref (ses-formula-references formula))
1033 1034 1035 1036 1037 1038 1039 1040 1041
		  (if (and ses-self-reference-early-detection (eq ref this-sym))
		      (error "Cycle found: cell %S is self-referring" this-sym)
		    (when (or (memq ref curlist)
			      (memq ref ses--deferred-recalc))
		      ;; This cell refers to another that isn't done yet
		      (add-to-list 'ses--deferred-recalc this-sym)
		      (throw 'ref t)))))
	      ;; ses-update-cells is called from post-command-hook, so
	      ;; inhibit-quit is implicitly bound to t.
1042
	      (when quit-flag
1043
		;; Abort the recalculation.  User will probably undo now.
1044
		(error "Quit"))
1045
	      (ses-calculate-cell (car this-rowcol) (cdr this-rowcol) force)))
1046
	(dolist (ref ses--deferred-recalc)
1047
	  (add-to-list 'nextlist ref)))
1048
      (when ses--deferred-recalc
1049
	;; Just couldn't finish these.
1050
	(dolist (x ses--deferred-recalc)
1051 1052 1053
	  (let ((this-rowcol (ses-sym-rowcol x)))
	    (ses-set-cell (car this-rowcol) (cdr this-rowcol) 'value '*error*)
	    (1value (ses-print-cell (car this-rowcol) (cdr this-rowcol)))))
1054
	(error "Circular references: %s" ses--deferred-recalc))
1055
      (message " "))
1056
    ;; Can't use save-excursion here: if the cell under point is updated,
1057
    ;; save-excursion's marker will move past the cell.
1058 1059 1060
    (goto-char pos)))


1061 1062 1063
;;----------------------------------------------------------------------------
;; The print area
;;----------------------------------------------------------------------------
1064

1065
(defun ses-in-print-area ()
1066
  "Return t if point is in print area of spreadsheet."
1067
  (<= (point) ses--data-marker))
1068

1069 1070 1071
;; We turn off point-motion-hooks and explicitly position the cursor, in case
;; the intangible properties have gotten screwed up (e.g., when ses-goto-print
;; is called during a recursive ses-print-cell).
1072 1073
(defun ses-goto-print (row col)
  "Move point to print area for cell (ROW,COL)."
1074 1075
  (let ((inhibit-point-motion-hooks t)
	(n 0))
1076
    (goto-char (point-min))
1077
    (forward-line row)
1078
    ;; Calculate column position.
1079
    (dotimes (c col)
1080
      (setq n (+ n (ses-col-width c) 1)))
1081
    ;; Move to the position.
1082 1083
    (and (> n (move-to-column n))
	 (eolp)
1084
	 ;; Move point to the bol of next line (for TAB at the last cell).
1085
	 (forward-char))))
1086 1087

(defun ses-set-curcell ()
1088
  "Set `ses--curcell' to the current cell symbol, or a cons (BEG,END) for a
1089 1090 1091 1092
region, or nil if cursor is not at a cell."
  (if (or (not mark-active)
	  deactivate-mark
	  (= (region-beginning) (region-end)))
1093
      ;; Single cell.
1094
      (setq ses--curcell (get-text-property (point) 'intangible))
1095
    ;; Range.
1096 1097
    (let ((bcell (get-text-property (region-beginning) 'intangible))
	  (ecell (get-text-property (1- (region-end))  'intangible)))
1098
      (when (= (region-end) ses--data-marker)
1099
	;; Correct for overflow.
1100
	(setq ecell (get-text-property (- (region-end) 2)  'intangible)))
1101 1102 1103
      (setq ses--curcell (if (and bcell ecell)
			     (cons bcell ecell)
			   nil))))
1104 1105 1106
  nil)

(defun ses-check-curcell (&rest args)
1107 1108 1109 1110
  "Signal an error if `ses--curcell' is inappropriate.
The end marker is appropriate if some argument is 'end.
A range is appropriate if some argument is 'range.
A single cell is appropriate unless some argument is 'needrange."
1111
  (if (eq ses--curcell t)
1112
      ;; curcell recalculation was postponed, but user typed ahead.
1113 1114
      (ses-set-curcell))
  (cond
1115
   ((not ses--curcell)
1116 1117
    (or (memq 'end args)
	(error "Not at cell")))
1118
   ((consp ses--curcell)
1119 1120 1121 1122 1123 1124 1125
    (or (memq 'range args)
	(memq 'needrange args)
	(error "Can't use a range")))
   ((memq 'needrange args)
    (error "Need a range"))))

(defun ses-print-cell (row col)
1126 1127 1128 1129 1130
  "Format and print the value of cell (ROW,COL) to the print area.
Use the cell's printer function.  If the cell's new print form is too wide,
it will spill over into the following cell, but will not run off the end of the
row or overwrite the next non-nil field.  Result is nil for normal operation,
or the error signal if the printer function failed and the cell was formatted
1131 1132 1133 1134 1135 1136 1137 1138
with \"%s\".  If the cell's value is *skip*, nothing is printed because the
preceding cell has spilled over."
  (catch 'ses-print-cell
    (let* ((cell    (ses-get-cell row col))
	   (value   (ses-cell-value cell))
	   (printer (ses-cell-printer cell))
	   (maxcol  (1+ col))
	   text sig startpos x)
1139
      ;; Create the string to print.
1140 1141
      (cond
       ((eq value '*skip*)
1142
	;; Don't print anything.
1143 1144 1145 1146
	(throw 'ses-print-cell nil))
       ((eq value '*error*)
	(setq text (make-string (ses-col-width col) ?#)))
       (t
1147
	;; Deferred safety-check on printer.
1148 1149 1150
	(if (eq (car-safe printer) 'ses-safe-printer)
	    (ses-set-cell row col 'printer
			  (setq printer (ses-safe-printer (cadr printer)))))
1151
	;; Print the value.
1152 1153
	(setq text (ses-call-printer (or printer
					 (ses-col-printer col)
1154
					 ses--default-printer)
1155 1156
				     value))
	(if (consp ses-call-printer-return)
1157
	    ;; Printer returned an error.