forked from ocaml/tuareg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tuareg.el
4117 lines (3796 loc) · 172 KB
/
tuareg.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
;;; tuareg.el --- OCaml mode -*- coding: utf-8; lexical-binding:t -*-
;; Copyright (C) 1997-2006 Albert Cohen, all rights reserved.
;; Copyright (C) 2011-2022 Free Software Foundation, Inc.
;; Copyright (C) 2009-2010 Jane Street Holding, LLC.
;; Licensed under the GNU General Public License.
;; Author: Albert Cohen <Albert.Cohen@inria.fr>
;; Sam Steingold <sds@gnu.org>
;; Christophe Troestler <Christophe.Troestler@umons.ac.be>
;; Till Varoquaux <till@pps.jussieu.fr>
;; Sean McLaughlin <seanmcl@gmail.com>
;; Stefan Monnier <monnier@iro.umontreal.ca>
;; Maintainer: Christophe Troestler <Christophe.Troestler@umons.ac.be>
;; Stefan Monnier <monnier@iro.umontreal.ca>
;; Created: 8 Jan 1997
;; Version: 2.3.0
;; Package-Requires: ((emacs "24.4") (caml "4.8"))
;; Keywords: ocaml languages
;; Homepage: https://github.com/ocaml/tuareg
;; EmacsWiki: TuaregMode
;;; Commentary:
;; Tuareg helps editing OCaml code, to highlight important parts of
;; the code, to run an OCaml REPL, and to run the OCaml debugger
;; within Emacs.
;; See https://github.com/ocaml/tuareg for customization tips.
;;; Installation:
;; If you have permissions to the local `site-lisp' directory, you
;; only have to copy `tuareg.el', `ocamldebug.el'
;; and `tuareg-site-file.el'. Otherwise, copy the previous files
;; to a local directory and add the following line to your `.emacs':
;;
;; (add-to-list 'load-path "DIR")
;;; Usage:
;; Tuareg allows you to run batch OCaml compilations from Emacs (using
;; M-x compile) and browse the errors (C-x `). Typing C-x ` sets the
;; point at the beginning of the erroneous program fragment, and the
;; mark at the end. Under Emacs, the program fragment is temporarily
;; hilighted.
;;
;; M-x tuareg-run-ocaml (or simply `run-ocaml') starts an OCaml
;; REPL (aka toplevel) with input and output in an Emacs buffer named
;; `*OCaml*. This gives you the full power of Emacs to edit
;; the input to the OCaml REPL. This mode is based on comint so
;; you get all the usual comint features, including command history. A
;; hook named `tuareg-interactive-mode-hook' may be used for
;; customization.
;;
;; Typing C-c C-e in a buffer in tuareg mode sends the current phrase
;; (containing the point) to the OCaml REPL, and evaluates it. If
;; you type one of these commands before M-x tuareg-run-ocaml, the
;; REPL will be started automatically.
;;
;; M-x ocamldebug FILE starts the OCaml debugger ocamldebug on the
;; executable FILE, with input and output in an Emacs buffer named
;; *ocamldebug-FILE*. It is similar to April 1996 version, with minor
;; changes to support XEmacs, Tuareg and OCaml. Furthermore, package
;; `thingatpt' is not required any more.
;; This file is *NOT* part of GNU Emacs.
;; 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 <https://www.gnu.org/licenses/>.
;;; Code:
(eval-when-compile (require 'cl-lib))
(require 'easymenu)
(require 'find-file)
(require 'subr-x)
(require 'caml-help nil t)
(require 'caml-types nil t)
(require 'tuareg-opam)
(require 'tuareg-compat)
(defconst tuareg-mode-revision
(eval-when-compile
(with-temp-buffer
(if (file-directory-p ".git")
(progn
(insert "git: ")
(call-process "git" nil t nil "log" "--pretty=%h" "-1")))
(unless (zerop (buffer-size))
(buffer-substring-no-properties
(point-min) (1- (point-max))))))
"Tuareg revision from the control system used.")
(defconst tuareg-mode-version
(let ((version (or (if (fboundp 'package-get-version)
(package-get-version))
"2.3.0")))
(concat "Tuareg Version " version
(when tuareg-mode-revision
(concat " (" tuareg-mode-revision ")"))))
;; FIXME: Do we really want to have this copy of the license blurb
;; as the docstring?
" Copyright (C) 1997-2006 Albert Cohen, all rights reserved.
Copyright (C) 2009-2010 Jane Street Holding, LLC.
Copyright (C) 2011- Stefan Monnier & Christophe Troestler
Copying is covered by the GNU General Public License.
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.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Compatibility functions
(defun tuareg-editing-ls3 ()
"Tell whether we are editing Lucid Synchrone syntax."
(string-match-p "\\.ls\\'" (or buffer-file-name (buffer-name))))
(defun tuareg-editing-ocamllex ()
"Tell whether we are editing OCamlLex syntax."
(string-match-p "\\.mll\\'" (or buffer-file-name (buffer-name))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Import types and help features
(defvar tuareg-with-caml-mode-p
(and (featurep 'caml-types) (featurep 'caml-help)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; User customizable variables
(require 'smie)
;; Use the standard `customize' interface or `tuareg-mode-hook' to
;; Configure these variables
(require 'custom)
(defgroup tuareg nil
"Support for the OCaml language."
:link '(url-link "https://github.com/ocaml/tuareg")
:group 'languages)
;; Indentation defaults
(defcustom tuareg-default-indent 2
"*Default indentation.
Global indentation variable (large values may lead to indentation overflows).
When no governing keyword is found, this value is used to indent the line
if it has to."
:group 'tuareg :type 'integer)
(defcustom tuareg-support-camllight nil
"*If true, handle Caml Light character syntax (incompatible with labels)."
:group 'tuareg :type 'boolean
:set (lambda (var val)
(set-default var val)
(when (boundp 'tuareg-mode-syntax-table)
(modify-syntax-entry ?` (if val "\"" ".")
tuareg-mode-syntax-table))))
(defcustom tuareg-support-metaocaml nil
"*If true, handle MetaOCaml syntax."
:group 'tuareg :type 'boolean
:set (lambda (var val)
(set-default var val)
(ignore-errors
(dolist (buf (buffer-list))
(with-current-buffer buf
(when (derived-mode-p 'tuareg-mode 'tuareg-interactive-mode)
(tuareg--install-font-lock)))))))
(defcustom tuareg-in-indent 0 ; tuareg-default-indent
"*How many spaces to indent from a `in' keyword.
Upstream <http://caml.inria.fr/resources/doc/guides/guidelines.en.html>
recommends 0, and this is what we default to since 2.0.1
instead of the historical `tuareg-default-indent'."
:group 'tuareg :type 'integer)
(defcustom tuareg-with-indent 0
"*How many spaces to indent from a `with' keyword.
The examples at <http://caml.inria.fr/resources/doc/guides/guidelines.en.html>
show the `|' is aligned with `match', thus 0 is the default value."
:group 'tuareg :type 'integer)
(defcustom tuareg-match-clause-indent 1
"*How many spaces to indent a clause of match after a pattern `| ... ->'
or `... ->' (pattern without preceding `|' in the first clause of a matching).
To respect <http://caml.inria.fr/resources/doc/guides/guidelines.en.html>
the default is 1."
:type 'integer)
(defcustom tuareg-match-when-indent (+ 4 tuareg-match-clause-indent)
"*How many spaces from `|' to indent `when' in a pattern match
| patt
when cond ->
clause"
:type 'integer)
(defcustom tuareg-match-patterns-aligned nil
"Non-nil means that the pipes for multiple patterns of a single case
are aligned instead of being slightly shifted to spot the multiple
patterns better.
function v.s. function
| A | A
| B -> ... | B -> ...
| C -> ... | C -> ... "
:group 'tuareg :type 'boolean)
;; Tuareg-Interactive
;; Configure via `tuareg-mode-hook'
;; Automatic indentation
(make-obsolete-variable 'tuareg-use-abbrev-mode
"Use `electric-indent-mode' instead." "2.2.0")
(defcustom tuareg-electric-indent nil
"Whether to automatically indent the line after typing one of
the words in `tuareg-electric-indent-keywords'. Lines starting
with `|', `)', `]`, and `}' are always indented when the
`electric-indent-mode' is turned on."
:group 'tuareg :type 'boolean)
(defcustom tuareg-electric-close-vector t
"*Non-nil means electrically insert `|' before a vector-closing `]' or
`>' before an object-closing `}'.
Many people find electric keys irritating, so you can disable them by
setting this variable to nil. You should probably have this on,
though, if you also have `tuareg-electric-indent' on."
:group 'tuareg :type 'boolean)
(defcustom tuareg-highlight-all-operators nil
"If t, highlight all operators (as opposed to unusual ones).
This is not turned on by default because this makes font-lock
much less efficient."
:group 'tuareg :type 'boolean)
(defcustom tuareg-other-file-alist
'(("\\.\\(?:pp\\.\\)?mli\\'" (".ml" ".mll" ".mly" ".pp.ml"))
("\\.\\(?:pp\\.\\)?ml\\'" (".mli"))
("\\.mll\\'" (".mli"))
("\\.mly\\'" (".mli"))
("\\.eliomi\\'" (".eliom"))
("\\.eliom\\'" (".eliomi")))
"Associative list of alternate extensions to find.
See `ff-other-file-alist'."
:group 'tuareg
:type '(repeat (list regexp (choice (repeat string) function))))
(defcustom tuareg-comment-show-paren t
"Highlight comment delimiters in `show-paren-mode' if non-nil."
:group 'tuareg
:type 'boolean)
(defcustom tuareg-interactive-scroll-to-bottom-on-output nil
"*Controls when to scroll to the bottom of the interactive buffer
upon evaluating an expression.
See `comint-scroll-to-bottom-on-output' for details."
:group 'tuareg :type 'boolean
:set (lambda (var val)
(set-default var val)
(when (boundp 'comint-scroll-to-bottom-on-output)
(dolist (buf (buffer-list))
(with-current-buffer buf
(when (derived-mode-p 'tuareg-interactive-mode)
(setq-local comint-scroll-to-bottom-on-output val)))))))
(defcustom tuareg-skip-after-eval-phrase t
"*Non-nil means skip to the end of the phrase after evaluation in the
OCaml REPL."
:group 'tuareg :type 'boolean)
(defcustom tuareg-interactive-read-only-input nil
"*Non-nil means input sent to the OCaml REPL is read-only."
:group 'tuareg :type 'boolean)
(defcustom tuareg-interactive-echo-phrase t
"*Non-nil means echo phrases in the REPL buffer when sending
them to the OCaml REPL."
:group 'tuareg :type 'boolean)
(defcustom tuareg-interactive-input-font-lock t
"*Non nil means Font-Lock for REPL input phrases."
:group 'tuareg :type 'boolean)
(defcustom tuareg-interactive-output-font-lock t
"*Non nil means Font-Lock for REPL output messages."
:group 'tuareg :type 'boolean)
(defcustom tuareg-interactive-error-font-lock t
"*Non nil means Font-Lock for REPL error messages."
:group 'tuareg :type 'boolean)
(defcustom tuareg-display-buffer-on-eval t
"*Non nil means pop up the OCaml REPL when evaluating code."
:group 'tuareg :type 'boolean)
(defcustom tuareg-manual-url
"http://caml.inria.fr/pub/docs/manual-ocaml/"
"*URL to the OCaml reference manual."
:group 'tuareg :type 'string)
(defcustom tuareg-browser 'browse-url
"*Name of function that displays the OCaml reference manual.
Valid names are `browse-url', `browse-url-firefox', etc."
:group 'tuareg :type 'function)
(defcustom tuareg-library-path "/usr/local/lib/ocaml/"
"*Path to the OCaml library."
:group 'tuareg :type 'string)
(defvar tuareg-options-list
`(["Prettify symbols" prettify-symbols-mode
:style toggle :selected prettify-symbols-mode :active t])
"*List of menu-configurable Tuareg options.")
(defvar tuareg-interactive-options-list
'(("Skip phrase after evaluation" . 'tuareg-skip-after-eval-phrase)
("Echo phrase in interactive buffer" . 'tuareg-interactive-echo-phrase)
"---"
("Font-lock interactive input" . 'tuareg-interactive-input-font-lock)
("Font-lock interactive output" . 'tuareg-interactive-output-font-lock)
("Font-lock interactive error" . 'tuareg-interactive-error-font-lock)
"---"
("Read only input" . 'tuareg-interactive-read-only-input))
"*List of menu-configurable Tuareg options.")
(defvar tuareg-interactive-program "ocaml -nopromptcont"
"*Default program name for invoking an OCaml REPL (aka toplevel) from Emacs.")
;; Could be interesting to have this variable buffer-local
;; (e.g., ocaml vs. metaocaml buffers)
;; (make-variable-buffer-local 'tuareg-interactive-program)
(defgroup tuareg-faces nil
"Special faces for the Tuareg mode."
:group 'tuareg)
(defface tuareg-font-lock-governing-face
'((((class color) (type tty)) (:bold t))
(((background light)) (:foreground "black" :bold t))
(t (:foreground "wheat" :bold t)))
"Face description for governing/leading keywords."
:group 'tuareg-faces)
(defvar tuareg-font-lock-governing-face
'tuareg-font-lock-governing-face)
(defface tuareg-font-lock-multistage-face
'((((background light))
(:foreground "darkblue" :background "lightgray" :bold t))
(t (:foreground "steelblue" :background "darkgray" :bold t)))
"Face description for MetaOCaml staging operators."
:group 'tuareg-faces)
(defvar tuareg-font-lock-multistage-face
'tuareg-font-lock-multistage-face)
(defface tuareg-font-lock-line-number-face
'((((background light)) (:foreground "dark gray"))
(t (:foreground "gray60")))
"Face description for line numbering directives."
:group 'tuareg-faces)
(defvar tuareg-font-lock-line-number-face
'tuareg-font-lock-line-number-face)
(defface tuareg-font-lock-operator-face
'((((background light)) (:foreground "brown"))
(t (:foreground "khaki")))
"Face description for all operators."
:group 'tuareg-faces)
(defvar tuareg-font-lock-operator-face
'tuareg-font-lock-operator-face)
(defface tuareg-font-lock-module-face
'((t (:inherit font-lock-type-face))); backward compatibility
"Face description for modules and module paths."
:group 'tuareg-faces)
(defvar tuareg-font-lock-module-face
'tuareg-font-lock-module-face)
(defface tuareg-font-lock-constructor-face
'((t (:inherit default))) ;FIXME: Why not just nil?
"Face description for constructors of (polymorphic) variants and exceptions."
:group 'tuareg-faces)
(defvar tuareg-font-lock-constructor-face
'tuareg-font-lock-constructor-face)
(defface tuareg-font-lock-label-face
'((t (:inherit font-lock-constant-face keep)))
"Face description for labels."
:group 'tuareg-faces)
(defvar tuareg-font-lock-label-face
'tuareg-font-lock-label-face)
(defface tuareg-font-double-semicolon-face
'((t (:foreground "OrangeRed")))
"Face description for ;; which is not needed in standard code."
:group 'tuareg-faces)
(defvar tuareg-font-double-semicolon-face
'tuareg-font-double-semicolon-face)
(defface tuareg-font-lock-error-face
'((t (:foreground "yellow" :background "red" :bold t)))
"Face description for all errors reported to the source."
:group 'tuareg-faces)
(defvar tuareg-font-lock-error-face
'tuareg-font-lock-error-face)
(defface tuareg-font-lock-interactive-output-face
'((((background light))
(:foreground "blue4"))
(t (:foreground "grey")))
"Face description for all outputs in the REPL."
:group 'tuareg-faces)
(defvar tuareg-font-lock-interactive-output-face
'tuareg-font-lock-interactive-output-face)
(defface tuareg-font-lock-interactive-error-face
'((t :inherit font-lock-warning-face))
"Face description for all REPL errors."
:group 'tuareg-faces)
(defvar tuareg-font-lock-interactive-error-face
'tuareg-font-lock-interactive-error-face)
(defface tuareg-font-lock-interactive-directive-face
'((((background light)) (:foreground "slate gray"))
(t (:foreground "light slate gray")))
"Face description for all REPL directives such as #load."
:group 'tuareg-faces)
(defvar tuareg-font-lock-interactive-directive-face
'tuareg-font-lock-interactive-directive-face)
(defface tuareg-font-lock-attribute-face
'((t :inherit font-lock-preprocessor-face))
"Face description for OCaml attribute annotations."
:group 'tuareg-faces)
(defvar tuareg-font-lock-attribute-face
'tuareg-font-lock-attribute-face)
(defface tuareg-font-lock-infix-extension-node-face
'((t :inherit font-lock-preprocessor-face))
"Face description for OCaml the infix extension node."
:group 'tuareg-faces)
(defvar tuareg-font-lock-infix-extension-node-face
'tuareg-font-lock-infix-extension-node-face)
(defface tuareg-font-lock-extension-node-face
'((default :inherit tuareg-font-lock-infix-extension-node-face)
(((background dark)) :foreground "LightSteelBlue")
(t :background "gray92"))
"Face description for OCaml extension nodes."
:group 'tuareg-faces)
(defvar tuareg-font-lock-extension-node-face
'tuareg-font-lock-extension-node-face)
(defface tuareg-font-lock-doc-markup-face
`((t :inherit ,(if (facep 'font-lock-doc-markup-face)
'font-lock-doc-markup-face ; Emacs ≥28.
'font-lock-constant-face)))
"Face for mark-up syntax in OCaml doc comments."
:group 'tuareg-faces)
(defface tuareg-font-lock-doc-verbatim-face
'((t :inherit fixed-pitch)) ; FIXME: find something better
"Face for verbatim text in OCaml doc comments (inside {v ... v})."
:group 'tuareg-faces)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Support definitions
;; This function is different from the standard in that it does NOT signal
;; errors at beginning-of-buffer.
(defun tuareg-backward-char (&optional step)
(if step (goto-char (- (point) step))
(goto-char (1- (point)))))
(defun tuareg-in-indentation-p ()
"Return non-nil if all chars between beginning of line and point are blanks."
(save-excursion
(skip-chars-backward " \t")
(bolp)))
(defun tuareg-in-literal-or-comment-p (&optional pos)
"Return non-nil if point is inside an OCaml literal or comment."
(nth 8 (syntax-ppss pos)))
(defun tuareg--point-after-comment-p ()
"Return non-nil if a comment precedes the point."
(and (eq (char-before) ?\))
(eq (char-before (1- (point))) ?*) ; implies position is in range
(save-excursion
(nth 4 (syntax-ppss (1- (point)))))))
(defun tuareg-backward-up-list ()
;; FIXME: not clear if moving out of a string/comment should count as 1 or no.
(condition-case nil
(backward-up-list)
(scan-error (goto-char (point-min)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Font-lock in Emacs
;; Originally by Stefan Monnier
(defcustom tuareg-font-lock-symbols nil
"*Display fun and -> and such using symbols in fonts.
This may sound like a neat trick, but note that it can change the
alignment and can thus lead to surprises. On recent Emacs >= 24.4,
use `prettify-symbols-mode'."
:group 'tuareg :type 'boolean)
(make-obsolete-variable 'tuareg-font-lock-symbols
'prettify-symbols-mode "Emacs-24.4")
(defcustom tuareg-prettify-symbols-full nil
"If non-nil, add fun and -> and such to be prettified with symbols.
This may sound like a neat trick, but note that it can change the
alignment and can thus lead to surprises. By default, only symbols that
do not perturb in essential ways the alignment are used. See
`tuareg-prettify-symbols-basic-alist' and
`tuareg-prettify-symbols-extra-alist'."
:group 'tuareg :type 'boolean)
(defvar tuareg-prettify-symbols-basic-alist
`(("sqrt" . ?√)
("&&" . ?∧) ; 'LOGICAL AND' (U+2227)
("||" . ?∨) ; 'LOGICAL OR' (U+2228)
("+." . ?∔) ;DOT PLUS (U+2214)
("-." . ?∸) ;DOT MINUS (U+2238)
;;("*." . ?×)
("*." . ?∙) ; BULLET OPERATOR
("/." . ?÷)
("<-" . ?←)
("<=" . ?≤)
(">=" . ?≥)
("<>" . ?≠)
("==" . ?≡)
("!=" . ?≢)
("<=>" . ?⇔)
("infinity" . ?∞)
;; Some greek letters for type parameters.
("'a" . ?α)
("'b" . ?β)
("'c" . ?γ)
("'d" . ?δ)
("'e" . ?ε)
("'f" . ?φ)
("'i" . ?ι)
("'k" . ?κ)
("'m" . ?μ)
("'n" . ?ν)
("'o" . ?ω)
("'p" . ?π)
("'r" . ?ρ)
("'s" . ?σ)
("'t" . ?τ)
("'x" . ?ξ)))
(defvar tuareg-prettify-symbols-extra-alist
`(("fun" . ?λ)
("not" . ?¬)
;;("or" . ?∨); should not be used as ||
("[|" . ?〚) ;; 〚
("|]" . ?〛) ;; 〛
("->" . ?→)
(":=" . ?⇐)
("::" . ?∷)))
(defun tuareg--prettify-symbols-compose-p (start end match)
"Return true iff the symbol MATCH should be composed.
See `prettify-symbols-compose-predicate'."
;; Refine `prettify-symbols-default-compose-p' so as not to compose
;; symbols for errors,...
(and (fboundp 'prettify-symbols-default-compose-p)
(prettify-symbols-default-compose-p start end match)
(not (memq (get-text-property start 'face)
'(tuareg-font-lock-error-face
tuareg-font-lock-interactive-output-face
tuareg-font-lock-interactive-error-face)))))
(defun tuareg-font-lock-compose-symbol (alist)
"Compose a sequence of ascii chars into a symbol.
Regexp match data 0 points to the chars."
;; Check that the chars should really be composed into a symbol.
(let* ((mbegin (match-beginning 0))
(mend (match-end 0))
(syntax (char-syntax (char-after mbegin))))
(if (or (eq (char-syntax (or (char-before mbegin) ?\ )) syntax)
(eq (char-syntax (or (char-after mend) ?\ )) syntax)
(memq (get-text-property mbegin 'face)
'(font-lock-doc-face
font-lock-string-face
font-lock-comment-face
tuareg-font-lock-error-face
tuareg-font-lock-interactive-output-face
tuareg-font-lock-interactive-error-face)))
;; No composition for you. Let's actually remove any composition
;; we may have added earlier and which is now incorrect.
(remove-text-properties mbegin mend '(composition))
;; That's a symbol alright, so add the composition.
(compose-region mbegin mend (cdr (assoc (match-string 0) alist)))))
;; Return nil because we're not adding any face property.
nil)
(defun tuareg-font-lock-symbols-keywords ()
(let ((alist (if tuareg-prettify-symbols-full
(append tuareg-prettify-symbols-basic-alist
tuareg-prettify-symbols-extra-alist)
tuareg-prettify-symbols-basic-alist)))
(dolist (x alist)
(when (and (char-displayable-p (cdr x))
(not (assoc (car x) alist))) ; not yet in alist.
(push x alist)))
(when alist
`((,(regexp-opt (mapcar #'car alist) t)
(0 (tuareg-font-lock-compose-symbol ',alist)))))))
(defvar tuareg-mode-syntax-table
(let ((st (make-syntax-table)))
(modify-syntax-entry ?_ "_" st)
(modify-syntax-entry ?. "'" st) ;Make qualified names a single symbol.
(modify-syntax-entry ?# "." st)
(modify-syntax-entry ?? ". p" st)
(modify-syntax-entry ?~ ". p" st)
;; See http://caml.inria.fr/pub/docs/manual-ocaml/lex.html.
(dolist (c '(?! ?$ ?% ?& ?+ ?- ?/ ?: ?< ?= ?> ?@ ?^ ?|))
(modify-syntax-entry c "." st))
(modify-syntax-entry ?' "_" st) ; ' is part of symbols (for primes).
(modify-syntax-entry
;; ` is punctuation or character delimiter (Caml Light compatibility).
?` (if tuareg-support-camllight "\"" ".") st)
(modify-syntax-entry ?\" "\"" st) ; " is a string delimiter
(modify-syntax-entry ?\\ "\\" st)
(modify-syntax-entry ?* ". 23" st)
(modify-syntax-entry ?\( "()1n" st)
(modify-syntax-entry ?\) ")(4n" st)
st)
"Syntax table in use in Tuareg mode buffers.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Font-Lock
(defconst tuareg-font-lock-syntactic-keywords
;; Char constants start with ' but ' can also appear in identifiers.
;; Beware not to match things like '*)hel' or '"hel' since the first '
;; might be inside a string or comment.
;; Note: for compatibility with Emacs<23, we use "\\<" rather than "\\_<",
;; which depends on tuareg-font-lock-syntax turning all "_" into "w".
'(("\\<\\('\\)\\([^'\\\n]\\|\\\\.[^\\'\n \")]*\\)\\('\\)"
(1 '(7)) (3 '(7)))))
(defun tuareg-syntax-propertize (start end)
(goto-char start)
(tuareg--syntax-quotation end)
(funcall
(syntax-propertize-rules
;; When we see a '"', knowing whether it's a literal char (as opposed to
;; the end of a string followed by the beginning of a literal char)
;; requires checking syntax-ppss as in:
;; ("\\_<\\('\"'\\)"
;; (1 (unless (nth 3 (save-excursion (syntax-ppss (match-beginning 0))))
;; (string-to-syntax "\""))))
;; Not sure if it's worth the trouble since adding a space between the
;; string and the literal char is easy enough and is the usual
;; style anyway.
;; For all other cases we don't need to check syntax-ppss because, if the
;; first quote is within a string (or comment), the whole match is within
;; the string (or comment), so the syntax-properties don't hurt.
;;
;; Note: we can't just use "\\<" here because syntax-propertize is also
;; used outside of font-lock.
("\\_<\\('\\)\\(?:[^'\\\n]\\|\\\\.[^\\'\n \")]*\\)\\('\\)"
(1 "\"") (2 "\""))
("\\({\\)[a-z_]*|"
(1 (prog1 "|" (tuareg--syntax-quotation end))))
)
(point) end))
(defun tuareg--syntax-quotation (end)
(let ((ppss (syntax-ppss)))
(when (eq t (nth 3 ppss))
(pcase (char-after (nth 8 ppss))
(`?<
;; We're indeed inside a quotation.
(when (re-search-forward ">>" end 'move)
(put-text-property (1- (point)) (point)
'syntax-table (string-to-syntax "|"))))
(`?\{
;; We're inside a quoted string
;; http://caml.inria.fr/pub/docs/manual-ocaml/extn.html#sec244
(let ((id (save-excursion
(goto-char (1+ (nth 8 ppss)))
(buffer-substring (point)
(progn (skip-chars-forward "a-z_")
(point))))))
(when (search-forward (concat "|" id "}") end 'move)
(put-text-property (1- (point)) (point)
'syntax-table (string-to-syntax "|")))))
(c (error "Unexpected char '%c' starting delimited string" c))))))
(defmacro tuareg--syntax-rules (&rest rules)
"Generate a function to parse according to RULES.
Each argument has the form (RE BODY...) where RE is a regexp to
match and BODY what to execute upon match. BODY is executed with
point at the end of the match, `start' bound to the start of the
match and `group' to the number of the first group in RE, if any.
The returned function takes the two arguments BEGIN and END
delimiting the region of interest. "
(let ((group-number 1)
(clauses nil)
(regexps nil))
(dolist (rule rules)
(let* ((re (macroexpand (car rule)))
(body (cdr rule))
(re-ngroups (regexp-opt-depth re))
(clause-body
(if (> re-ngroups 0)
`((let ((group ,(1+ group-number)))
,@body))
body)))
(push re regexps)
(push `((match-beginning ,group-number) . ,clause-body)
clauses)
(setq group-number (+ group-number 1 re-ngroups))))
(let ((combined-re (mapconcat (lambda (re) (concat "\\(" re "\\)"))
(nreverse regexps) "\\|"))
(begin (make-symbol "begin"))
(end (make-symbol "end")))
`(lambda (,begin ,end)
(goto-char ,begin)
(while (and (< (point) ,end)
(re-search-forward ,combined-re ,end t)
(let ((start (match-beginning 0)))
(cond . ,(nreverse clauses))
t)))))))
;; FIXME: using nil here is a tad unstable -- sometimes we get a full
;; fontification as code (which is nice!), sometimes not.
(defconst tuareg-font-lock-doc-code-face nil
"Face to use for parts of a doc comment marked up as code (ie, [TEXT]).")
(defun tuareg-fontify-doc-comment (state)
(let ((beg (nth 8 state))
(end (save-excursion
(parse-partial-sexp (point) (point-max) nil nil state
'syntax-table)
(point))))
(put-text-property beg end 'face 'font-lock-doc-face)
(when (and (eq (char-after (- end 2)) ?*)
(eq (char-after (- end 1)) ?\)))
(setq end (- end 2))) ; stop before closing "*)"
(save-excursion
(let ((case-fold-search nil))
(funcall
(tuareg--syntax-rules
((rx (or "[" "{["))
;; Fontify opening bracket.
(put-text-property start (point) 'face
'tuareg-font-lock-doc-markup-face)
;; Skip balanced set of brackets.
(let ((start-end (point))
(level 1))
(while (and (< (point) end)
(re-search-forward (rx (? "\\") (in "[]"))
end 'noerror)
(let ((next (char-after (match-beginning 0))))
(cond
((eq next ?\[)
(setq level (1+ level))
t)
((eq next ?\])
(setq level (1- level))
(if (> level 0)
t
(forward-char -1)
nil))
(t t)))))
(put-text-property start-end (point) 'face
tuareg-font-lock-doc-code-face)
(if (> level 0)
;; Highlight unbalanced opening bracket.
(put-text-property start start-end 'face
'tuareg-font-lock-error-face)
;; Fontify closing bracket.
(put-text-property (point) (1+ (point)) 'face
'tuareg-font-lock-doc-markup-face)
(forward-char 1))))
((rx "]")
(put-text-property start (1+ start) 'face
'tuareg-font-lock-error-face))
;; @-tag.
((rx "@" (group (or "author" "deprecated" "param" "raise" "return"
"see" "since" "before" "version"))
word-end)
(put-text-property start (point) 'face
'tuareg-font-lock-doc-markup-face)
;; Use code face for the first argument of some tags.
(when (and (member (match-string group)
'("param" "raise" "before"))
(looking-at (rx (+ space)
(group
(+ (in "a-zA-Z0-9" "_.'-"))))))
(put-text-property (match-beginning 1) (match-end 1) 'face
tuareg-font-lock-doc-code-face)
(goto-char (match-end 0))))
;; Cross-reference.
((rx (or "{!" "{{!")
(? (or "tag" "module" "modtype" "class" "classtype" "val" "type"
"exception" "attribute" "method" "section" "const"
"recfield")
":")
(group (* (in "a-zA-Z0-9" "_.'"))))
(put-text-property start (match-beginning group) 'face
'tuareg-font-lock-doc-markup-face)
;; Use code face for the reference.
(put-text-property (match-beginning group) (match-end group) 'face
tuareg-font-lock-doc-code-face))
;; {v ... v}
((rx "{v" (in " \t\n"))
(put-text-property start (+ 3 start) 'face
'tuareg-font-lock-doc-markup-face)
(let ((verbatim-end end))
(when (re-search-forward (rx (in " \t\n") "v}")
end 'noerror)
(setq verbatim-end (match-beginning 0))
(put-text-property verbatim-end (point) 'face
'tuareg-font-lock-doc-markup-face))
(put-text-property (+ 3 start) verbatim-end 'face
'tuareg-font-lock-doc-verbatim-face)))
;; Other {..} and <..> constructs.
((rx (or (seq "{"
(or (or "-" ":" "_" "^"
"b" "i" "e" "C" "L" "R"
"ul" "ol" "%"
"{:")
;; Section header with optional label.
(seq (+ digit)
(? ":"
(+ (in "a-zA-Z0-9" "_"))))))
"}"
;; HTML-style tags
(seq "<" (? "/")
(or "b" "i" "code" "ul" "ol" "li"
"center" "left" "right"
(seq "h" (+ digit)))
">")))
(put-text-property start (point) 'face
'tuareg-font-lock-doc-markup-face))
;; Escaped syntax characters.
((rx "\\" (in "{}[]@"))))
beg end))))
nil)
(defun tuareg-font-lock-syntactic-face-function (state)
"`font-lock-syntactic-face-function' for Tuareg."
(if (nth 3 state)
font-lock-string-face
(let ((start (nth 8 state)))
(if (and (> (point-max) (+ start 2))
(eq (char-after (+ start 2)) ?*)
(not (eq (char-after (+ start 3)) ?*)))
;; This is a documentation comment
(tuareg-fontify-doc-comment state)
font-lock-comment-face))))
;; Initially empty, set in `tuareg--install-font-lock-1'
(defvar tuareg-font-lock-keywords ()
"Font-Lock patterns for Tuareg mode (basic level).")
(defvar tuareg-font-lock-keywords-1 ()
"Font-Lock patterns for Tuareg mode (intermediate level).")
(defvar tuareg-font-lock-keywords-2 ()
"Font-Lock patterns for Tuareg mode (maximum level).")
(defconst tuareg-font-lock-syntax
;; Note: as a general rule, changing syntax-table during font-lock
;; is a potential problem for syntax-ppss.
`((?_ . "w") (?' . "w"))
"Syntax changes for Font-Lock.")
(defconst tuareg--whitespace-re
;; QUESTION: Why not just "[ \t\n]*"?
;; It used to be " *[\t\n]? *" but this is inefficient since it can match
;; N spaces in N+1 different ways :-(
" *\\(?:[\t\n] *\\)?")
(defconst tuareg--id-re "\\_<[A-Za-z_][A-Za-z0-9_']*\\_>"
"Regular expression for identifiers.")
(defconst tuareg--lid-re "\\_<[a-z_][A-Za-z0-9_']*\\_>"
"Regular expression for variable names.")
(defconst tuareg--uid-re "\\_<[A-Z][A-Za-z0-9_']*\\_>"
"Regular expression for module and constructor names.")
(defun tuareg--install-font-lock (&optional interactive-p)
"Setup `font-lock-defaults'. INTERACTIVE-P says whether it is
for the interactive mode."
(let* ((id tuareg--id-re)
(lid tuareg--lid-re)
(uid tuareg--uid-re)
(attr-id1 "\\<[A-Za-z_][A-Za-z0-9_']*\\>")
(attr-id (concat attr-id1 "\\(?:\\." attr-id1 "\\)*"))
(maybe-infix-extension (concat "\\(?:%" attr-id "\\)?")); at most 1
;; Matches braces balanced on max 3 levels.
(balanced-braces
(let ((b "\\(?:[^()]\\|(")
(e ")\\)*"))
(concat b b b "[^()]*" e e e)))
(balanced-braces-no-string
(let ((b "\\(?:[^()\"]\\|(")
(e ")\\)*"))
(concat b b b "[^()\"]*" e e e)))
(balanced-braces-no-end-operator ; non-empty
(let* ((b "\\(?:[^()]\\|(")
(e ")\\)*")
(braces (concat b b "[^()]*" e e))
(end-op (concat "\\(?:[^()!$%&*+-./:<=>?@^|~]\\|("
braces ")\\)")))
(concat "\\(?:[^()!$%&*+-./:<=>?@^|~]"
;; Operator not starting with ~
"\\|[!$%&*+-./:<=>?@^|][!$%&*+-./:<=>?@^|~]*" end-op
;; Operator or label starting with ~
"\\|~\\(?:[!$%&*+-./:<=>?@^|~]+" end-op
"\\|[a-z][a-zA-Z0-9]*[: ]\\)"
"\\|(" braces e)))
(balanced-brackets
(let ((b "\\(?:[^][]\\|\\[")
(e "\\]\\)*"))
(concat b b b "[^][]*" e e e)))
(maybe-infix-attribute
(concat "\\(?:\\[@" attr-id balanced-brackets "\\]\\)*"))
(maybe-infix-ext+attr
(concat maybe-infix-extension maybe-infix-attribute))
;; FIXME: module paths with functor applications
(module-path (concat uid "\\(?:\\." uid "\\)*"))
(typeconstr (concat "\\(?:" module-path "\\.\\)?" lid))
(extended-module-name
(concat uid "\\(?: *([ A-Z]" balanced-braces ")\\)*"))
(extended-module-path
(concat extended-module-name
"\\(?: *\\. *" extended-module-name "\\)*"))
(modtype-path (concat "\\(?:" extended-module-path "\\.\\)*" id))
(typevar "'[A-Za-z_][A-Za-z0-9_']*\\>")
(typeparam (concat "\\(?:[+-]?" typevar "\\|_\\)"))
(typeparams (concat "\\(?:" typeparam "\\|( *"
typeparam " *\\(?:, *" typeparam " *\\)*)\\)"))
(typedef (concat "\\(?:" typeparams " *\\)?" lid))
;; Define 2 groups: possible path, variables
(let-ls3 (regexp-opt '("clock" "node" "static"
"present" "automaton" "where" "match"
"with" "do" "done" "unless" "until"
"reset" "every")))
(before-operator-char "[^-!$%&*+./:<=>?@^|~#?]")
(operator-char "[-!$%&*+./:<=>?@^|~]")
(operator-char-no> "[-!$%&*+./:<=?@^|~]"); for "->"
(binding-operator-char
(concat "\\(?:[-$&*+/<=>@^|]" operator-char "*\\)"))
(let-binding-g4 ; 4 groups
(concat "\\_<\\(?:\\(let\\_>" binding-operator-char "?\\)"
"\\(" maybe-infix-ext+attr
"\\)\\(?: +\\(" (if (tuareg-editing-ls3) let-ls3 "rec\\_>")
"\\)\\)?\\|\\(and\\_>" binding-operator-char "?\\)\\)"))
;; group for possible class param
(gclass-gparams
(concat "\\(\\_<class\\(?: +type\\)?\\(?: +virtual\\)?\\_>\\)"
" *\\(\\[ *" typevar " *\\(?:, *" typevar " *\\)*\\] *\\)?"))
;; font-lock rules common to all levels
(common-keywords
`(("^#[0-9]+ *\\(?:\"[^\"]+\"\\)?"
0 tuareg-font-lock-line-number-face t)
;; cppo
(,(concat "^ *#"
(regexp-opt '("define" "undef" "if" "ifdef" "ifndef"
"else" "elif" "endif" "include"
"warning" "error" "ext" "endext")
'symbols))
. font-lock-preprocessor-face)
;; Directives