mirrored from git://git.sv.gnu.org/emacs.git
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathses.el
4160 lines (3845 loc) · 159 KB
/
ses.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
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
419
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
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
627
628
629
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; ses.el --- Simple Emacs Spreadsheet -*- lexical-binding:t -*-
;; Copyright (C) 2002-2025 Free Software Foundation, Inc.
;; Author: Jonathan Yavner <jyavner@member.fsf.org>
;; Maintainer: Vincent Belaïche <vincentb1@users.sourceforge.net>
;; Keywords: spreadsheet Dijkstra
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; 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
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;; To-do list:
;; * M-w should deactivate the mark.
;; * offer some way to use absolute cell addressing.
;; * Maybe some way to copy a reference to a cell's formula rather than the
;; formula itself.
;; * split (catch 'cycle ...) call back into one or more functions
;; * Use $ or … for truncated fields
;; * M-t to transpose 2 columns.
;; * M-d should kill the cell under point.
;; * C-t to transpose 2 rows.
;; * C-k and M-k should be ses-kill-row and ses-kill-column.
;; * C-o should insert the row below point rather than above?
;; * rows inserted with C-o should inherit formulas from surrounding rows.
;; * 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.
;; * Do something about control characters & octal codes in cell print
;; areas. Use string-width?
;; * 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.
;;; 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.
;;
;; The current algorithm is based on Dijkstra's algorithm. The cycle length is
;; 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.
;;; Code:
(require 'unsafep)
(require 'macroexp)
(eval-when-compile (require 'cl-lib))
;; Autoloaded, but we have not loaded cl-loaddefs yet.
(declare-function cl-member "cl-seq" (cl-item cl-list &rest cl-keys))
;;----------------------------------------------------------------------------
;; User-customizable variables
;;----------------------------------------------------------------------------
(defgroup ses nil
"Simple Emacs Spreadsheet."
:tag "SES"
:group 'applications
:link '(custom-manual "(ses) Top")
:prefix "ses-"
:version "21.1")
(defcustom ses-initial-size '(1 . 1)
"Initial size of a new spreadsheet, as a cons (NUMROWS . NUMCOLS)."
:type '(cons (integer :tag "numrows") (integer :tag "numcols")))
(defcustom ses-initial-column-width 7
"Initial width of columns in a new spreadsheet."
:type '(integer :match (lambda (widget value) (> value 0))))
(defcustom ses-initial-default-printer "%.7g"
"Initial default printer for a new spreadsheet."
:type '(choice string
(list :tag "Parenthesized string" string)
function))
(defcustom ses-after-entry-functions '(forward-char)
"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."
: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."
:type 'hook)
(defcustom ses-jump-cell-name-function #'upcase
"Function to process the string passed to function `ses-jump'.
Set it to `identity' to make no change.
Set it to `upcase' to make cell name change case isensitive.
May return
* a string, in this case this must be a cell name.
* a (row . col) cons cell, in this case that must be valid cell coordinates."
:type 'function)
(defcustom ses-jump-prefix-function #'ses-jump-prefix
"Function that takes the prefix argument passed to function `ses-jump'.
It may return the same sort of thing as `ses-jump-cell-name-function'."
:type 'function)
;;----------------------------------------------------------------------------
;; Global variables and constants
;;----------------------------------------------------------------------------
(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.")
(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]
["Unset row" ses-unset-header-row (> ses--header-row 0)]))
(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.")
(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-completion-keys '("\M-\C-i" "\C-i")
"List for keys that can be used for completion while editing.")
(defvar ses--completion-table nil
"Set globally to what completion table to use depending on type
of completion (local printers, cells, etc.). We need to go
through a local variable to pass the SES buffer local variable
to completing function while the current buffer is the
minibuffer.")
(defvar ses--list-orig-buffer nil
"Calling buffer for SES listing help.
Used for listing local printers or renamed cells.")
(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
"\C-h\C-p" ses-list-local-printers
"\C-h\C-n" ses-list-named-cells
"\M-\C-i" completion-at-point))
(newmap (make-sparse-keymap)))
(set-keymap-parent newmap minibuffer-local-map)
(while keys
(define-key newmap (pop keys) (pop keys)))
newmap)
"Local keymap for SES minibuffer cell-editing.")
;Local keymap for SES print area
(defalias 'ses-mode-print-map
(let ((keys '([backtab] backward-char
[tab] ses-forward-or-insert
"\C-i" ses-forward-or-insert ; Needed for ses-coverage.el?
"\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
"c" ses-recalculate-cell
"j" ses-jump
"p" ses-read-cell-printer
"t" ses-truncate-cell
"w" ses-set-column-width
"x" ses-export-keymap
"\M-p" ses-read-column-printer))
(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))
(define-key newmap [remap clipboard-kill-region] #'ses-kill-override)
(define-key newmap [remap end-of-line] #'ses-end-of-line)
(define-key newmap [remap kill-line] #'ses-delete-row)
(define-key newmap [remap kill-region] #'ses-kill-override)
(define-key newmap [remap open-line] #'ses-insert-row)
;;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.
(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"
"Marker string denoting the boundary between print area and data area.")
(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"
"Initial contents for the three-element list at the bottom of the data area.")
(defconst ses-initial-global-parameters-re
"\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"
"Match Global parameters for .")
(defconst ses-initial-file-trailer
";; Local Variables:\n;; mode: ses\n;; End:\n"
"Initial contents for the file-trailer area at the bottom of the file.")
(defconst ses-initial-file-contents
(concat " \n" ; One blank cell in print area.
ses-print-data-boundary
"(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.
"(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
ses-prin1)
"List of print functions to be included in initial history of printer functions.
None of these standard-printer functions, except function
`ses-prin1', 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.")
;;----------------------------------------------------------------------------
;; Local variables and constants
;;----------------------------------------------------------------------------
(eval-and-compile
(defconst ses-localvars
'(ses--blank-line ses--cells ses--col-printers
ses--col-widths ses--curcell ses--curcell-overlay
ses--default-printer
(ses--local-printer-hashmap . :hashmap)
(ses--numlocprn . 0); count of local printers
ses--deferred-narrow ses--deferred-recalc
ses--deferred-write ses--file-format
ses--named-cell-hashmap
(ses--header-hscroll . -1) ; Flag for "initial recalc needed"
ses--header-row ses--header-string ses--linewidth
ses--numcols ses--numrows ses--symbolic-formulas
ses--data-marker ses--params-marker (ses--Dijkstra-attempt-nb . 0)
ses--Dijkstra-weight-bound
;; This list is useful for clean-up of symbols when an area
;; containing renamed cell is deleted.
ses--in-killing-named-cell-list
;; Global variables that we override
next-line-add-newlines transient-mark-mode)
"Buffer-local variables used by SES."))
(defmacro ses--\,@ (exp) (declare (debug t)) (macroexp-progn (eval exp t)))
(ses--\,@
(mapcar (lambda (x) `(defvar ,(or (car-safe x) x))) ses-localvars))
(defun ses-set-localvars ()
"Set buffer-local and initialize some SES variables."
(dolist (x ses-localvars)
(cond
((symbolp x)
(set (make-local-variable x) nil))
((consp x)
(cond
((integerp (cdr x))
(set (make-local-variable (car x)) (cdr x)))
((eq (cdr x) :hashmap)
(set (make-local-variable (car x)) (make-hash-table :test 'eq)))
(t (error "Unexpected initializer `%S' in list `ses-localvars' for entry %S"
(cdr x) (car x)) ) ))
(t (error "Unexpected elements `%S' in list `ses-localvars'" x)))))
;;; This variable is documented as being permitted in file-locals:
(put 'ses--symbolic-formulas 'safe-local-variable #'consp)
(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
ses--numcols 3 ses--numlocprn 4)
"Offsets from \"Global parameters\" line to various parameter lines in the
data area of a spreadsheet.")
(defconst ses-paramfmt-plist
'(ses--col-widths "(ses-column-widths %S)"
ses--col-printers "(ses-column-printers %S)"
ses--default-printer "(ses-default-printer %S)"
ses--header-row "(ses-header-row %S)"
ses--file-format " %S ;SES file-format"
ses--numrows " %S ;numrows"
ses--numcols " %S ;numcols"
ses--numlocprn " %S ;numlocprn")
"Formats of \"Global parameters\" various parameters in the data
area of a spreadsheet.")
;;
;; "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).
;;
(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
left-justification of the result. Set to error-signal if `ses-call-printer'
encountered an error during printing. Otherwise nil.")
(defvar ses-start-time nil
"Time when current operation started.
Used by `ses--time-check' to decide when to emit a progress
message.")
;;----------------------------------------------------------------------------
;; Macros
;;----------------------------------------------------------------------------
(defmacro ses-get-cell (row col)
"Return the cell structure that stores information about cell (ROW,COL)."
(declare (debug t))
`(aref (aref ses--cells ,row) ,col))
(cl-defstruct (ses-cell
(:constructor nil)
(:constructor ses-make-cell
(&optional symbol formula printer references))
(:copier nil)
;; This is treated as an 4-elem array in various places.
;; Mostly in ses-set-cell.
(:type vector) ;Not named.
(:conc-name ses-cell--))
symbol formula printer references properties)
(cl-defstruct (ses--locprn
(:constructor)
(:constructor ses-make-local-printer-info
(def &optional (compiled (ses-local-printer-compile def))
(number ses--numlocprn))))
def
compiled
number
local-printer-list)
(defmacro ses-cell-symbol (row &optional col)
"Return symbol of the local-variable holding value of CELL or pair (ROW,COL).
For example, (0,0) => A1."
(declare (debug t))
`(ses-cell--symbol ,(if col `(ses-get-cell ,row ,col) row)))
(put 'ses-cell-symbol 'safe-function t)
(defmacro ses-cell-formula (row &optional col)
"From a CELL or a pair (ROW,COL), get the function that computes its value."
(declare (debug t))
`(ses-cell--formula ,(if col `(ses-get-cell ,row ,col) row)))
(defmacro ses-cell-printer (row &optional col)
"From a CELL or a pair (ROW,COL), get the function that prints its value."
(declare (debug t))
`(ses-cell--printer ,(if col `(ses-get-cell ,row ,col) row)))
(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."
(declare (debug t))
`(ses-cell--references ,(if col `(ses-get-cell ,row ,col) row)))
(defmacro ses-sym-rowcol (sym)
"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."
(declare (debug t))
`(let ((rc (and (symbolp ,sym) (get ,sym 'ses-cell))))
(if (eq rc :ses-named)
(and ses--named-cell-hashmap (gethash ,sym ses--named-cell-hashmap))
rc)))
(defun ses-cell-p (cell)
"Return non-nil if 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)))))))
(defun ses-plist-delq (plist prop)
"Return PLIST after deleting the first pair (if any) with symbol PROP.
This can alter PLIST."
(cond
((null plist) nil)
((eq (car plist) prop) (cddr plist))
(t (let* ((plist-1 (cdr plist))
(plist-2 (cdr plist-1)))
(setcdr plist-1 (ses-plist-delq plist-2 prop))
plist))))
(defvar ses--ses-buffer-list nil "A list of buffers containing a SES spreadsheet.")
(defun ses--unbind-cell-name (name)
"Make NAME non longer a renamed cell name."
(remhash name ses--named-cell-hashmap)
(kill-local-variable name)
;; remove symbol property 'ses-cell from symbol NAME, unless this
;; symbol is also a renamed cell name in another SES buffer.
(let (used-elsewhere (buffer-list ses--ses-buffer-list) buf)
(while buffer-list
(setq buf (pop buffer-list))
(cond
((eq buf (current-buffer)))
;; This case should not happen, some SES buffer has been
;; killed without the ses-killbuffer-hook being called.
((null (buffer-live-p buf))
;; Silently repair ses--ses-buffer-list
(setq ses--ses-buffer-list (delq buf ses--ses-buffer-list)))
(t
(with-current-buffer buf
(when (gethash name ses--named-cell-hashmap)
(setq used-elsewhere t
buffer-list nil))))))
(unless used-elsewhere
(setplist name (ses-plist-delq (symbol-plist name) 'ses-cell))) ))
(defmacro ses--letref (vars place &rest body)
(declare (indent 2) (debug (sexp form body)))
(gv-letplace (getter setter) place
`(cl-macrolet ((,(nth 0 vars) () ',getter)
(,(nth 1 vars) (v) (funcall ',setter v)))
,@body)))
(defmacro ses-cell-property (property-name row &optional col)
"Get property named PROPERTY-NAME from a CELL or a pair (ROW,COL).
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))
`(alist-get ,property-name
(ses-cell--properties
,(if col `(ses-get-cell ,row ,col) row))))
(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--letref (pget pset)
(alist-get ,property-name
(ses-cell--properties
,(if col `(ses-get-cell ,row ,col) row))
nil t)
(prog1 (pget) (pset nil))))
(defmacro ses-cell-value (row &optional col)
"From a CELL or a pair (ROW,COL), get the current value for that cell."
(declare (debug t))
`(symbol-value (ses-cell-symbol ,row ,col)))
(defmacro ses-col-width (col)
"Return the width for column COL."
(declare (debug t))
`(aref ses--col-widths ,col))
(defmacro ses-col-printer (col)
"Return the default printer for column COL."
(declare (debug t))
`(aref ses--col-printers ,col))
(defun ses-is-cell-sym-p (sym)
"Check whether SYM point at a cell of this spread sheet."
(and (symbolp sym)
(local-variable-p sym)
(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)))))))
(defun 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. 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)
(unless (or formula (eq value '*skip*))
(setq formula (macroexp-quote value)))
(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)))
(setf (ses-get-cell (car rowcol) (cdr rowcol))
(ses-make-cell sym formula printer references)))
(set sym value))
(defun ses-local-printer-compile (printer)
"Convert local printer function into faster printer definition."
(cond
((functionp printer) printer)
((stringp printer)
`(lambda (x)
(if (null x) ""
(format ,printer x))))
((stringp (car-safe printer))
`(lambda (x)
(if (null x) ""
(setq ses-call-printer-return t)
(format ,(car printer) x))))
(t (error "Invalid printer %S" printer))))
(defun ses--local-printer (name def)
"Define a local printer with name NAME and definition DEF.
Return the printer info."
(or
(and (symbolp name)
(ses-printer-validate def))
(error "Invalid local printer definition"))
(and (gethash name ses--local-printer-hashmap)
(error "Duplicate printer definition %S" name))
(add-to-list 'ses-read-printer-history (symbol-name name))
(puthash name
(ses-make-local-printer-info (ses-safe-printer def))
ses--local-printer-hashmap))
(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."
(or (and (vectorp widths) (= (length widths) ses--numcols))
(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)
(setq ses--col-widths widths
ses--linewidth (apply #'+ -1 (mapcar #'1+ widths))
ses--blank-line (concat (make-string ses--linewidth ?\s) "\n"))
t)
(defmacro ses-column-printers (printers)
"Load the vector of column printers from the spreadsheet file and check
them for safety. This is a macro to prevent propagate-on-load viruses."
(or (and (vectorp printers) (= (length printers) ses--numcols))
(error "Bad column-printers vector"))
(dotimes (x ses--numcols)
(aset printers x (ses-safe-printer (aref printers x))))
(setq ses--col-printers printers)
(mapc #'ses-printer-record printers)
t)
(defmacro ses-default-printer (def)
"Load the global default printer from the spreadsheet file and check it
for safety. This is a macro to prevent propagate-on-load viruses."
(setq ses--default-printer (ses-safe-printer def))
(ses-printer-record def)
t)
(defmacro ses-header-row (row)
"Load the header row from the spreadsheet file and check it for safety.
This is a macro to prevent propagate-on-load viruses."
(or (and (wholenump row) (or (zerop ses--numrows) (< row ses--numrows)))
(error "Bad header-row"))
(setq ses--header-row row)
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'."
(declare (indent defun) (debug (form body)))
(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)))
(if (or (> minrow maxrow) (> mincol maxcol))
(error "Empty range"))
(dotimes (,r (- maxrow minrow -1))
(let ((row (+ ,r minrow)))
(dotimes (,c (- maxcol mincol -1))
(let ((col (+ ,c mincol)))
,@body))))))))
;;----------------------------------------------------------------------------
;; Utility functions
;;----------------------------------------------------------------------------
(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)
"Signal an error if PRINTER is not a valid SES cell printer."
(or (not printer)
(stringp printer)
;; printer is a local printer
(and (symbolp printer) (gethash printer ses--local-printer-hashmap))
(functionp printer)
(and (stringp (car-safe printer)) (not (cdr printer)))
(error "Invalid printer function %S" printer))
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)
"If FORMULA is of the form \\='SYMBOL, add it to the list of symbolic formulas
for this spreadsheet."
(and (ses-is-cell-sym-p formula)
(cl-pushnew (symbol-name formula) ses--symbolic-formulas :test #'string=)))
(defun ses-column-letter (col)
"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)
units
(concat (ses-column-letter (1- (/ col 26))) units))))
(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)))))
(defun ses-decode-cell-symbol (str)
"Decode a symbol \"A1\" => (0,0).
Return nil if STR is not a canonical cell name."
(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)))))))
(defun ses-create-cell-variable-range (minrow maxrow mincol maxcol)
"Create buffer-local variables for cells. This is undoable."
(push `(apply ses-destroy-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
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)))))
(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)
(if (let (case-fold-search) (string-match-p "\\`[A-Z]+[0-9]+\\'" (symbol-name sym)))
(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))))
;; 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.
(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)))
(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))))
(if (boundp sym)
(push `(apply ses-set-with-undo ,sym ,(symbol-value sym))
buffer-undo-list))
(kill-local-variable sym))))
(push `(apply ses-create-cell-variable-range ,minrow ,maxrow ,mincol ,maxcol)
buffer-undo-list))
(defun ses-reset-header-string ()
"Flag the header string for update.
Upon undo, the header string will be updated again."
(push '(apply ses-reset-header-string) buffer-undo-list)
(setq ses--header-hscroll -1))
;;Split this code off into a function to avoid coverage-testing difficulties
(defmacro ses--time-check (format &rest args)
"If `ses-start-time' is more than a second ago, call `message' with FORMAT
and ARGS and reset `ses-start-time' to the current time."
`(when (time-less-p 1 (time-since ses-start-time))
(message ,format ,@args)
(setq ses-start-time (float-time))))
;;----------------------------------------------------------------------------
;; The cells
;;----------------------------------------------------------------------------
(defmacro 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'."
(macroexp-let2 nil row row
(macroexp-let2 nil col col
(macroexp-let2 nil val val
`(let* ((cell (ses-get-cell ,row ,col))
(change
,(let ((field (progn (cl-assert (eq (car field) 'quote))
(cadr field))))
(if (eq field 'value)
`(ses-set-with-undo (ses-cell-symbol cell) ,val)
;; (let* ((slots (get 'ses-cell 'cl-struct-slots))
;; (slot (or (assq field slots)
;; (error "Unknown field %S" field)))
;; (idx (- (length slots)
;; (length (memq slot slots)))))
;; `(ses-aset-with-undo cell ,idx ,val))
(let ((getter (intern-soft (format "ses-cell--%s" field))))
`(ses-setter-with-undo
(eval-when-compile
(cons #',getter
(lambda (newval cell)
(setf (,getter cell) newval))))
,val cell))))))
(if change
(add-to-list 'ses--deferred-write (cons ,row ,col)))
nil))))) ; Make coverage-tester happy.
(defun ses-cell-set-formula (row col formula)
"Store a new formula for (ROW . COL) and enqueue the cell for
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)
not-a-cell-ref-list
x xref xrow xcol)
(cl-pushnew sym ses--deferred-recalc)
;;Delete old references from this cell. Skip the ones that are also
;;in the new list.
(dolist (ref oldref)
(unless (memq ref newref)
;; Because we do not cancel edit when the user provides a
;; false reference in it, then we need to check that ref
;; points to a cell that is within the spreadsheet.
(when
(and (setq x (ses-sym-rowcol ref))
(< (setq xrow (car x)) ses--numrows)
(< (setq xcol (cdr x)) ses--numcols))
;; Cell reference has to be re-written to data area as its
;; reference list is changed.
(cl-pushnew x ses--deferred-write :test #'equal)
(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)
;;Do not trust the user, the reference may be outside the spreadsheet
(if (and
(setq x (ses-sym-rowcol ref))
(< (setq xrow (car x)) ses--numrows)
(< (setq xcol (cdr x)) ses--numcols))
(unless (memq sym (setq xref (ses-cell-references xrow xcol)))
;; Cell reference has to be re-written to data area as
;; its reference list is changed.
(cl-pushnew x ses--deferred-write :test #'equal)
(ses-set-cell xrow xcol 'references (cons sym xref)))
(cl-pushnew ref not-a-cell-ref-list)))
(ses-formula-record formula)
(ses-set-cell row col 'formula formula)
(and not-a-cell-ref-list
(error "Found in formula cells not in spreadsheet: %S" not-a-cell-ref-list)))))
(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)))
(cl-pushnew sym (ses-cell-property :ses-repair-reference
(car rowcol)
(cdr rowcol))))))))
;; 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 "----------------------------------------------------------------
Some references were corrupted.
The following is a list where each element ELT is such
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"))))
(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))
cycle-error formula-error printer-error)
(let ((oldval (ses-cell-value cell))
(formula (ses-cell-formula cell))
newval
this-cell-Dijkstra-attempt+1)