-
Notifications
You must be signed in to change notification settings - Fork 29
/
company-coq.el
5802 lines (5096 loc) · 263 KB
/
company-coq.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
;;; company-coq.el --- A collection of extensions for Proof General's Coq mode -*- lexical-binding: t -*-
;; Copyright (C) 2015, 2016, 2017 Clément Pit-Claudel
;; Author: Clément Pit-Claudel <clement.pitclaudel@live.com>
;; URL: https://github.com/cpitclaudel/company-coq
;; Keywords: convenience, languages
;; Package-Requires: ((cl-lib "0.5") (dash "2.12.1") (yasnippet "0.11.0") (company "0.8.12") (company-math "1.1"))
;; Version: 1.0
;; This program 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.
;; This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; This package includes a collection of company-mode backends for
;; Proof-General's Coq mode, and many useful extensions to Proof-General.
;;
;; See https://github.com/cpitclaudel/company-coq/ for a detailed description,
;; including screenshots and documentation. After installing, you may want to
;; use M-x company-coq-tutorial to open the tutorial.
;;; History:
;;
;; 2016-02-28 — Show input hints for Unicode and prettified symbols
;; 2016-02-28 — Prettify symbols in notation strings and code blocks
;; 2016-02-07 — Support for changing [Require]s to use fully qualified names
;; 2016-02-02 — Preserve names by inserting intros when extracting a lemma
;; 2016-01-31 — Fall back to regular autocompletion in comments (except in code blocks)
;; 2016-01-26 — Detect and display subscripts: a1 → a₁ and a__n → aₙ
;; 2016-01-20 — First stable release (~600 commits)
;; 2015-02-15 — First commit
;;; Code:
;;
;; Technical notes
;; ===============
;;
;; Sending commands to the prover when it's already busy breaks everything.
;; 'proof-shell-handle-delayed-output-hook is a good place to reload symbols,
;; except when an error occurs (in that case the hook runs before all output has
;; been processed.
;;
;; This problem is solved by refusing to communicate with the prover, unless it
;; is reported as available. When it isn't, the interaction is either abandonned
;; (that's what happens with documentation, and with completion if the symbols
;; aren't available yet)) or delayed using an idle timer (reload; in fact, this
;; one is always wrapped in an idle timer). To prevent loops due to idle timers
;; firing in succession, reloads are only attempted once.
;;
;; The current implementation uses two hooks:
;; * 'proof-shell-insert-hook
;; In this one we check the input to see if it might introduce new symbols
;; (e.g. [Require …])
;; * 'proof-shell-handle-delayed-output-hook
;; In this one we parse the output to see if it suggests that new symbols
;; have been introduced (e.g. [… defined])
;;
;; Since these two hooks are called into even for commands issued by our own
;; code, we only execute their body if we are not currently already waiting for
;; an answer from the prover (company-coq-talking-to-prover).
(require 'cl-lib) ;; Compatibility
(require 'company) ;; Autocompletion
(require 'company-math) ;; Math symbols
(require 'dash) ;; -when-let, -if-let, -zip, -keep, etc.
(require 'diff-mode) ;; Browsing through large error messages
(require 'outline) ;; Outlines
(require 'hideshow) ;; Code folding
(require 'paren) ;; Find matching block start
(require 'shr) ;; HTML rendering
(require 'smie) ;; Move around the source code
(require 'yasnippet) ;; Templates
(require 'pulse) ;; Pulsing after jumping to definitions
(require 'button) ;; Links in goals and error messages
(require 'menu-bar) ;; `popup-menu'
(unless (require 'alert nil t) ;; Notifications
(require 'notifications nil t))
(require 'company-coq-abbrev) ;; Tactics from the manual
(require 'company-coq-tg) ;; Parsing code for tactic notations
(require 'company-coq-utils) ;; Various utils
;;; Shims for old emacsen
(defvar company-coq-seconds-to-string
(list (list 1 "ms" 0.001)
(list 100 "s" 1)
(list (* 60 100) "m" 60.0)
(list (* 3600 30) "h" 3600.0)
(list (* 3600 24 400) "d" (* 3600.0 24.0))
(list nil "y" (* 365.25 24 3600)))
"Formatting used by the function `company-coq-seconds-to-string'.")
(defun company-coq-seconds-to-string (delay)
"Convert the time interval DELAY in seconds to a short string."
(cond ((> 0 delay) (concat "-" (company-coq-seconds-to-string (- delay))))
((= 0 delay) "0s")
(t (let ((sts company-coq-seconds-to-string) here)
(while (and (car (setq here (pop sts)))
(<= (car here) delay)))
(concat (format "%.2f" (/ delay (car (cddr here)))) (cadr here))))))
(eval-and-compile
;; Silence the byte-compiler in Emacs < 24.4
(defvar shr-width)
(defvar shr-internal-width)
(defvar shr-target-id)
(defvar shr-external-rendering-functions))
(defvar company-coq--libxml-available-p nil)
(defun company-coq--libxml-available-p ()
"Check for libxml."
(unless (consp company-coq--libxml-available-p)
(setq company-coq--libxml-available-p
(list
(cond
((fboundp 'libxml-available-p)
(libxml-available-p))
((fboundp 'libxml-parse-xml-region)
;; Just having libxml-parse-xml-region isn't enough on Windows
(with-temp-buffer
(insert "<a/>")
(libxml-parse-xml-region (point-min) (point-max))))))))
(car company-coq--libxml-available-p))
;; Shims for PG
(eval-and-compile
(defvar company-coq--check-forward-declarations nil
"Whether incorrect `company-coq--forward-declare' forms should throw errors.
This is useful for debugging, mostly.")
(defun company-coq-forward-declare-var--verify (var value)
"Check that the forward declaration of SYMBOL with VALUE is legitimate."
(when company-coq--check-forward-declarations
(unless (or (boundp var) value)
(warn "Variable %S isn't declared" var))
(when (and (boundp var) value (not (equal (symbol-value var) value)))
(warn "Variable %S is declared to %S, but fallback is set to %S" var (symbol-value var) value))))
(defmacro company-coq-forward-declare-var (var &optional value)
"Forward-declare VAR.
If `company-coq--check-forward-declarations', check that the declaration is valid.
If VALUE is non-nil, assign it to the variable."
(declare (indent defun))
`(progn
(company-coq-forward-declare-var--verify ',var ,value)
(if ,value
(defvar ,var ,value)
(defvar ,var))))
(defun company-coq-forward-declare-fun--verify (fun)
"Check that the forward declaration of FUN is legitimate."
(when (and company-coq--check-forward-declarations (not (fboundp fun)))
(warn "Function %S isn't declared" fun)))
(defmacro company-coq-forward-declare-fun (fun &rest args)
"Forward-declare FUN with ARGS.
If `company-coq--check-forward-declarations' is set, do not
forward-declare; instead, check that the declaration is valid."
(declare (indent defun))
`(progn
(company-coq-forward-declare-fun--verify ',fun)
(declare-function ,fun ,@args)))
(company-coq-forward-declare-var proof-goals-buffer)
(company-coq-forward-declare-var proof-script-buffer)
(company-coq-forward-declare-var proof-response-buffer)
(company-coq-forward-declare-var proof-action-list)
(company-coq-forward-declare-var proof-script-fly-past-comments)
(company-coq-forward-declare-var proof-shell-proof-completed)
(company-coq-forward-declare-var proof-shell-last-output)
(company-coq-forward-declare-var proof-shell-last-output-kind)
(company-coq-forward-declare-var proof-shell-last-goals-output)
(company-coq-forward-declare-var proof-shell-last-response-output)
(company-coq-forward-declare-var proof-shell-delayed-output-flags)
(company-coq-forward-declare-var proof-shell-eager-annotation-start)
(company-coq-forward-declare-var proof-shell-eager-annotation-end)
(company-coq-forward-declare-var pg-span-context-menu-keymap)
(company-coq-forward-declare-var coq-reserved)
(company-coq-forward-declare-var coq-user-cheat-tactics-db)
(company-coq-forward-declare-var coq-user-commands-db)
(company-coq-forward-declare-var coq-user-reserved-db)
(company-coq-forward-declare-var coq-user-solve-tactics-db)
(company-coq-forward-declare-var coq-user-tacticals-db)
(company-coq-forward-declare-var coq-user-tactics-db)
(company-coq-forward-declare-fun proof-shell-invisible-command "ext:proof-shell.el" cmd)
(company-coq-forward-declare-fun proof-shell-available-p "ext:proof-shell.el")
(company-coq-forward-declare-fun proof-shell-live-buffer "ext:proof-shell.el")
(company-coq-forward-declare-fun proof-shell-ready-prover "ext:proof-shell.el")
(company-coq-forward-declare-fun proof-unprocessed-begin "ext:proof-script.el")
(company-coq-forward-declare-fun proof-electric-terminator "ext:pg-user.el")
(company-coq-forward-declare-fun proof-goto-point "ext:pg-user.el")
(company-coq-forward-declare-fun proof-electric-terminator "ext:pg-user.el")
(company-coq-forward-declare-fun coq-mode "ext:coq.el")
(company-coq-forward-declare-fun coq-response-mode "ext:coq.el")
(company-coq-forward-declare-fun coq-insert-match "ext:coq.el")
(company-coq-forward-declare-fun coq-last-prompt-info-safe "ext:coq.el")
(company-coq-forward-declare-fun proof-inside-comment "ext:proof-syntax.el" cmd))
;; This doesn't run at compile time
(unless (require 'proof-site nil t)
;; No others `require's at this point: we don't want to start PG's machinery
;; just because a user `require'd company-coq.
(error "Company-Coq: Unable to load proof-site. Is Proof General installed properly?"))
(defgroup company-coq nil
"Extensions for Proof General's Coq mode."
:prefix "company-coq-"
:group 'company)
(defgroup company-coq-obsolete nil
"Company-Coq obsolete settings."
:prefix "company-coq-"
:group 'company-coq)
(defgroup company-coq-faces nil
"Company-Coq faces."
:prefix "company-coq-"
:group 'company-coq)
(eval-and-compile
(defvar company-coq-debug nil
"Debug mode for company-coq."))
(defcustom company-coq-custom-snippets '("Section ${1:SectionName}.\n$0\nEnd $1."
"Module ${1:ModuleName}.\n$0\nEnd $1."
"Module Type ${1:ModuleTypeName}.\n$0\nEnd $1."
"match ${ident} with\n$0\nend"
"lazymatch ${ident} with\n$0\nend"
"multimatch ${ident} with\n$0\nend"
"match constr:($1) with\n$0\nend"
"lazymatch constr:($1) with\n$0\nend"
"match goal with\n$0\nend"
"lazymatch goal with\n$0\nend")
"Custom snippets.
Feel free to share your snippets on company-coq's GitHub!"
:group 'company-coq
:type '(repeat string))
(defcustom company-coq-dynamic-autocompletion nil
"Get suggestions by querying coq about defined identifiers.
This is an experimental feature. It requires Coq 8.5 beta 3 or a
patched version of Coq 8.4 to work properly."
:group 'company-coq-obsolete
:type 'boolean)
(make-obsolete-variable 'company-coq-dynamic-autocompletion 'company-coq-live-on-the-edge "company-coq 1.0")
(defconst company-coq--capability-detection-cmd "Test Search Output Name Only"
"Command used to test for dynamic completion capabilities.
Two patches are required for proper completion of theorems:
=Redirect=ion to a file, and =Search Output Name Only=. For
tactics, and extra patch is required.")
(defvar company-coq--coqtop-patched-result 'unknown
"Whether coqtop supports advanced completion features.
One of 'unknown, 'yes, 'no.")
(defcustom company-coq-autocomplete-context t
"Autocomplete hypotheses by parsing the latest Goals output.
This is an experimental feature."
:group 'company-coq-obsolete
:type 'boolean)
(make-obsolete-variable 'company-coq-autocomplete-context 'company-coq-disabled-features "company-coq 1.0")
(defcustom company-coq-autocomplete-modules t
"Autocomplete module names from Coq's load path."
:group 'company-coq-obsolete
:type 'boolean)
(make-obsolete-variable 'company-coq-autocomplete-modules 'company-coq-disabled-features "company-coq 1.0")
(defcustom company-coq-autocomplete-block-end t
"Autocomplete the name of the last opened block."
:group 'company-coq-obsolete
:type 'boolean)
(make-obsolete-variable 'company-coq-autocomplete-block-end 'company-coq-disabled-features "company-coq 1.0")
(defcustom company-coq-autocomplete-search-results t
"Autocomplete symbol names pulled from the results of the last search."
:group 'company-coq-obsolete
:type 'boolean)
(make-obsolete-variable 'company-coq-autocomplete-search-results 'company-coq-disabled-features "company-coq 1.0")
(defcustom company-coq-autocomplete-symbols t
"Autocomplete symbols by searching in the buffer for lemmas and theorems.
If the dynamic completion feature is on, query the proof
assistant in addition to searching."
:group 'company-coq-obsolete
:type 'boolean)
(make-obsolete-variable 'company-coq-autocomplete-symbols 'company-coq-disabled-features "company-coq 1.0")
(defcustom company-coq-prettify-symbols t
"Transparently replace keywords by the corresponding symbols.
The contents of the buffer are not changed."
:group 'company-coq-obsolete
:type 'boolean)
(make-obsolete-variable 'company-coq-prettify-symbols 'company-coq-disabled-features "company-coq 1.0")
(defcustom company-coq-snippet-default-hole-contents "_"
"String to use to indicate holes in inserted snippets."
:group 'company-coq
:type '(string))
(defvar company-coq-enabled-backends nil
"List of currently enabled company-coq completion backends.
Do not enable or disable backends by editing this list; instead,
customize `company-coq-disabled-features'.")
(defvar company-coq-excluded-pg-patterns '("without loss" "Fixpoint")
"List of patterns that are not imported from Proof General's list.")
(defcustom company-coq-sorted-backends '(company-coq-reserved-keywords-backend
company-coq-block-end-backend
company-coq-user-snippets-backend
company-coq-modules-backend
company-coq-context-backend
company-coq-refman-ltac-abbrevs-backend
company-coq-refman-tactic-abbrevs-backend
company-coq-refman-vernac-abbrevs-backend
company-coq-refman-scope-abbrevs-backend
company-coq-pg-backend
company-coq-local-definitions-backend
company-coq-search-results-backend
company-coq-dynamic-tactics-backend
company-coq-dynamic-symbols-backend)
"All completion backends, ordered by display priority.
Do not remove entries from this list (but feel free to reorder
them). To disable backends, customize `company-coq-disabled-features'."
:group 'company-coq
:type '(repeat function))
(defvar company-coq-talking-to-prover nil
"Indicates whether a interaction has been initiated with the prover, to disable the input and output hooks.")
(defvar company-coq-symbols-reload-needed t
"Indicates whether the dynamic list of symbols is outdated.
This variable is set from places where immediate reloading is
impossible, for example in `proof-shell-insert-hook'")
(defvar company-coq-tactics-reload-needed t
"Indicates whether the dynamic list of tactics is outdated.
This variable is set from places where immediate reloading is
impossible, for example in `proof-shell-insert-hook'")
(defvar company-coq-modules-reload-needed t
"Indicates whether the dynamic list of modules is outdated.
This variable is set from places where immediate reloading is
impossible, for example in `proof-shell-insert-hook'")
(defvar company-coq-dynamic-symbols nil
"Keeps track of defined symbols.")
(defvar company-coq-dynamic-tactics nil
"Keeps track of defined tactics.")
(defvar company-coq-path-specs-cache nil
"Cache tracking paths specs in Coq's load path.")
(defvar company-coq-last-search-results nil
"Cache tracking symbols mentionned in search results.")
(defvar company-coq-last-search-scan-size nil
"If the response buffer has this size, search results are deemed up to date.")
(defvar company-coq-definition-overlay nil
"Overlay used to show inline definitions.")
(defconst company-coq-id-regexp "\\(?:[a-zA-Zα-ωΑ-Ω0-9_][a-zA-Zα-ωΑ-Ω0-9_']*\\)")
(defconst company-coq-prefix-regexp "\\(?:[a-zA-Zα-ωΑ-Ω0-9_][a-zA-Zα-ωΑ-Ω0-9_.']*!?\\)?") ;; '!' included for [intros!] etc.
(defconst company-coq-symbol-regexp "\\(?:[_a-zA-Zα-ωΑ-Ω]\\(?:[a-zA-Zα-ωΑ-Ω0-9_.']*[a-zA-Zα-ωΑ-Ω0-9_']\\)?\\)")
(defconst company-coq-symbol-regexp-no-dots "\\(?:_*[a-zA-Zα-ωΑ-Ω]\\(?:[a-zA-Zα-ωΑ-Ω0-9_']*[a-zA-Zα-ωΑ-Ω0-9_']\\)?\\)")
(defconst company-coq-symbol-regexp-no-dots-no-numbers "\\(?:_*[a-zA-Zα-ωΑ-Ω]\\(?:[a-zA-Zα-ωΑ-Ω0-9_']*[a-zA-Zα-ωΑ-Ω']\\)?\\)")
(defconst company-coq-module-chunk-regexp "\\(?:[A-Z][a-zA-Zα-ωΑ-Ω0-9_]*\\)")
(defconst company-coq-module-name-regexp (concat company-coq-module-chunk-regexp "\\(?:\\." company-coq-module-chunk-regexp "\\)*"))
(defconst company-coq-all-symbols-slow-regexp (concat "^\\(" company-coq-symbol-regexp "\\):")
"Regexp matching symbol names in search results.")
(defconst company-coq--subgoal-header-regexp
"\\(?:^\\(subgoal .* is:\\| ============================\\)$\\)"
"Regexp indicating the beginning of a subgoal.")
;; More powerful, but more tricky to match against:
;; "\\(?:^ \\|[^[:space:]] +\\)\\(\\(?:[^:=, \t\r\n]\\|, \\)+\\) \\(:=?\\) "
(defconst company-coq--hypothesis-header-regexp
"^ \\(\\(?:[^:=, \t\r\n]\\|, \\)+\\) \\(:=?\\) "
"Regexp indicating the beginning of a hypothesis.")
(defconst company-coq--hypotheses-block-opener "\n\\s-*\n"
"Regexp matching the beginning of hypotheses.")
(defconst company-coq--hypotheses-block-closer company-coq--subgoal-header-regexp
"Regexp matching the end of hypotheses.")
(defconst company-coq-path-regexp (concat "\\`\\(\\S-*\\) +\\(\\S-*\\)\\'"))
(defun company-coq-make-headers-regexp (headers &optional body)
"Construct a regexp from HEADERS and BODY.
The result matches any symbol in HEADERS, followed by BODY."
(concat "^[[:blank:]]*\\_<\\(" (regexp-opt headers) "\\)\\_>"
(when body (concat "\\s-*\\(" body "\\)"))))
(defconst company-coq-definitions-kwds `("Class" "CoFixpoint" "CoInductive" "Coercion" "Corollary"
"Declare Module" "Definition" "Example" "Fact" "Fixpoint"
"Function" "Functional Scheme" "Global Instance" "Inductive"
"Instance" "Lemma" "Let" "Ltac" "Program" "Program Definition"
"Program Instance" "Program Fixpoint" "Record" "Scheme" "Theorem"
"Variant" "with")
"Keywords that introduce a definition.")
(defconst company-coq-definitions-regexp (company-coq-make-headers-regexp company-coq-definitions-kwds
company-coq-id-regexp)
"Regexp used to locate symbol definitions in the current buffer.")
(defconst company-coq-block-end-regexp (company-coq-make-headers-regexp '("End") company-coq-id-regexp)
"Regexp used to find section endings.")
(defcustom company-coq-search-blacklist '("Raw" "Proofs") ;; "_refl" "_sym" "_trans" "_ind" "_rec" "_rect"
"List of strings to add to Coq's search blacklist when loading completion candidates."
:group 'company-coq
:type '(repeat string))
(defconst company-coq-search-blacklist-str (mapconcat (lambda (str) (concat "\"" str "\""))
company-coq-search-blacklist " "))
(defconst company-coq-search-blacklist-add-cmd (concat "Add Search Blacklist "
company-coq-search-blacklist-str))
(defconst company-coq-search-blacklist-rem-cmd (concat "Remove Search Blacklist "
company-coq-search-blacklist-str))
(defconst company-coq-all-symbols-prelude (cons company-coq-search-blacklist-add-cmd
'("Set Search Output Name Only"))
"Commands to run before asking the prover for symbols.")
(defconst company-coq-redirection-template "Redirect \"%s\" %s")
(defconst company-coq-all-symbols-cmd "SearchPattern _"
"Command used to list all symbols.")
(defconst company-coq-all-ltacs-cmd "Print Ltac Signatures"
"Command used to list all tactics.")
(defconst company-coq-all-notations-cmd "Print Grammar tactic"
"Command used to list all tactic notations.")
(defvar company-coq-extra-symbols-cmd nil
"Command used to list extra symbols ([SearchPattern _] doesn't search inside modules in 8.4).")
(defconst company-coq-all-symbols-coda (cons company-coq-search-blacklist-rem-cmd
'("Unset Search Output Name Only"))
"Command to run after asking the prover for symbols.")
(defconst company-coq-doc-cmd "About %s"
"Command used to retrieve the documentation of a symbol.")
(defconst company-coq-def-cmd "Print %s"
"Command used to retrieve the definition of a symbol.")
(defconst company-coq-type-cmd "Check %s"
"Command used to retrieve the type of a symbol.")
(defconst company-coq-tactic-def-cmd "Print Ltac %s"
"Command used to retrieve the documentation of a tactic.")
(defconst company-coq-symbols-meta-cmd "Check @%s."
"Command used to retrieve a short description of a symbol.")
(defconst company-coq-modules-cmd "Print LoadPath."
"Command used to retrieve module path specs (for module name completion).")
(defconst company-coq-locate-lib-cmd "Locate Library %s."
"Command used to retrieve the qualified name of a library (to locate the corresponding source file).")
(defconst company-coq-locate-lib-output-format (replace-regexp-in-string
" " "[[:space:]]+"
(concat "\\`\\(" company-coq-module-name-regexp "\\)"
" \\(?:has been loaded from\\|is bound to\\) file "
"\\([^[:space:]]+\\)\\(\\.[^[:space:].]+\\)"))
"Regexp matching the output of `company-coq-locate-lib-cmd'.")
(defconst company-coq-compiled-regexp "\\.vi?o\\'"
"Regexp matching the extension of compiled Coq files.")
(defconst company-coq-end-of-def-regexp "\\(is\\|are\\) \\(recursively \\)?\\(defined\\|assumed\\|declared\\)"
"Regexp used to detect signs that new symbols have been defined.")
(defconst company-coq-error-regexps `("^Error:"
"^Syntax error:"
"^No object of basename"
"^Toplevel input, characters"
"^No Ltac definition is referred to by"
"^Unable to locate library"
"^The command has indeed failed with message:"
" not a defined object.")
"Regexps used to detect invalid output.")
(defconst company-coq-error-regexp (concat "\\(" (mapconcat #'identity company-coq-error-regexps "\\|") "\\)")
"Regexp used to detect invalid output.")
(defconst company-coq-import-regexp (regexp-opt '("Require" "Import" "Export"))
"Regexp used to detect signs that an import will be processed.")
(defconst company-coq-tac-notation-regexp (regexp-opt '("Tactic Notation"))
"Regexp used to detect signs that a tactic notation will be defined.")
(defconst company-coq-load-regexp "\\(LoadPath\\)"
"Regexp used to detect signs that new paths will be added to the load path.")
(defconst company-coq-doc-tagline "Documentation for symbol %s"
"Format string for the header of the documentation buffer.")
(defconst company-coq-doc-def-sep "\n---\n\n"
"Separation line between sections of the doc buffer.")
(defconst company-coq-dabbrev-to-yas-regexp "#\\|@{\\([^}]+\\)}"
"Regexp matching holes in abbrevs.")
(defconst company-coq-yasnippet-choice-regexp "\\${\\([a-z]+\\( | [a-z]+\\)+\\)}"
"Regexp matching alternatives in abbrevs.")
(defconst company-coq-section-kwds '("Chapter" "Module" "Module Type" "Section")
"Keywords opening a new section.")
(defconst company-coq-named-outline-kwds `("Equations" "Remark" "End"
"Add" ;; Add (Parametric)? Morphism
,@company-coq-section-kwds ,@company-coq-definitions-kwds)
"Headers used in outline mode and in `company-coq-occur'.")
(defconst company-coq-anonymous-outline-kwds
'("Goal" "Notation" "Tactic Notation" "Hint" "Hint Constructors" "Hint Cut"
"Hint Extern" "Hint Local" "Hint Rewrite" "Hint Unfold" "Hint Immediate"
"Hint Resolve")
"Extra headers to show in outline mode and in `company-coq-occur'.")
(defconst company-coq-section-regexp (company-coq-make-headers-regexp company-coq-section-kwds
company-coq-id-regexp)
"Regexp matching section openings.")
;; NOTE: Would be nice to fold [Require Import]s together instead of hiding them entirely
(defconst company-coq-outline-regexp-base
(concat "\\(?:" (company-coq-make-headers-regexp company-coq-named-outline-kwds company-coq-id-regexp) "\\)" "\\|"
"\\(?:" (company-coq-make-headers-regexp company-coq-anonymous-outline-kwds nil) "\\)")
"Regexp matching terms to show in outline mode and in `company-coq-occur'.")
(defconst company-coq-outline-regexp
;; Include preceeding blank space, if any.
(concat "\\(?:" "\n?" company-coq-outline-regexp-base "\\)"))
(defun company-coq-outline-level ()
"Determine the current outline level (always 0)."
0)
(defconst company-coq-outline-heading-end-regexp "\\.[ \t\n]"
"Regexp used to locate the end of a heading.")
(defcustom company-coq-prettify-symbols-alist '(;; Disabled
;; ("*" . ?×) ; Inconsistent (‘intros H *’, rewrite in *, etc.)
;; ("~" . ?¬) ; Too invasive
;; ("+-" . ?±) ; Too uncommon
;; ("++" . ?⧺) ; Not present in TeX fonts
;; ("nat" . ?𝓝) ("Prop" . ?𝓟) ; Rather uncommon
;; ("N" . ?ℕ) ("Z" . ?ℤ) ("Q" . ?ℚ) ; Too invasive
;; Core Coq symbols
("|-" . ?⊢) ("||" . ?‖) ("/\\" . ?∧) ("\\/" . ?∨)
("->" . ?→) ("<-" . ?←) ("<->" . ?↔) ("=>" . ?⇒)
("<=" . ?≤) (">=" . ?≥) ("<>" . ?≠)
("True" . ?⊤) ("False" . ?⊥)
("fun" . ?λ) ("forall" . ?∀) ("exists" . ?∃)
("nat" . ?ℕ) ("Prop" . ?ℙ) ("Real" . ?ℝ) ("bool" . ?𝔹)
;; Extra symbols
(">->" . ?↣)
("-->" . ?⟶) ("<--" . ?⟵) ("<-->" . ?⟷)
("==>" . ?⟹) ("<==" . ?⟸) ("~~>" . ?⟿) ("<~~" . ?⬳))
"An alist of symbols to prettify.
Assigned to `prettify-symbols-alist' in Emacs >= 24.4."
:group 'company-coq
:type 'alist)
(defcustom company-coq-local-symbols nil
"An alist of file-specific symbols to prettify.
Combined with `company-coq-prettify-symbols-alist' when loading
the file. Most useful as a file-local variable."
:group 'company-coq
:type 'alist
:safe 'listp)
(defcustom company-coq-dir-local-symbols nil
"An alist of directory-specific symbols to prettify.
Combined with `company-coq-prettify-symbols-alist' when loading
the file. Most useful as a dir-local variable."
:group 'company-coq
:type 'alist
:safe 'listp)
(defcustom company-coq-completion-predicate #'company-coq-in-code-p
"Function called before offering company-coq completions, or nil.
If nil, offer company-coq candidates everywhere. If set to
`company-coq-not-in-comment-p', offer completions in source code,
but never in comments. If set to `company-coq-in-code-p', offer
completion in source code, in code blocks in comments […], but
not in comment text. This function should not change the point."
:group 'company-coq
:type '(choice (const :tag "Complete in code and code comments" company-coq-in-code-p)
(const :tag "Complete only in code" company-coq-not-in-comment-p)
(const :tag "Offer completions everywhere" nil)))
(defun company-coq--in-comment-p (&optional point)
"Check if POINT is in a comment."
(nth 4 (syntax-ppss (or point (point)))))
(defun company-coq--looking-at-comment ()
"Return non-nil if point is inside a comment."
(or (company-coq--in-comment-p (point))
(company-coq--in-comment-p (1+ (point)))))
(defun company-coq-not-in-comment-p ()
"Return nil if point is inside a comment.
Useful as a value for `company-coq-completion-predicate'"
(not (company-coq--looking-at-comment)))
(defconst company-coq--notations-header
(regexp-opt '("Infix" "Notation" "Tactic Notation" "Reserved Notation") 'symbols)
"Regexp for keywords introducing notations.")
(defun company-coq--in-notation-string-1 (pp)
"Use PP to check if point in in a “Notation” string.
That is, return non-nil in any string between “^Tactic? Notation”
and “:=”. PP should be the result of calling `syntax-ppss' on
point."
(and (nth 3 pp) ;; In a string
(save-excursion
(save-match-data
(let ((bol (point-at-bol)))
(and (not (re-search-backward "[^\"]:=" bol t))
(progn (goto-char bol)
(looking-at company-coq--notations-header))))))))
(defun company-coq--in-escaped-code-block-p (comment-beg)
"Check if point is in a code block.
Point is assumed to be in a comment starting at COMMENT-BEG."
(save-excursion
(skip-chars-backward "^[]" (max comment-beg (point-at-bol)))
(eq (char-before (point)) ?\[)))
(defun company-coq--in-code-p-1 (pp)
"Helper for `company-coq--in-code-p'.
PP is the result of calling `syntax-ppss' on point."
(let* ((in-comment-p (nth 4 pp))
(comment-or-str-beg (nth 8 pp)))
(or (not comment-or-str-beg) ;; In code
(and in-comment-p ;; Or in a code block comment
(company-coq--in-escaped-code-block-p comment-or-str-beg)))))
(defun company-coq-in-code-p ()
"Return non-nil if point is in code context.
Code contexts are portions of the buffer outside comments and
strings, and code blocks in comments. Thus this function returns
nil in “(* abc| ”, but t in “(* abc [p| ”.
Useful as a value for `company-coq-completion-predicate'."
(company-coq--in-code-p-1 (syntax-ppss)))
(defalias 'company-coq-not-in-comment-text-or-string-p 'company-coq-in-code-p)
(defconst company-coq-unification-error-header
"\\(?:The command has indeed failed with message:\\|Error:\\|In environment.*?\\)"
"Header of unification errors.")
(defconst company-coq-unification-error-quick-regexp
(regexp-opt '("Refiner was given an argument"
"Unable to unify"
"Impossible to unify"
"it is expected to have type"))
"Fast regexp to check if current response is a unification error.")
(defconst company-coq-unification-error-messages
'("Refiner was given an argument \".*\" of type \"\\(?1:.*\\)\" instead of \"\\(?2:.*\\)\"."
"Unable to unify \"\\(?1:.*\\)\" with \"\\(?2:.*\\)\"."
"Impossible to unify \"\\(?1:.*\\)\" with \"\\(?2:.*\\)\"."
"The term \".*\" has type \"\\(?1:.*\\)\" while it is expected to have type \"\\(?2:.*\\)\".")
"Bodies of unification errors.")
(defconst company-coq-unification-error-message
(replace-regexp-in-string
(regexp-quote ".") (replace-quote "\\(?:.\\|[\n]\\)")
(replace-regexp-in-string
"[ \n]" (replace-quote "\\s-*")
(concat "\\(?:" company-coq-unification-error-header " \\)+" "\\(?:"
(mapconcat #'identity company-coq-unification-error-messages "\\|")
"\\)\\s-*\\(?:" "(cannot unify \"\\(?3:.*\\)\" and \"\\(?4:.*\\)\")." "\\)?")))
"Rexep matching unification error messages.")
(defconst company-coq-deprecated-options '("Equality Scheme" "Record Elimination Schemes"
"Tactic Evars Pattern Unification" "Undo")
"Deprecated options, as reported by [Print Tables].")
(defconst company-coq-options-header-re (regexp-opt '("Set " "Unset " "Test "))
"Regexp matching keywords starting option-related vernacs.")
(defconst company-coq-deprecated-options-re (concat "\\(?1:" company-coq-options-header-re
(regexp-opt company-coq-deprecated-options) "\\)")
"Regexp matching uses of deprecated options.")
(defconst company-coq-deprecated-vernacs-re (concat "\\(?1:" (regexp-opt '("Include Type"
"Arguments Scope"
"Implicit Arguments")) "\\)")
"Regexp matching uses of deprecated vernacs.")
(defconst company-coq-deprecated-man-re
(mapconcat (lambda (x) (concat "\\(?:\\_<" x "\\)"))
'("\\(?1:assert\\) ([a-zA-Z_]+ ?:= .*)" "\\(?1:double induction\\)"
"\\(?1:appcontext\\_>\\)[ a-zA-Z]*\\[" "\\(?1:cutrewrite\\) \\(?:<-\\|->\\)"
"\\(?1:Backtrack [[:digit:]]+ [[:digit:]]+ [[:digit:]]+\\)" "\\(?1:SearchAbout\\_>\\)"
"\\(?1:Save\\_>\\(?: \\(?:Lemma\\|Theorem\\|Remark\\|Fact\\|Corollary\\|Proposition\\)\\_>\\)?\\)"
"\\(?1:absurd_hyp\\_>\\) [A-Za-z]")
"\\|")
"Regexp matching deprecating forms described by the manual.")
(defconst company-coq-deprecated-re (concat "^[[:blank:]]*\\(?:"
"\\(?:" company-coq-deprecated-options-re "\\)\\|"
"\\(?:" company-coq-deprecated-vernacs-re "\\)\\|"
"\\(?:" company-coq-deprecated-man-re "\\)"
"\\)")
"Regexp matching all deprecated forms.")
(defvar company-coq--reserved-keywords-regexp nil
"Regexp matching Coq's reserved keywords.")
(defun company-coq--reserved-keywords-regexp ()
"Construct and cache a regexp matching Coq's reserved keywords."
(or company-coq--reserved-keywords-regexp
(setq company-coq--reserved-keywords-regexp
(concat "^" (regexp-opt (append coq-reserved '("Set" "Prop" "Type"))) "$"))))
(defconst company-coq--doc-buffer "*company-coq: documentation*"
"Name to give to company-coq documentation buffers.")
(defconst company-coq--goal-diff-buffer "*goal-diff*"
"Name to give to company-coq goal diff buffers.")
(defconst company-coq--unification-diff-buffer "*unification-diff*"
"Name to give to company-coq unification diff buffers.")
(defconst company-coq-script-full-path
(or (and load-in-progress load-file-name)
(bound-and-true-p byte-compile-current-file)
(buffer-file-name))
"Full path of this script.")
(defconst company-coq-refman-path
(when company-coq-script-full-path
(expand-file-name "refman/" (file-name-directory company-coq-script-full-path)))
"Refman (and other assets)'s directory.")
(defface company-coq-doc-header-face-docs-and-sources
'((t :height 1.5 :weight bold))
"Face used to highlight the target line in source view."
:group 'company-coq-faces)
(defface company-coq-doc-header-face-about
'((t :inherit highlight :height 1.2))
"Face used to highlight the target line in the docs."
:group 'company-coq-faces)
(defface company-coq-doc-tt-face
'((t :inherit font-lock-keyword-face :weight bold))
"Face used to highlight keywords in the docs."
:group 'company-coq-faces)
(defface company-coq-doc-i-face
'((t :inherit font-lock-variable-name-face :weight bold :slant italic))
"Face used to highlight symbol names in the docs."
:group 'company-coq-faces)
(defface company-coq-comment-h1-face
'((t :inherit font-lock-doc-face :height 2.5))
"Face used to highlight *** comments."
:group 'company-coq-faces)
(defface company-coq-comment-h2-face
'((t :inherit font-lock-doc-face :height 1.8))
"Face used to highlight *+ comments."
:group 'company-coq-faces)
(defface company-coq-comment-h3-face
'((t :inherit font-lock-doc-face :height 1.2))
"Face used to highlight *! comments."
:group 'company-coq-faces)
(defface company-coq-coqdoc-h1-face
'((t :inherit font-lock-doc-face :inverse-video t :weight black))
"Face used to highlight coqdoc's * comments."
:group 'company-coq-faces)
(defface company-coq-coqdoc-h2-face
'((t :inherit font-lock-doc-face :weight bold))
"Face used to highlight coqdoc's ** comments."
:group 'company-coq-faces)
(defface company-coq-coqdoc-h3-face
'((t :inherit font-lock-doc-face :slant italic))
"Face used to highlight coqdoc's *** comments."
:group 'company-coq-faces)
(defface company-coq-coqdoc-h4-face
'((t :inherit font-lock-doc-face))
"Face used to highlight coqdoc's **** comments."
:group 'company-coq-faces)
(defface company-coq-goal-separator-face
'((((supports :strike-through t)) :strike-through t)
(t :underline t))
"Face used to highlight the goal line."
:group 'company-coq-faces)
(defconst company-coq-goal-separator-spec
`(("^ *\\(=====+ *\\)$"
1 '(face company-coq-goal-separator-face display (space :align-to right)) append))
"Font-lock spec for a sequence of '=' signs.")
(defconst company-coq-deprecated-spec
`((,company-coq-deprecated-re 1 '(face (:underline (:color "#FF0000" :style wave))
help-echo "This form is deprecated (8.5)")
append))
"Font-lock spec for deprecated forms.")
(defmacro company-coq-dbg (format &rest args)
"Call `message' with FORMAT and ARGS if `company-coq-debug' is non-nil."
`(when company-coq-debug
(message (concat "company-coq: " ,format) ,@args)))
(defmacro company-coq-suppress-warnings (&rest body)
"Run BODY, suppressing compilation warnings in Emacs <= 24.4."
(declare (indent 0)
(debug t))
(if (and (= emacs-major-version 24) (< emacs-minor-version 4))
`(with-no-warnings ,@body)
`(progn ,@body)))
(defun company-coq--last-output-without-eager-annotation-markers ()
"Return `proof-shell-last-output', without eager annotation markers.
Normally PG strips eager annotations, but
`company-coq-ask-prover' turns that mechanism off to not loose
output."
(when proof-shell-last-output
(if (or proof-shell-eager-annotation-start
proof-shell-eager-annotation-end)
(replace-regexp-in-string
(concat "\\(?:" (or proof-shell-eager-annotation-start "") "\\)"
"\\(?1:[^0]+\\)"
"\\(?:" (or proof-shell-eager-annotation-end "") "\\)")
"\\1" proof-shell-last-output t)
proof-shell-last-output)))
(defun company-coq-trim (str)
"Trim STR."
(replace-regexp-in-string "\\`[ \r\n\t]+\\|[ \r\n\t]+\\'" "" str t t))
(defun company-coq-ask-prover (question)
"Synchronously send QUESTION to the prover.
This function attemps to preserve the offsets of the
goals and response windows."
(when question
(if (company-coq-prover-available-p)
(progn
(setq company-coq-talking-to-prover t)
(unwind-protect
;; `save-window-excursion' is still needed to restore any buffer
;; that might have been show instead of the goals or the response
;; (the fix to PG doesn't prevent it from restoring the window
;; configuration, and anyway the fix isn't deployed to everyone)
(save-window-excursion
;; Coq-mode intercepts <infomsg>s using eager-annotation-start,
;; but it shouldn't.
(let* ((proof-shell-eager-annotation-start nil)
(proof-shell-eager-annotation-end nil))
;; proof-shell-invisible-cmd-get-result does not pass the
;; 'no-goals-display flag, causing the goals buffer to jitter.
(proof-shell-invisible-command question 'wait nil
'no-response-display
'no-error-display
'no-goals-display))
(company-coq-trim (company-coq--last-output-without-eager-annotation-markers)))
(setq company-coq-talking-to-prover nil)))
(company-coq-dbg "Prover not available; [%s] discarded" question)
nil)))
(defun company-coq-error-message-p (msg)
"Check if MSG is an error message."
(and msg (string-match-p company-coq-error-regexp msg)))
(defun company-coq-unless-error (str)
"Return STR, unless STR is an error message."
(unless (company-coq-error-message-p str)
str))
(defun company-coq-ask-prover-swallow-errors (question)
"Call `company-coq-ask-prover' with QUESTION, swallowing errors.
Since the caller seems to be ok with this erroring out, we seize
the opportunity and wrap this in [Timeout 1] on Unixes."
(unless (memq system-type '(cygwin windows-nt ms-dos))
(setq question (format "Timeout 1 %s" question)))
(company-coq-unless-error (company-coq-ask-prover question)))
(defun company-coq-split-lines (str &optional omit-nulls)
"Split lines of STR.
If OMIT-NULLS is non-nil, remove empty strings from resulting list."
(when str
(split-string str "\n" omit-nulls)))
(defun company-coq-split-wrapped-lines (str &optional omit-nulls)
"Unwrap STR and split it into lines.
If OMIT-NULLS is non-nil, remove empty strings from resulting list."
(when str
(let ((unwrapped (replace-regexp-in-string "\n +" " " str)))
(company-coq-split-lines unwrapped omit-nulls))))
(defun company-coq-looking-back (regexp limit)
"A greedy version of `looking-back'.
REGEXP and LIMIT are as in `looking-back'."
(save-excursion
(save-restriction
(narrow-to-region limit (point))
(goto-char limit)
(re-search-forward (concat "\\(?:" regexp "\\)\\'") nil t))))
(defun company-coq-text-width (from to)
"Measure the width of the text between FROM and TO.
Results are meaningful only if FROM and TO are on the same line."
;; (current-column) takes prettification into account
(- (save-excursion (goto-char to) (current-column))
(save-excursion (goto-char from) (current-column))))
(defun company-coq-max-line-length ()
"Return the width of the longest line in the current buffer."
(save-excursion
(goto-char (point-min))
(cl-loop maximize (company-coq-text-width (point-at-bol) (point-at-eol))
until (eobp) do (forward-line 1))))
(defun company-coq-truncate-buffer (start n-lines &optional ellipsis)
"Truncate current buffer N-LINES after START.
Optionally adds an ELLIPSIS at the end."
(cl-assert (and n-lines (> n-lines 0)))
(save-excursion
(goto-char start)
(forward-line n-lines)
(unless (eobp)
(delete-region (point) (point-max))
(forward-line -1)
(goto-char (point-at-eol))
(insert (or ellipsis " …")))))
(defun company-coq-prefix-all-lines (prefix)
"Add a PREFIX to all lines of the current buffer."
(save-excursion
(goto-char (point-min))
(while (not (eobp))
(insert prefix)
(forward-line 1))))
(defun company-coq-insert-spacer (pos)
"Insert a thin horizontal line at POS."
(save-excursion
(goto-char pos)
(let* ((from (point))
(to (progn (insert "\n") (point)))
(color (or (face-attribute 'highlight :background) "black")))
(add-text-properties from to `(face (:height 1 :background ,color :extend t))))))
(defun company-coq-get-header (str)
"Extract contents of STR, until the first blank line."
(save-match-data
(let ((header-end (and (string-match "\n\\s-*\\(\n\\|\\'\\)" str) (match-beginning 0))))
(substring-no-properties str 0 header-end))))
(defun company-coq-boundp-string-match-p (regexp symbol)
"Match REGEXP against SYMBOL.
If SYMBOL is undefined or nil, return nil."
(and (boundp symbol)
(symbol-value symbol)
(string-match regexp (symbol-value symbol))))
(defun company-coq-boundp-equal (var symbol)
"Check that VAR is defined, and compare its value to SYMBOL."
(and (boundp var) (equal (symbol-value var) symbol)))