-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathetcs-mode.el
More file actions
2153 lines (1831 loc) · 82.9 KB
/
etcs-mode.el
File metadata and controls
2153 lines (1831 loc) · 82.9 KB
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
;;; -*- emacs-lisp -*-
;;; to use this mode, you will need to do something along the lines of
;;; the following and have it in your .emacs file:
;;; (setq hol-executable "<fullpath to HOL executable>")
;;; (load "<fullpath to this file>")
;;; The fullpath to this file can be just the name of the file, if
;;; your elisp variable load-path includes the directory where it
;;; lives.
(require 'thingatpt)
(require 'cl-lib)
(require 'subr-x)
(defgroup etcs nil
"Customising the Emacs interface to the ETCS4 proof assistant."
:group 'external)
(define-prefix-command 'etcs-map)
(define-prefix-command 'etcs-d-map)
(define-prefix-command 'etcs-movement-map)
(make-variable-buffer-local 'etcs-buffer-name)
(set-default 'etcs-buffer-name "*ETCS*")
(set-default 'etcs-default-buffer nil)
(defcustom etcs-executable
"/Users/yimingxu/Documents/GitHub/ETCS/bin/etcs"
"Path-name for the ETCS executable."
:group 'etcs
:type '(file :must-match t))
(defcustom etcsmake-executable
"/Users/yimingxu/Documents/GitHub/ETCS/bin/Etcsmake"
"Path-name for the Etcsmake executable."
:group 'etcs
:type '(file :must-match t))
(defcustom etcs-show-tooltips-in-minibuffer t
"Whether to additionally show tooltips in minibuffer."
:group 'etcs
:type '(choice
(const :tag "Yes; messages appear in minibuffer" t)
(const :tag "No; messages only in tooltips" nil)))
(defconst etcs-dir
(file-name-directory
(directory-file-name (file-name-directory etcs-executable))))
(setq load-path (cons (concat etcs-dir "tools/") load-path))
(require 'etcsscript-mode)
(defcustom etcs-new-buffer-style-default 'new-frame
"Default style for creating new ETCS buffers. Possible values are
new-frame (create in a new-frame); horizontal (create in a new buffer
that is horizontally adjacent and to the right); and vertical (create in
a new buffer that is vertically adjacent and below)."
:group 'etcs
:type '(choice (const new-frame :tag "new-frame")
(const horizontal :tag "horizontal")
(const vertical :tag "vertical")))
(defun etcs-set-executable (filename)
"*Set etcs executable variable to be NAME."
(interactive "fETCS executable: ")
(setq etcs-executable filename)
(setq etcs-bare-p nil))
(defun etcsmake-set-executable (filename)
"*Set etcsmake executable variable to be NAME."
(interactive "fETCS executable: ")
(setq etcsmake-executable filename))
(defvar etcs-mode-sml-init-command
"use (Globals.ETCSDIR ^ \"/tools/etcs-mode.sml\")"
"*The command to send to ETCS to load the ML-part of etcs-mode.")
(defcustom etcs-echo-commands-p nil
"Whether or not to echo the text of commands originating elsewhere."
:group 'etcs
:type 'boolean)
(defcustom etcs-raise-on-recentre nil
"Controls if etcs-recentre (\\[etcs-recentre]) also raises the ETCS frame."
:group 'etcs
:type 'boolean)
(defcustom etcs-unicode-print-font-filename
"/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf"
"File name of font to use when printing ETCS output to a PDF file."
:group 'etcs
:type '(file :must-match t))
(defvar etcs-generate-locpragma-p t
"*Whether or not to generate (*#loc row col *) pragmas for ETCS.")
(defvar etcs-emit-time-elapsed-p nil
"*Whether or not to print time elapsed messages after causing ETCS
evaluations.")
(defvar etcs-auto-load-p t
"*Do automatic loading?")
(defvar etcs-bare-p nil
"*use etcs.bare?")
;;; For compatability between both Emacs and XEmacs, please use the following
;;; two functions to determine if the mark is active, or to set it active.
(defun etcs-is-region-active ()
(and transient-mark-mode (boundp 'mark-active) mark-active))
(defvar-local etcs-term-end-delim nil)
(put 'etcs-term 'end-op
(function
(lambda ()
(let ((pthm-point
(save-excursion
(let ((ok t))
(while
(and ok
(re-search-forward
"^Proof\\|^Theorem\\|^Triviality" nil t))
(let ((ppss (syntax-ppss)))
(if (or (nth 3 ppss) (nth 4 ppss)) nil
(setq ok nil))))
(not ok)))))
(if (and pthm-point (equal (match-string 0) "Proof"))
(progn (goto-char (match-beginning 0))
(setq etcs-term-end-delim "Proof"))
(re-search-forward "[`’”]\\|^End\\|^Termination" nil t)
(setq etcs-term-end-delim (match-string 0))
(goto-char (match-beginning 0)))))))
(defvar etcs-beg-pos nil) ; ugh, global, but easiest this way
(defvar etcs-name-attrs-colon-re
"[[:space:]]+[A-Za-z0-9'_]+\\(\\[[A-Za-z0-9_,]+\\]\\)?[[:space:]]*:")
(defvar etcs-quoted-theorem-proof-re-begin
(concat "\\(Theorem\\|Triviality\\)" etcs-name-attrs-colon-re))
(defvar etcs-quoted-definition-re-begin
(concat "\\(Definition\\|\\(Co\\)?Inductive\\)" etcs-name-attrs-colon-re))
(put 'etcs-term 'beginning-op
(function
(lambda ()
(let ((beg
(cond
((equal etcs-term-end-delim "`") "`")
((equal etcs-term-end-delim "’") "‘")
((equal etcs-term-end-delim "”") "“")
((equal etcs-term-end-delim "Proof")
etcs-quoted-theorem-proof-re-begin)
((or (equal etcs-term-end-delim "End")
(equal etcs-term-end-delim "Termination"))
etcs-quoted-definition-re-begin))))
(re-search-backward beg nil t)
(goto-char (match-end 0))
(setq etcs-beg-pos (point))))))
(defun etcs-term-at-point ()
(let ((s (thing-at-point 'etcs-term t)))
(with-etcs-locpragma etcs-beg-pos s)))
(defun etcs-buffer-ok (string)
"Checks a string to see if it is the name of a good ETCS buffer.
In reality this comes down to checking that a buffer-name has a live
process in it."
(and string (get-buffer-process string)
(eq 'run
(process-status
(get-buffer-process string)))))
(defun ensure-etcs-buffer-ok ()
"Ensures by prompting that a ETCS buffer name is OK, and returns it."
(if (etcs-buffer-ok etcs-buffer-name) etcs-buffer-name
(message
(cond (etcs-buffer-name (concat etcs-buffer-name " not valid anymore."))
(t "Please choose a ETCS to attach this buffer to.")))
(sleep-for 1)
(setq etcs-buffer-name (read-buffer "ETCS buffer: " etcs-default-buffer t))
(while (not (etcs-buffer-ok etcs-buffer-name))
(ding)
(message "Not a valid ETCS process")
(sleep-for 1)
(setq etcs-buffer-name
(read-buffer "ETCS buffer: " etcs-default-buffer t)))
(setq etcs-default-buffer etcs-buffer-name)
etcs-buffer-name))
(defun with-etcs-locpragma (pos s)
(if etcs-generate-locpragma-p
(concat (etcs-locpragma-of-position pos) s)
s))
(defun etcs-locpragma-of-position (pos)
"Convert Elisp position into ETCS location pragma. Not for interactive use."
(let ((initial-point (point)))
(goto-char pos)
(let* ((rowstart (point-at-bol)) ;; (line-beginning-position)
(row (+ (count-lines 1 pos)
(if (= rowstart pos) 1 0)))
(col (+ (current-column) 1)))
(goto-char initial-point)
(format " (*#loc %d %d *)\n" (- row 1) col))))
(defun send-raw-string-to-etcs (string echoit)
"Sends a string in the raw to ETCS. Not for interactive use."
(let ((buf (ensure-etcs-buffer-ok)))
(if echoit
(with-current-buffer buf
(goto-char (point-max))
(princ (concat string ";") (get-buffer buf))
(goto-char (point-max))
(comint-send-input)
(etcs-recentre 1))
(comint-send-string buf (concat string ";\n")))))
(defun send-timed-string-to-etcs (string echo-p &optional loud-opens)
"Send STRING to ETCS (with send-string-to-etcs), and emit information about
how long this took."
(interactive)
(send-raw-string-to-etcs
"val etcs_mode_time0 = #usr (Timer.checkCPUTimer Globals.etcs_clock);" nil)
(send-string-to-etcs string echo-p)
(send-raw-string-to-etcs
"val _ = let val t = #usr (Timer.checkCPUTimer Globals.etcs_clock)
val elapsed = Time.-(t, etcs_mode_time0)
in
print (\"\\n*** Time taken: \"^
Time.toString elapsed^\"s\\n\")
end" nil))
(defvar tactic-connective-regexp
"[[:space:]]*\\(THEN1\\|THENL\\|THEN\\|>>\\|>|\\|>-\\|>~\\|\\\\\\\\\\)[[:space:]]*[[(]?"
"Regular expression for strings used to put tactics together.")
(defun tactic-cleanup-leading (string)
"Remove leading instances of tactic connectives from a string.
A tactic connective is any one of \"THEN\", \"THENL\", \"THEN1\", \">>\", \">|\"
or \">-\"."
(let* ((case-fold-search nil)
(pattern (concat "\\`" tactic-connective-regexp)))
(replace-regexp-in-string pattern "" string)))
(defun tactic-cleanup-trailing (string)
"Remove trailing instances of tactic connectives from a string.
A tactic connective is any one of \"THEN\", \"THENL\", \"THEN1\", \">>\", \">|\"
or \">-\"."
(let* ((case-fold-search nil)
(pattern (concat tactic-connective-regexp "\\'")))
(replace-regexp-in-string pattern "" string)))
(defun etcs-find-eval-next-tactic (arg)
"Highlights the next tactic in the source and evaluates in the ETCS buffer.
With a prefix ARG, uses `expandf' rather than `e'."
(interactive "P")
(deactivate-mark)
(skip-syntax-forward " ")
(let
((term (thing-at-point 'tactic-terminator))
(sqb (char-equal (following-char) ?\[)))
(while (or term sqb)
(cond (term (forward-tactic-terminator 1))
(sqb (forward-char)))
(skip-syntax-forward " ")
(setq term (thing-at-point 'tactic-terminator))
(setq sqb (char-equal (following-char) ?\[))))
(mark-etcs-tactic)
(copy-region-as-etcs-tactic (region-beginning) (region-end) arg)
(goto-char (region-end)))
(defun copy-region-as-etcs-tactic (start end arg)
"Send selected region to ETCS process as tactic."
(interactive "r\nP")
(let*
((region-string0 (buffer-substring start end))
(region-string1 (tactic-cleanup-leading region-string0))
(region-string2 (tactic-cleanup-trailing region-string1))
(start-offset (- (length region-string0) (length region-string1)))
(region-string3 (with-etcs-locpragma (+ start start-offset) region-string2))
(ste "\"show_typecheck_errors\"")
(region-string (concat "let val old = Feedback.current_trace "
ste
" val _ = Feedback.set_trace "
ste
" 0 in ("
region-string3
") before "
"Feedback.set_trace " ste " old end"))
(e-string (concat "proofManagerLib." (if arg "expandf" "e")))
(tactic-string (format "%s (%s)" e-string region-string))
(sender (if etcs-emit-time-elapsed-p
'send-timed-string-to-etcs
'send-string-to-etcs)))
(funcall sender tactic-string etcs-echo-commands-p)))
;;; For goaltrees
(defun copy-region-as-goaltree-tactic (start end)
"Send selected region to ETCS process as goaltree tactic."
(interactive "r\nP")
(let* ((region-string (with-etcs-locpragma start
(buffer-substring-no-properties start end)))
(tactic-string
(format "proofManagerLib.expandv (%S,%s) handle e => Raise e"
region-string region-string))
(sender (if etcs-emit-time-elapsed-p
'send-timed-string-to-etcs
'send-string-to-etcs)))
(funcall sender tactic-string etcs-echo-commands-p)))
(defun send-string-as-etcs-goal (s)
(let ((goal-string (format "proofManagerLib.g \"%s\"" s)))
(send-raw-string-to-etcs goal-string etcs-echo-commands-p)
(send-raw-string-to-etcs "proofManagerLib.set_backup 100;" nil)))
(defun count-text-match (regex string)
(let ((case-fold-search nil)
(i 0)
(c 0))
(while (string-match regex string i)
(progn (setq i (match-end 0))
(setq c (+ c 1))))
c))
(defun etcs-string-contains-term-delimiters-p (s)
(< 0 (count-text-match
(concat "^Theorem\\|^Definition\\|^Proof\\|^\\(Co\\)?Inductive\\|"
"^Termination\\|^End\\|[“”‘’`]\\|^Triviality")
s)))
(defun etcs-do-goal (arg)
"Send term around point to ETCS process as goal.
If prefix ARG is true, or if in transient mark mode, region is active and
the region contains no term-delimiters, then send region instead."
(interactive "P")
(let ((txt (condition-case nil
(with-etcs-locpragma (region-beginning)
(buffer-substring (region-beginning) (region-end)))
(error nil))))
(if (or (and (etcs-is-region-active)
(not (etcs-string-contains-term-delimiters-p txt)))
arg)
(send-string-as-etcs-goal txt)
(send-string-as-etcs-goal (etcs-term-at-point)))))
(defun send-string-as-etcs-goaltree (s)
(let ((goal-string
(format "proofManagerLib.gt `%s` handle e => Raise e" s)))
(send-raw-string-to-etcs goal-string etcs-echo-commands-p)
(send-raw-string-to-etcs "proofManagerLib.set_backup 100;" nil)))
(defun etcs-do-goaltree (arg)
"Send term around point to ETCS process as goaltree.
If prefix ARG is true, or if in transient mark mode, region is active and
the region contains no backquotes, then send region instead."
(interactive "P")
(let ((txt (condition-case nil
(with-etcs-locpragma (region-beginning)
(buffer-substring (region-beginning) (region-end)))
(error nil))))
(if (or (and (etcs-is-region-active) (= (cl-count ?\` txt) 0))
arg)
(send-string-as-etcs-goaltree txt)
(send-string-as-etcs-goaltree (etcs-term-at-point)))))
(defun copy-region-as-etcs-definition (start end arg &optional loud-opens0)
"Send selected region to ETCS process as definition/expression. With a
prefix arg of 4 (hit control-u once), wrap what is sent so that it becomes
( .. ) handle e => Raise e, allowing ETCS_ERRs to be displayed cleanly.
With a prefix arg of 16 (hit control-u twice), toggle `quiet-declarations'
before and after the region is sent."
(interactive "r\np")
(let* ((buffer-string
(with-etcs-locpragma start (buffer-substring start end)))
(send-string
(if (= arg 4)
(concat "(" buffer-string ") handle e => Raise e")
buffer-string))
(loud-opens (if (= arg 16) t loud-opens0))
(sender (if etcs-emit-time-elapsed-p
'send-timed-string-to-etcs
'send-string-to-etcs)))
(if (= arg 16) (etcs-toggle-quietdec))
(unwind-protect
(progn
(funcall sender send-string etcs-echo-commands-p loud-opens)
(if (> (length send-string) 300)
(send-string-to-etcs
(concat "val _ = print \"\\n*** Emacs/ETCS command completed "
"***\\n\\n\""))))
(if (= (prefix-numeric-value arg) 16) (etcs-toggle-quietdec)))))
(defun copy-region-as-etcs-definition-quietly (start end)
(interactive "r")
(etcs-toggle-quiet-quietdec)
(copy-region-as-etcs-definition start end 0 t)
(etcs-toggle-quiet-quietdec))
(defun etcs-name-top-theorem (string arg)
"Name the top theorem of the proofManagerLib.
With prefix argument, drop the goal afterwards."
(interactive "sName for top theorem: \nP")
(if (not (string= string ""))
(send-raw-string-to-etcs
(format "val %s = top_thm()" string)
etcs-echo-commands-p))
(if arg
(send-raw-string-to-etcs "proofManagerLib.drop()" etcs-echo-commands-p)))
(defun etcs-start-termination-proof (arg)
"Send definition around point to ETCS process as Defn.tgoal.
If prefix ARG is true, or if in transient mark mode, region is active and
the region contains no term delimiters, then send region instead."
(interactive "P")
(let ((txt (condition-case nil
(with-etcs-locpragma (region-beginning)
(buffer-substring (region-beginning) (region-end)))
(error nil))))
(if (or (and (etcs-is-region-active)
(not (etcs-string-contains-term-delimiters-p txt)))
arg)
(etcs-send-string-as-termination-proof txt)
(etcs-send-string-as-termination-proof (etcs-term-at-point)))))
(defun etcs-send-string-as-termination-proof (str)
(send-raw-string-to-etcs
(concat "Defn.tgoal (Defn.Etcs_defn \"ETCSmode_defn\" `"
str "`) handle e => Raise e")
nil))
(defun remove-sml-comments (end)
(let (done (start (point)))
(while (and (not done) (re-search-forward "(\\*\\|\\*)" end t))
(if (string= (match-string 0) "*)")
(progn
(delete-region (- start 2) (point))
(setq done t))
;; found a comment beginning
(if (not (remove-sml-comments end)) (setq done t))))
(if (not done) (message "Incomplete comment in region given"))
done))
(defun remove-quoted-etcs-term (bq eq end-marker &optional extra)
(let ((start (point))
(bqsize (length bq))
(i (if extra extra 0)))
(if (re-search-forward eq end-marker t)
(delete-region (- start (- bqsize i)) (point))
(error
(format "Incomplete (%s...%s-quoted) ETCS term in region given; \
starts >%s%s<"
bq eq
bq
(buffer-substring (point) (+ (point) 10)))))))
(defun remove-etcs-string (end-marker)
(let ((start (point)))
(if (re-search-forward "\n\\|[^\\]?\"" end-marker t)
(if (string= (match-string 0) "\n")
(message "String literal terminated by newline - not allowed!")
(delete-region (- start 1) (point))))))
(setq etcs-open-terminator-regexp
(concat
(mapconcat (lambda (s) (concat "^" s "\\>"))
'("Theorem" "Definition" "Inductive" "CoInductive"
"Triviality" "Datatype" "Type" "Overload")
"\\|")
"\\|;\\|"
(regexp-opt
'("val" "fun" "in" "infix" "infixl" "infixr" "open" "local" "type"
"datatype" "nonfix" "exception" "end" "structure") 'symbols)))
(setq sml-struct-id-regexp "[A-Za-z][A-Za-z0-9_]*")
(defun send-string-to-etcs (string &optional echoit leave-loud-opens)
"Send a string to ETCS process."
(let ((buf (ensure-etcs-buffer-ok))
(old-mark-active (etcs-is-region-active)))
(unwind-protect
(with-temp-buffer
(etcsscript-mode)
(setq etcs-buffer-name buf) ; version of this variable in tmpbuf
(setq case-fold-search nil) ; buffer-local version
(insert string)
(goto-char (point-min))
;; first thing to do is to search through buffer looking for
;; identifiers of form id.id. When spotted such identifiers need
;; to have the first component of the name loaded.
(let ((regexp
(concat "`\\|“\\|‘\\|"
etcs-quoted-theorem-proof-re-begin "\\|"
etcs-quoted-definition-re-begin "\\|"
"\\(" sml-struct-id-regexp "\\)\\.\\w+" "\\|"
"\\_<open\\_>")))
(while (re-search-forward regexp (point-max) t)
(let ((pp (syntax-ppss))
(ms (match-string-no-properties 0)))
(if (and (not (nth 3 pp)) (not (nth 4 pp)))
;; maybe looking at termish thing that needs dodging
(cond
((string= ms "`")
(let ((term
(if (looking-at "`") ; double backtick
(progn (forward-char 1) "``") "`")))
(if (not (re-search-forward term nil t))
(error
(concat "Unbalanced " term " in region")))))
((string= ms "“")
(if (not (re-search-forward "”" nil t))
(error "Unbalanced “ in region")))
((string= ms "‘")
(if (not (re-search-forward "’" nil t))
(error "Unbalanced “ in region")))
((and (or (string-prefix-p "Theorem" ms)
(string-prefix-p "Triviality" ms))
(char-equal (char-before) ?:))
(if (not (re-search-forward "^Proof" nil t))
(error "Unbalanced `Theorem/Triviality' in region")))
((and (string-prefix-p "Definition" ms)
(char-equal (char-before) ?:))
(if (not
(re-search-forward "^Termination\\|^End" nil t))
(error "Unbalanced `Definition' in region")))
((and (or (string-prefix-p "Inductive" ms)
(string-prefix-p "CoInductive" ms))
(char-equal (char-before) ?:))
(if (not (re-search-forward "^End" nil t))
(error "Unbalanced [Co]Inductive in region")))
((string= ms "open")
;; point now after an open, now search forward
;; to end of buffer or a semi-colon, or an infix
;; declaration or a val or a fun or another open
;; or whatever, (as per the regexp defined just
;; before this function definition)
(let ((open-start (match-beginning 0))
(start (point))
(end
(save-excursion
(let ((case-fold-search nil)
(foundp nil)
(abortedp nil))
;; complicated loop required to avoid being
;; confused by input such as
;; open listSyntax (* ; *) integerTheory;
(while (and (not foundp) (not abortedp))
(if (re-search-forward
etcs-open-terminator-regexp
nil t)
(setq foundp
(let ((pp (syntax-ppss)))
(and (not (nth 3 pp))
(not (nth 4 pp)))))
(setq abortedp t)))
(if foundp
(- (point) (length (match-string 0)))
(point-max)))))
(endm (make-marker)))
; (message "Handling an open")
(if etcs-auto-load-p
(etcs-load-modules-in-region start end))
(if leave-loud-opens nil
;; now bracket the open decl with quietdec toggles
(set-marker endm end)
(goto-char end)
(insert
";val _ = ETCS_Interactive.toggle_quietdec();\n")
(goto-char open-start)
(insert
"val _ = ETCS_Interactive.toggle_quietdec();\n")
(goto-char endm) (set-marker endm nil))))
(t
; (message "Saw \"%s\"; position = %d; loading: %s"
; ms (point) (match-string 6))
(if etcs-auto-load-p
(etcs-load-string (match-string 6))))))))
;; send the string
(goto-char (point-min))
(send-buffer-to-etcs-maybe-via-file echoit)))
)
;; deactivate-mark will have likely been set by all the editting actions
;; in the temporary buffer. We fix this here, thereby keeping the mark
;; active, if it is active.
;; if in XEmacs, use (zmacs-activate-region) instead.
(if (boundp 'deactivate-mark)
(if deactivate-mark (setq deactivate-mark nil))
(if (and old-mark-active (fboundp 'zmacs-activate-region))
(zmacs-activate-region)))))
(defun interactive-send-string-to-etcs (string &optional echoit)
"Send a string to ETCS process."
(interactive "sString to send to ETCS process: \nP")
(if etcs-emit-time-elapsed-p
(send-timed-string-to-etcs string echoit)
(send-string-to-etcs string echoit)))
(if (null temporary-file-directory)
(if (equal system-type 'windows-nt)
(if (not (null (getenv "TEMP")))
(setq temporary-file-directory (getenv "TEMP")))
(setq temporary-file-directory "/tmp")))
(defun make-temp-file-xemacs (prefix &optional dir-flag)
"Create a temporary file.
The returned file name (created by appending some random characters at the end
of PREFIX, and expanding against `temporary-file-directory' if necessary,
is guaranteed to point to a newly created empty file.
You can then use `write-region' to write new data into the file.
If DIR-FLAG is non-nil, create a new empty directory instead of a file."
(let (file)
(while (condition-case ()
(progn
(setq file
(make-temp-name
(expand-file-name prefix temporary-file-directory)))
(if dir-flag
(make-directory file)
(write-region "" nil file nil 'silent nil)) ;; 'excl
nil)
(file-already-exists t))
;; the file was somehow created by someone else between
;; `make-temp-name' and `write-region', let's try again.
nil)
file))
(defvar etcs-mode-to-delete nil
"String optionally containing name of last temporary file used to transmit
ETCS sources to a running session (using \"use\")")
(defun send-buffer-to-etcs-maybe-via-file (&optional echoit)
"Send the contents of current buffer to ETCS, possibly putting it into a
file to \"use\" first."
(if (< 500 (buffer-size))
(let ((fname (if (fboundp 'make-temp-file)
;; then
(make-temp-file "etcs" nil "Script.sml")
;; else
(make-temp-file-xemacs "etcs")
)))
(if (stringp etcs-mode-to-delete)
(progn (condition-case nil
(delete-file etcs-mode-to-delete)
(error nil))
(setq etcs-mode-to-delete nil)))
; below, use visit parameter = 1 to stop message in mini-buffer
(write-region (point-min) (point-max) fname nil 1)
(send-raw-string-to-etcs (format "use \"%s\"" fname) nil)
(setq etcs-mode-to-delete fname))
(send-raw-string-to-etcs (buffer-string) echoit)))
(defun etcs-backup ()
"Perform a ETCS backup."
(interactive)
(send-raw-string-to-etcs "proofManagerLib.b()" etcs-echo-commands-p))
(defun etcs-user-backup ()
"Perform a ETCS backup to a user-defined save-point."
(interactive)
(send-raw-string-to-etcs "proofManagerLib.restore()" etcs-echo-commands-p))
(defun etcs-print-info ()
"Show some information about the currently running ETCS and the settings of etcs-mode."
(interactive)
(send-raw-string-to-etcs
(concat "print_current_etcs_status" "\""
etcs-executable "\" \"" etcsmake-executable "\" ();")
etcs-echo-commands-p))
(defun etcs-user-save-backup ()
"Saves the current status of the proof for later backups to this point."
(interactive)
(send-raw-string-to-etcs "proofManagerLib.save()" etcs-echo-commands-p))
(defun etcs-print-goal ()
"Print the current ETCS goal."
(interactive)
(send-raw-string-to-etcs "proofManagerLib.p()" etcs-echo-commands-p))
(defun etcs-print-all-goals ()
"Print all the current ETCS goals."
(interactive)
(send-raw-string-to-etcs "proofManagerLib.status()" etcs-echo-commands-p))
(defun etcs-interrupt ()
"Perform a ETCS interrupt."
(interactive)
(let ((buf (ensure-etcs-buffer-ok)))
(interrupt-process (get-buffer-process buf))))
(defun etcs-kill ()
"Kill ETCS process."
(interactive)
(let ((buf (ensure-etcs-buffer-ok)))
(kill-process (get-buffer-process buf))))
(defun etcs-recentre (arg)
"Display the ETCS window in such a way that it displays most text, with the
cursor at the bottom.
With prefix arg, instead orient the ETCS window so as to put the cursor in
the middle of the window, and keep the cursor in its current position.
If the variable `etcs-raise-on-recentre' is non-nil, also raise the frame
containing the ETCS window, but keep the current frame uppermost."
(interactive "p")
(let ((f (selected-frame)))
(if (get-buffer-window etcs-buffer-name t)
(save-mark-and-excursion
(select-window (get-buffer-window etcs-buffer-name t))
(and etcs-raise-on-recentre (progn (raise-frame) (raise-frame f)))
(if (= arg 1) (goto-char (point-max)))
(recenter (if (= arg 1) -1 nil))))))
(defun etcs-rotate (arg)
"Rotate the goal stack N times. Once by default."
(interactive "p")
(send-raw-string-to-etcs (format "proofManagerLib.r %d" arg)
etcs-echo-commands-p))
(defun etcs-scroll-up (arg)
"Scrolls the ETCS window."
(interactive "P")
(ensure-etcs-buffer-ok)
(save-excursion
(select-window (get-buffer-window etcs-buffer-name t))
(scroll-up arg)))
(defun etcs-scroll-down (arg)
"Scrolls the ETCS window."
(interactive "P")
(ensure-etcs-buffer-ok)
(save-excursion
(select-window (get-buffer-window etcs-buffer-name t))
(scroll-down arg)))
(defun etcs-use-file (filename)
"Gets ETCS session to \"use\" a file."
(interactive "fFile to use: ")
(send-raw-string-to-etcs (concat "use \"" filename "\";")
etcs-echo-commands-p))
(defun etcs-load-string (s)
"Loads the ML object file NAME.uo; checking that it isn't already loaded."
(let* ((buf (ensure-etcs-buffer-ok))
(mys (format "%s" s)) ;; gets rid of text properties
(commandstring
(concat "val _ = if List.exists (fn s => s = \""
mys
"\") (emacs_etcs_mode_loaded()) then () else "
"(print \"Loading " mys
"\\n\"; " "Meta.load \"" mys "\");\n")))
(comint-send-string buf commandstring)))
(defun etcs-load-modules-in-region (start end)
"Attempts to load all of the words in the region as modules."
(interactive "rP")
(save-excursion
(goto-char start)
(while (re-search-forward (concat "\\b" sml-struct-id-regexp "\\b") end t)
(let ((ppss (syntax-ppss)))
(if (and (not (nth 4 ppss)) (not (nth 3 ppss)))
(etcs-load-string (match-string 0)))))))
(defun etcs-load-file (arg)
"Gets ETCS session to \"load\" the file at point.
If there is no filename at point, then prompt for file. If the region
is active (in transient mark mode) and it looks like it might be a
module name or a white-space delimited list of module names, then send
region instead. With prefix ARG prompt for a file-name to load."
(interactive "P")
(let* ((wap (word-at-point))
(txt (condition-case nil
(buffer-substring (region-beginning) (region-end))
(error nil))))
(cond (arg (etcs-load-string (read-string "Library to load: ")))
((and (etcs-is-region-active)
(string-match (concat "^\\(\\s-*" sml-struct-id-regexp
"\\)+\\s-*$") txt))
(etcs-load-modules-in-region (region-beginning) (region-end)))
((and wap (string-match "^\\w+$" wap)) (etcs-load-string wap))
(t (etcs-load-string (read-string "Library to load: "))))))
(defun etcs-mode-init-sml ()
(etcs-toggle-quiet-quietdec)
(send-raw-string-to-etcs etcs-mode-sml-init-command nil)
(etcs-toggle-quiet-quietdec))
(defun turn-off-etcs-font-lock (oldvar)
(interactive)
(if (not oldvar)
(progn
(message "Turning on font-lock mode does nothing in ETCS mode")
(setq font-lock-defaults nil)))
(setq font-lock-mode nil))
(defun etcsmake (&optional dir)
(interactive "DRun Etcsmake in dir: ")
(if (not (null dir))
(with-current-buffer (get-buffer-create "*Etcsmake*")
(delete-region (point-min) (point-max))
(cd (expand-file-name dir)))
)
(let* ((buf (make-comint "Etcsmake"
etcsmake-executable nil "--qof" "-k")))
(with-current-buffer buf
(font-lock-mode 0)
(make-local-variable 'font-lock-function)
(setq font-lock-function 'turn-off-etcs-font-lock)
(setq comint-preoutput-filter-functions '(etcsmakepp-output-filter)))
(setq comint-scroll-show-maximum-output t)
(setq comint-scroll-to-bottom-on-output t)
(display-buffer buf)
))
;** etcs map keys and function definitions
(defun etcs-executable-with-bare ()
(if etcs-bare-p (concat etcs-executable ".bare")
etcs-executable))
(defun etcs--looks-like-root-etcsdir (dir)
(cl-every
(lambda (s) (file-exists-p (concat (file-name-as-directory dir) s)))
'("COPYRIGHT" "tools" "tools-poly" "std.prelude" "bin")))
(defun etcs--find-alternate-executable (dir0 original-name0)
(let ((dir (expand-file-name dir0))
(original-name (expand-file-name original-name0)))
;; check for lastmaker file
(if-let*
(((file-readable-p ".ETCSMK/lastmaker"))
((> 500 (file-attribute-size (file-attributes ".ETCSMK/lastmaker"))))
(lines (with-temp-buffer
(insert-file-contents-literally ".ETCSMK/lastmaker")
(split-string (buffer-string) "\n" t)))
((not (null lines)))
(dir1 (file-name-directory (car lines)))
(name (concat dir1 "etcs"))
((not (equal name original-name))))
(list (concat dir1 "etcs") "(honouring last build in this directory)")
(while (and (not (etcs--looks-like-root-etcsdir dir))
(not (equal "/" dir)))
(setq dir (file-name-directory (directory-file-name dir))))
(if (equal "/" dir) nil
(let ((bindir
(file-name-as-directory
(concat (file-name-as-directory dir) "bin"))))
(cond
((equal (file-name-directory original-name) bindir) nil)
((file-exists-p (concat bindir "etcs.state"))
(list (concat bindir "etcs") "(as we are in its ETCS directory)"))
((file-exists-p (concat bindir "etcs.state0"))
(list
(concat bindir "etcs.bare")
"(as we are in its ETCS directory and etcs.state doesn't exist)"))))))))
(defun etcs--get-executable ()
(let ((first-option (etcs-executable-with-bare)))
(or (let ((alternate
(etcs--find-alternate-executable default-directory first-option)))
(if alternate
(progn (message "Using %s as ETCS executable %s"
(car alternate) (cadr alternate))
(sleep-for 1 500)
(car alternate))))
first-option)))
(defun etcs (&optional display-actions display-alist)
"Runs a ETCS session in a comint window."
(interactive)
(let* ((original-buffer (current-buffer))
(my-dir (or (ignore-errors (file-name-directory buffer-file-name))
default-directory))
(etcs-executable (etcs--get-executable)))
(if (not (file-executable-p etcs-executable))
(error "Wanted to execute %s as ETCS, but can not find/execute it"
etcs-executable))
(if (get-buffer etcs-buffer-name)
(progn
(set-buffer etcs-buffer-name)
(if (etcs-buffer-ok etcs-buffer-name)
(progn
(message "Killing existing ETCS process")
(comint-send-eof)
(sleep-for 0 500)))
(setq default-directory my-dir)
(make-comint-in-buffer "ETCS" etcs-buffer-name etcs-executable))
(let* ((buf (make-comint "ETCS" etcs-executable)))
(setq etcs-buffer-name (buffer-name buf))
(set-buffer etcs-buffer-name)))
(setq comint-prompt-regexp "^- ")
;; must go to ridiculous lengths to ensure that font-lock-mode is
;; turned off and stays off
(font-lock-mode 0)
(make-local-variable 'font-lock-function)
(setq font-lock-function 'turn-off-etcs-font-lock)
(make-local-variable 'comint-preoutput-filter-functions)
(etcspp-quiet-reset)
(setq comint-preoutput-filter-functions '(etcspp-output-filter))
(setq comint-scroll-show-maximum-output t)
(setq comint-scroll-to-bottom-on-output t)
(etcs-mode-init-sml)
(send-raw-string-to-etcs
"val _ = Parse.current_backend := PPBackEnd.emacs_terminal;" nil)
(if etcs-show-tooltips-in-minibuffer
(progn (setq help-at-pt-display-when-idle t)
(help-at-pt-set-timer)))
(if (eq (get-buffer etcs-buffer-name) original-buffer)
nil
(display-buffer etcs-buffer-name
(cons
(append display-actions
'(display-buffer-use-some-frame
display-buffer-pop-up-frame))
display-alist))
(select-frame-set-input-focus
(window-frame (get-buffer-window original-buffer t))))))
(defun etcs-toggle-bare ()
"Toggles the elisp variable 'etcs-bare-p."
(interactive)
(setq etcs-bare-p (not etcs-bare-p))
(concat "using " (etcs-executable-with-bare)))
(defun etcs-display ()
"Attempts to bring the ETCS buffer to the fore (calling `display-buffer')."
(interactive)
(display-buffer etcs-buffer-name))
(defun etcs-vertical ()
"Runs a ETCS session after splitting the window"
(interactive)
(etcs '(display-buffer-below-selected)))
(defun etcs-horizontal ()
"Runs a ETCS session after splitting the window"
(interactive)
(etcs '(display-buffer-reuse-window
(lambda (b al)
(let ((split-height-thresetcsd nil)
(split-width-thresetcsd 0))
(display-buffer-pop-up-window b al))))
'((window-width . 83) (reusable-frames . nil))))
(defvar etcs-new-buffer-style etcs-new-buffer-style-default)
(setq etcs-new-buffer-style-alist
'((horizontal . etcs-horizontal)
(vertical . etcs-vertical)
(new-frame . etcs)))
(defun etcs-with-region ()
"Starts a ETCS session and pastes selected region into it. If there is no active region, pastes wetcse buffer."
(interactive)
(let* ((style-str (completing-read
(concat "ETCS buffer position ("
(symbol-name etcs-new-buffer-style)
"): ")
'("horizontal" "vertical" "new-frame")
nil
t
nil
nil
(symbol-name etcs-new-buffer-style)
t))
(style (intern style-str))
(starter (cdr (assoc style etcs-new-buffer-style-alist))))
(setq etcs-new-buffer-style style)
(save-mark-and-excursion (funcall starter))
(if (region-active-p)
(copy-region-as-etcs-definition-quietly (region-beginning) (region-end))
(let ((beg (point-min))
(end (progn
(while (looking-at "[[:space:]]*\n") (forward-line 1))
(search-backward "\n\n")
(while (looking-at "[[:space:]]*\n") (forward-line 1))
(point))))
(push-mark (point-min))
(activate-mark t)
(copy-region-as-etcs-definition-quietly beg end)))))
(defun run-program (filename niceness)
"Runs a PROGRAM in a comint window, with a given (optional) NICENESS."
(interactive "fProgram to run: \nP")
(let* ((niceval (cond ((null niceness) 0)
((listp niceness) 10)
(t (prefix-numeric-value niceness))))