-
Notifications
You must be signed in to change notification settings - Fork 230
/
merlin.el
2078 lines (1808 loc) · 80.3 KB
/
merlin.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
;;; merlin.el --- Mode for Merlin, an assistant for OCaml -*- coding: utf-8; lexical-binding: t -*-
;; Licensed under the MIT license.
;; Author: Frédéric Bour <frederic.bour(_)lakaban.net>
;; Created: 30 August 2016
;; Version: 3.0
;; Keywords: ocaml languages
;; Package-Requires: ((emacs "25.1"))
;; URL: https://github.com/ocaml/merlin
;;; Commentary:
;; merlin-mode is an Emacs interface to merlin. It allows you to perform
;; queries such as getting the type of an expression, completion, and so on.
;; Installation:
;; You need merlin installed on your system (ocamlmerlin binary) for merlin-mode
;; to work.
;;; Usage:
;; TODO
;;; Code:
(require 'cl-lib)
(require 'crm) ;; for completing-read-multiple
;; caml-types for highlighting
;; (https://github.com/ocaml/merlin/issues/331)
(require 'caml-types nil 'noerror)
;; silence free variable warning
(defvar merlin-mode)
(defgroup merlin nil
"merlin binding mode allowing completion and typing in OCaml files."
:group 'languages :prefix "merlin-")
;;
;; Faces
;;
(defface merlin-type-face
'((t :inherit caml-types-expr-face))
"Face for highlighting a typed expr."
:group 'merlin)
(defface merlin-compilation-warning-face
'((t :inherit compilation-warning))
"Face to use to highlight merlin warnings."
:group 'merlin)
(defface merlin-compilation-error-face
'((t :inherit compilation-error))
"Face to use to highlight merlin errors."
:group 'merlin)
;;
;; Customizable vars
;;
(defcustom merlin-show-instance-in-lighter t
"Show the current instance of the buffer in the lighter."
:group 'merlin :type 'boolean)
(defcustom merlin-report-errors-in-lighter nil
"Report absence of .merlin or errors in .merlin in the lighter."
:group 'merlin :type 'boolean)
(defcustom merlin-client-log-function nil
"The function takes four arguments:
- the path to the merlin binary
- the name of the command
- the total time spent in the server (or -1 if that information
is not available)
- the resulting state (\"return\", \"failure\" or \"interrupted\")
Its return value is ignored."
:group 'merlin :type 'symbol)
(defcustom merlin-configuration-function nil
"The function takes no argument and returns the configuration for the current
buffer, in a form suitable for `merlin-buffer-configuration'."
:group 'merlin :type 'symbol)
(defcustom merlin-grouping-function nil
"Deprecated, see `merlin-configuration-function'."
:group 'merlin :type 'symbol)
(defcustom merlin-command 'opam
"The path to merlin in your installation."
:group 'merlin :type '(choice (file :tag "Filename (default binary is \"ocamlmerlin\")")
(function :tag "Function returning path to the binary")
(const :tag "Use current opam switch" opam)))
(defcustom merlin-completion-with-doc nil
"If non-nil, tries to retrieve ocamldoc comments associated with each
completion candidate."
:group 'merlin :type 'boolean)
(defcustom merlin-completion-dwim t
"If non-nil, fallback to fuzzier completion when normal completion gives
no result."
:group 'merlin :type 'boolean)
(defcustom merlin-completion-types t
"If non-nil, print the types of the variables during completion."
:group 'merlin :type 'boolean)
(defcustom merlin-completion-arg-type t
"If non-nil, print the type of the expected argument during completion
on an application."
:group 'merlin :type 'boolean)
(defcustom merlin-debug nil
"If non-nil, log the data sent and received from merlin into
`merlin-log-buffer-name' buffer."
:group 'merlin :type 'boolean)
(defcustom merlin-report-warnings t
"If non-nil, report warnings, otherwise ignore them."
:group 'merlin :type 'boolean)
(defcustom merlin-occurrences-buffer-name "*merlin-occurrences*"
"The name of the buffer listing occurrences of an identifier after
a call to `merlin-occurrences'."
:group 'merlin :type 'string)
(defcustom merlin-type-buffer-name "*merlin-types*"
"The name of the buffer storing module signatures."
:group 'merlin :type 'string)
(defcustom merlin-error-buffer-name "*merlin-errors*"
"The name of the buffer storing module signatures."
:group 'merlin :type 'string)
(defcustom merlin-log-buffer-name "*merlin-log*"
"The name of the buffer storing log messages and debug information.
See `merlin-debug'."
:group 'merlin :type 'string)
(defcustom merlin-favourite-caml-mode nil
"The OCaml mode to use for the *merlin-types* buffer."
:group 'merlin :type 'symbol)
(defcustom merlin-error-after-save '("ml" "mli")
"Determines whether merlin should check for errors after saving.
If t, always check for errors after saving.
If nil, never check.
If a string list, check only if the extension of the buffer-file-name
is in the list."
:group 'merlin :type '(choice (repeat string) boolean))
(defcustom merlin-error-in-fringe (>= emacs-major-version 24)
"If non-nil, display errors in fringe"
:group 'merlin :type 'boolean)
(defcustom merlin-error-on-single-line nil
"Only highlight first line of multi-line error messages"
:group 'merlin :type 'boolean)
(defcustom merlin-error-check-then-move t
"If t, merlin-error-next and merlin-error-prev first update the errors
then move the cursor.
If nil, they both update and move at the same time."
:group 'merlin :type 'boolean)
(defcustom merlin-default-flags nil
"The flags to pass to ocamlmerlin."
:group 'merlin :type '(repeat string))
(defcustom merlin-occurrences-show-buffer 'other
"Determine how to display the occurrences list after a call to
`merlin-occurrences'."
:group 'merlin :type '(choice (const :tag "Don't show list" never)
(const :tag "Show in the current window" same)
(const :tag "Show in another window" other)))
(defcustom merlin-locate-in-new-window 'diff
"Determine whether to display results of `merlin-locate' in
a new window or not."
:group 'merlin :type '(choice (const :tag "Always open a new window" always)
(const :tag "Never open a new window" never)
(const :tag "Open a new window only if the target file is different from current buffer." diff)))
(defcustom merlin-locate-preference 'ml
"Determine whether locate should in priority look in ml or mli files."
:group 'merlin :type '(choice (const :tag "Look at implementation" ml)
(const :tag "Look at interfaces" mli)))
(defcustom merlin-locate-focus-new-window t
"If non-nil, when locate opens a new window it will give it the focus."
:group 'merlin :type 'boolean)
(defcustom merlin-logfile nil
"If non-nil, use this file for the log file (should be an absolute path)."
:group 'merlin :type 'filename)
(defcustom merlin-arrow-keys-type-enclosing t
"If non-nil, after a type enclosing, C-up and C-down are used
to go up and down the AST. In addition, C-w copies the type to the
kill ring and C-d destructures the expression."
:group 'merlin :type 'boolean)
(defcustom merlin-type-after-locate nil
"If non-nil, use type-enclosing after locate."
:group 'merlin :type 'boolean)
(defcustom merlin-allow-sit-for t
"When user attention is required, merlin will use `sit-for' only if
`merlin-allow-sit-for' is `t'."
:group 'merlin :type 'boolean)
(defcustom merlin-construct-with-local-values nil
"If non-nil, `merlin-construct' includes values in the local environment.
Otherwise, `merlin-construct' only includes constructors."
:group 'merlin :type 'boolean)
(defalias 'merlin-find-file 'find-file-other-window
"The function called when merlin try to open a file (doesn't apply to
merlin-locate, see `merlin-locate-in-new-window').")
;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Buffer local settings ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar-local merlin-buffer-configuration nil
"An association list describing the configuration of merlin binary for the
current buffer. Customize `merlin-configuration-function' to initialize it.
The association list can contain the following optional keys:
- `flags': extra flags to give merlin
- `command': command to run
- `env': list of strings (of the shape VARIABLE=FOO) (see
`process-environment') that will be prepended to the environment of merlin
- `dot-merlin': path to a .merlin file
- `logfile': path to the logfile
- `name': a short name for this configuration, displayed in user notifications.
- `do-not-cache-config': if set, refreshes the config on every command")
(defvar-local merlin-buffer-packages nil
"List of packages loaded in the buffer")
(defvar-local merlin-buffer-packages-path nil
"List of path of packages loaded in the buffer")
(defvar-local merlin-buffer-extensions nil
"List of syntax extensions active in the buffer")
(defvar-local merlin-buffer-flags ""
"Additional flags to pass to merlin")
;;;;;;;;;;;;;;;;;;;;;;;;
;; Internal variables ;;
;;;;;;;;;;;;;;;;;;;;;;;;
(defvar merlin-opam-bin-path nil)
;; If user did not specify its merlin-favourite-caml-mode, try to guess it from
;; the buffer being edited
(defvar merlin-guessed-favorite-caml-mode nil)
(defvar merlin--idle-timer nil)
;; Errors related variables
(defvar-local merlin-erroneous-buffer nil
"Whether the buffer is erroneous or not")
(defvar merlin-highlight-overlay nil
"Merlin overlay used for highlights.")
;; Type related variables
(defvar-local merlin-enclosing-types nil
"List containing the enclosing type.")
(defvar-local merlin-enclosing-offset nil
"Current offset in `merlin-enclosing-types'.")
;; Locate
(defvar merlin-position-stack nil)
;; Verbosity
(defconst merlin-verbosity-context nil
"If non-nil, a simple key used to determine verbosity")
(defvar-local merlin--verbosity-cache nil
"Cache last command to determine verbosity level")
(defvar-local merlin-debug-last-commands nil
"Last merlin commands (for debugging)")
;; Misc
(defvar-local merlin--project-cache nil
"Cache for merlin--project-get")
(defvar-local merlin--dwimed nil
"Remember if we used dwim for the current completion or not")
;;;;;;;;;;;
;; UTILS ;;
;;;;;;;;;;;
(defun merlin--completion-map-with-space (&optional map)
"Return a map suitable for `minibuffer-local-completion-map'
but not overriding SPC binding."
(unless map (setq map minibuffer-local-completion-map ))
(setq map (make-composed-keymap nil map))
(define-key map (kbd "SPC") nil)
map)
(defun merlin-debug (message &rest args)
"Output S to `merlin-log-buffer-name' if `merlin-debug' is non-nil
in the current buffer."
(when merlin-debug
(with-current-buffer (get-buffer-create merlin-log-buffer-name)
(goto-char (point-max))
(if args (insert (apply 'format message args))
(insert message)))))
(defun merlin-enable-debug ()
"Start recording merlin debug information to `merlin-log-buffer-name'."
(interactive)
(setq merlin-debug t)
(message "merlin: logging to %S buffer" merlin-log-buffer-name))
(defun merlin-disable-debug ()
"Stop recording debug information."
(interactive)
(setq merlin-debug nil))
(defun merlin-debug-last-commands ()
"Display last commands executed and their result (if any)"
(interactive)
(let (buf)
(dolist (command merlin-debug-last-commands)
(push (concat "- result: " (or (cdr command) "failed")) buf)
(push (mapconcat 'identity
(merlin--map-flatten-to-string "command: " (car command))
" ") buf))
(message "Last commands executed, most recent at the end:\n%s"
(mapconcat 'identity buf "\n"))))
(defun merlin-buffer-substring (start end)
"Return content of buffer between two points or empty string
if points are not valid."
(if (< start end) (buffer-substring-no-properties start end) ""))
(defsubst merlin-lookup (key list &optional default)
"Lookup KEY in LIST which is a list of pairs. If not found,
return DEFAULT or the value associated to KEY."
(assoc-default key list nil default))
(defun merlin--differs-from-current-file (path)
(not (string-equal path (buffer-file-name))))
(defun merlin--rev-map-flatten (f xs &optional acc)
(while (consp xs)
(setq acc (if (listp (car xs))
(merlin--rev-map-flatten f (car xs) acc)
(cons (funcall f (car xs)) acc)))
(setq xs (cdr xs)))
(when xs
(setq acc (cons xs acc)))
acc)
(defun merlin--map-flatten (f &rest xs)
(nreverse (merlin--rev-map-flatten f xs)))
(defun merlin--map-flatten-to-string (&rest xs)
(merlin--map-flatten
(lambda (x) (if (stringp x) x (prin1-to-string x))) xs))
(defun merlin--goto-file-and-point (data)
"Go to the file and position indicated by DATA which is an assoc list
containing fields file, line and col."
(let* ((file (assoc 'file data))
(open-window (cond ((equal merlin-locate-in-new-window 'never) nil)
((equal merlin-locate-in-new-window 'always))
(file (merlin--differs-from-current-file (cdr file)))))
(filename (if file (cdr file) (buffer-file-name (buffer-base-buffer))))
(focus-window (or (not open-window) merlin-locate-focus-new-window))
(do-open (lambda ()
(push-mark)
(if open-window
(find-file-other-window filename)
(find-file filename))
(merlin--goto-point (cdr (assoc 'pos data))))))
(if focus-window
(progn
(push (cons (buffer-name) (point)) merlin-position-stack)
(funcall do-open)
(message "Use %s to go back."
(substitute-command-keys "\\[merlin-pop-stack]")))
(save-excursion (save-selected-window (funcall do-open))))))
(defun merlin-add-display-properties (overlay bitmap string &optional face)
"Add the necessary properties to OVERLAY to display it nicely."
(let ((prop (if window-system
`(left-fringe ,bitmap . ,(if face (list face) nil))
`((margin left-margin) ,string))))
(when face (overlay-put overlay 'face face))
(overlay-put overlay 'before-string
(propertize " " 'display prop))))
(defun merlin--highlight (bounds face)
"Create an overlay on BOUNDS (of the form (START . END)) and give it FACE."
(remove-overlays nil nil 'merlin-kind 'highlight)
(let ((overlay (make-overlay (car bounds) (cdr bounds))))
(overlay-put overlay 'face face)
(overlay-put overlay 'merlin-kind 'highlight)
(if merlin-allow-sit-for
(unwind-protect (sit-for 60) (delete-overlay overlay))
(run-with-idle-timer 0.5 nil
(lambda () (delete-overlay overlay))))))
;; Position management
(defun merlin--goto-point (data)
"Go to the point indicated by DATA which must be an assoc list with fields
line and col. If narrowing is in effect, widen if DATA is outside the visible
region."
(let ((target-pos (merlin--point-of-pos data)))
;; If our target position is outside the narrowed region, we'll
;; have to widen.
(when (or (< target-pos (point-min))
(> target-pos (point-max)))
(widen))
(goto-char target-pos)))
(defun merlin--point-of-pos (data)
"Transform DATA (a remote merlin position) into a point.
DATA must be an assoc list with fields line and col."
(let ((line-num (merlin-lookup 'line data 0))
(col-byte-offset (merlin-lookup 'col data 0)))
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(forward-line (1- line-num))
;; Find the target position, converting the byte position to a
;; character offset.
(let* ((bol-offset (position-bytes (point)))
(col-offset (max 0 col-byte-offset))
(target-off (+ bol-offset col-offset)))
(byte-to-position target-off))))))
(defun merlin-make-point (data)
"Transform DATA (a remote merlin position) into a point."
(merlin--point-of-pos data))
(defun merlin-unmake-point (point)
"Destruct POINT to line / col."
(save-excursion
(save-restriction
(widen)
(goto-char point)
(format "%d:%d" (line-number-at-pos)
(- (position-bytes (point))
(position-bytes (line-beginning-position)))))))
(define-obsolete-function-alias 'merlin/unmake-point 'merlin-unmake-point "2021-01-27")
(defun merlin--make-bounds (data)
"From a remote merlin object DATA {\"start\": LOC1; \"end\": LOC2},
return (LOC1 . LOC2)."
(cons
(merlin-make-point (cdr (assoc 'start data)))
(merlin-make-point (cdr (assoc 'end data)))))
;;;;;;;;;;;;;;;;;;;;;;;;
;; PROCESS MANAGEMENT ;;
;;;;;;;;;;;;;;;;;;;;;;;;
(defun merlin--call-process (path args)
"Some workarounds for piping buffer content to a process"
(merlin-debug "# calling binary: %S with arguments: %S.\n" path args)
(let ((ib (current-buffer))
(tmp (when merlin-debug (make-temp-file "merlin")))
(wd (expand-file-name default-directory))
result)
(with-temp-buffer
(let ((ob (current-buffer)))
(with-current-buffer ib
(save-restriction
(widen)
(let ((default-directory wd))
(apply 'call-process-region (point-min) (point-max) path nil
(list ob tmp) nil args)))))
(setq result (buffer-string))
(merlin-debug "# stdout\n%s" result)
(when tmp
(with-demoted-errors "Error when trying to read merlin log: %S"
(with-current-buffer merlin-log-buffer-name
(goto-char (point-max))
(insert "# stderr\n")
(insert-file-contents tmp)
(delete-file tmp))))
result)))
(defun merlin--call-merlin (command &rest args)
"Invoke merlin binary with the proper setup to execute the command passed as
argument (lookup appropriate binary, setup logging, pass global settings)"
;; Really start process
(let ((binary (merlin-command))
;; (flags (merlin-lookup 'flags merlin-buffer-configuration))
(process-environment (cl-copy-list process-environment))
(dot-merlin (merlin-lookup 'dot-merlin merlin-buffer-configuration))
;; FIXME use logfile
;; (logfile (or (merlin-lookup 'logfile merlin-buffer-configuration)
;; merlin-logfile))
(extensions (merlin--map-flatten (lambda (x) (cons "-extension" x))
merlin-buffer-extensions))
(packages (merlin--map-flatten (lambda (x) (cons "-I" x))
merlin-buffer-packages-path))
(filename (buffer-file-name (buffer-base-buffer))))
;; Update environment
(dolist (binding (merlin-lookup 'env merlin-buffer-configuration))
(let* ((equal-pos (string-match-p "=" binding))
(prefix (if equal-pos
(substring binding 0 (1+ equal-pos))
binding))
(is-prefix (lambda (x) (string-prefix-p prefix x))))
(setq process-environment (cl-delete-if is-prefix process-environment))
(when equal-pos
(setq process-environment (cons binding process-environment)))))
;; Compute verbosity
(when (eq merlin-verbosity-context t)
(setq merlin-verbosity-context (cons command args)))
(if (not merlin-verbosity-context)
(setq merlin--verbosity-cache nil)
(if (equal merlin-verbosity-context (car-safe merlin--verbosity-cache))
(setcdr merlin--verbosity-cache (1+ (cdr merlin--verbosity-cache)))
(setq merlin--verbosity-cache (cons merlin-verbosity-context 0))))
;; Compute full command line.
(setq args (merlin--map-flatten-to-string
"server" command "-protocol" "sexp"
(when dot-merlin
(list "-dot-merlin" dot-merlin))
;; Is debug mode enabled
(when merlin-debug '("-log-file" "-"))
;; If command is repeated, increase verbosity
(when merlin-verbosity-context
(list "-verbosity" (cdr merlin--verbosity-cache)))
packages
extensions
(unless (string-equal merlin-buffer-flags "")
(cons "-flags" merlin-buffer-flags))
(when filename
(cons "-filename" filename))
args))
;; Log last commands
(setq merlin-debug-last-commands
(cons (cons (cons binary args) nil) merlin-debug-last-commands))
(let ((cdr (nthcdr 5 merlin-debug-last-commands)))
(when cdr (setcdr cdr nil)))
;; Call merlin process
(setcdr (car merlin-debug-last-commands) (merlin--call-process binary args))))
(defun merlin-client-logger (binary cmd timing result)
(when merlin-client-log-function
(funcall merlin-client-log-function binary cmd timing result)))
(defun merlin-call (command &rest args)
"Execute a command and parse output: return an sexp on success or throw an error"
(let ((binary (merlin-command)) result)
(condition-case err
(progn
(setq result (merlin--call-merlin command args))
(condition-case err
(setq result (car (read-from-string result)))
(error
(merlin-client-logger binary command -1 "failure")
(error "merlin: error %s trying to parse answer: %s"
err result))))
(quit
(merlin-client-logger binary command -1 "interrupted")
(signal (car err) (cdr err))))
(let* ((notifications (cdr-safe (assoc 'notifications result)))
(timing (cdr-safe (assoc 'timing result)))
(class (cdr-safe (assoc 'class result)))
(value (cdr-safe (assoc 'value result))))
(merlin-client-logger binary command timing class)
(dolist (notification notifications)
(message "(merlin) %s" notification))
(pcase class
("return" value)
("failure" (error "merlin-mode failure: %s" value))
("error" (error "merlin: %s" value))
(_ (error "unknown answer: %S:%S" class value))))))
(define-obsolete-function-alias 'merlin/call 'merlin-call "2021-01-27")
(defun merlin-stop-server ()
"Shutdown merlin server."
(interactive)
(unless merlin-mode (message "Buffer is not managed by merlin."))
(when merlin-mode
(merlin--call-merlin "stop-server")
;; These are buffer-local variables, so reset them in all buffers.
(dolist (buf (buffer-list))
(with-current-buffer buf
(kill-local-variable 'merlin-buffer-configuration)
(kill-local-variable 'merlin-erroneous-buffer)))))
;;;;;;;;;;;;;;;;;;;;
;; FILE SWITCHING ;;
;;;;;;;;;;;;;;;;;;;;
(defun merlin-switch-list-by-ext (&rest exts)
"List filenames ending by any of EXTS in the path."
(merlin-call "list-modules"
(merlin--map-flatten (lambda (x) (cons "-ext" x)) exts)))
(defun merlin-switch-to (name &rest exts)
"Switch to NAME.EXTS."
(let ((file (merlin-call "path-of-source"
(merlin--map-flatten
(lambda (ext) (cons "-file" (concat name ext))) exts))))
(when file (merlin-find-file file))))
(defun merlin-switch-to-ml (name)
"Switch to the ML file corresponding to the module NAME
(fallback to MLI if no ML is provided)."
(interactive (list (ido-completing-read "Module: "
(merlin-switch-list-by-ext '(".ml" ".mli")))))
(merlin-switch-to name '(".ml" ".mli")))
(defun merlin-switch-to-mli (name)
"Switch to the MLI file corresponding to the module NAME
(fallback to ML if no MLI is provided)."
(interactive (list (ido-completing-read "Module: "
(merlin-switch-list-by-ext '(".mli" ".ml")))))
(merlin-switch-to name '(".mli" ".ml")))
;;;;;;;;;;;;;;;;;;
;; ERROR BUFFER ;;
;;;;;;;;;;;;;;;;;;
(defvar merlin-error-buffer-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map special-mode-map)
(define-key map "g" nil)
map)
"Keymap for error buffer.")
(defun merlin-display-in-error-buffer (text)
"Change content of error-buffer."
(let ((curr-dir default-directory))
(with-current-buffer (get-buffer-create merlin-error-buffer-name)
(read-only-mode 0)
(erase-buffer)
(insert text)
(goto-char (point-min))
(read-only-mode 1)
(use-local-map merlin-error-buffer-map)
;; finally make sure that the error buffer directory is the same as the
;; last (ml) buffer we were in.
;; Indeed if people move to that buffer and start looking for a file we
;; want them to be in the directory they were in when they last requested a
;; type, not in the directory they were in when they first requested a
;; type (for long lived emacs sessions that directory might not even exist
;; anymore).
(setq default-directory curr-dir))))
(defun merlin--error-display (err)
"Display the error ERR."
(if (not err)
(message "<no information>")
(merlin-display-in-error-buffer err)
(message "%s" err)))
;;;;;;;;;;;;;;;;;;
;; ERROR REPORT ;;
;;;;;;;;;;;;;;;;;;
(defvar-local merlin--last-edit nil
"Coordinates (start . end) of last edit or nil, to prevent error messages
from flickering when cursor is around the edit.")
(defun merlin--on-edit (start end _length)
"Memorize coordinates of last edition to avoid flickering error messages
around the cursor"
(setq merlin--last-edit (cons start end)))
(defun merlin--error-position-delta (point err)
"Distance between point and error."
(setq err (cdr (assoc 'bounds err)))
(cond ((< point (car err)) (cons (- (car err) point) 0))
((> point (cdr err)) (cons (- point (cdr err)) 0))
(t (cons 0 (min (- (cdr err) point) (- point (car err)))))))
(defun merlin--error-at-position (point errors)
"Returns error from ERRORS list most relevant at POINT"
(let ((err nil) (d nil))
(dolist (err- errors err)
(let ((d- (merlin--error-position-delta point err-)))
(when (or (not err) (< (car d-) (car d))
(and (= (car d-) (car d)) (< (cdr d-) (cdr d))))
(setq d d-) (setq err err-))))))
(defun merlin-show-error-on-current-line ()
"Show the error of the current line in the echo area.
If there is no error, do nothing."
(when (and merlin-mode (not (current-message)))
(let* ((errors (overlays-in (line-beginning-position) (line-end-position)))
(err nil))
(when (or (not merlin--last-edit)
(not (or (= (point) (car merlin--last-edit))
(= (point) (cdr merlin--last-edit)))))
(setq errors (remove nil (mapcar 'merlin--overlay-pending-error errors)))
(setq err (merlin--error-at-position (point) errors))
(when err (merlin--error-display (cdr (assoc 'message err))))))))
(defun merlin--overlay-next-property-set (point prop &optional limit)
"Find next point where PROP is set.
(Like `next-single-char-property-change' but ensure that prop is not-nil)."
(setq point (next-single-char-property-change point prop nil limit))
(unless (cl-find-if (lambda (a) (overlay-get a prop)) (overlays-at point))
(setq point (next-single-char-property-change point prop nil limit)))
point)
(defun merlin--overlay-previous-property-set (point prop &optional limit)
"Find previous point where PROP is set.
(Like `previous-single-char-property-change' but ensure that prop is not-nil)."
(setq point (previous-single-char-property-change point prop nil limit))
(unless (cl-find-if (lambda (a) (overlay-get a prop)) (overlays-at point))
(setq point (previous-single-char-property-change point prop nil limit)))
point)
(defun merlin--has-error-group-overlay-at-point (point group)
(cl-some (lambda (err) (eq (overlay-get err 'merlin-error-group) group))
(overlays-at point)))
(defun merlin--error-group-next (point group &optional limit)
(let ((point (merlin--overlay-next-property-set point 'merlin-pending-error limit)))
(when group
(while (not (or (eq point (point-max))
(merlin--has-error-group-overlay-at-point point group)))
(setq point (merlin--overlay-next-property-set point 'merlin-pending-error limit))))
point))
(defun merlin--error-group-prev (point group &optional limit)
(let ((point (merlin--overlay-previous-property-set point 'merlin-pending-error limit)))
(when group
(while (not (or (eq point (point-min))
(merlin--has-error-group-overlay-at-point point group)))
(setq point (merlin--overlay-next-property-set point 'merlin-pending-error limit))))
point))
(defun merlin--errors-at-position (point)
(remove nil (mapcar 'merlin--overlay-pending-error (overlays-at point))))
(defun merlin--error-prev-cycle (group)
"Returns previous error, cycling when reaching beginning of buffer"
(let ((point (point)) (errors nil) (err nil))
(setq point (merlin--error-group-prev point group))
(unless (eq point (point)) (setq errors (merlin--errors-at-position point))
(unless errors
(setq point (merlin--error-group-prev (point-max) group (point)))
(setq errors (merlin--errors-at-position point)))
(setq err (merlin--error-at-position point errors))
(if err (cons point err) nil))))
(defun merlin--error-next-cycle (group)
"Returns next error, cycling when reaching end of buffer"
(let ((point (point)) (errors nil) (err nil))
(setq point (merlin--error-group-next point group))
(when (eq point (point-max))
(setq point (point-min))
(setq errors (merlin--errors-at-position point))
(unless errors
(setq point (merlin--error-group-next (point-min) group (point)))))
(unless errors
(setq errors (merlin--errors-at-position point)))
(setq err (merlin--error-at-position point errors))
(if err (cons point err) nil)))
(defun merlin--after-save ()
(when (and merlin-mode merlin-error-after-save) (merlin-error-check)))
(defadvice basic-save-buffer (after merlin--after-save activate)
"The save hook is called only if buffer was modified, but user might want fresh errors anyway"
(merlin--after-save))
(defun merlin-error-prev (&optional group)
"Jump back to previous error."
(interactive)
(let ((old-errors merlin-erroneous-buffer))
(merlin--error-check nil)
(let ((err (merlin--error-prev-cycle group)))
(unless (or err merlin-erroneous-buffer) (message "No errors"))
(when err
(if (and merlin-error-check-then-move
(not (equal old-errors merlin-erroneous-buffer)))
(message "(%d pending errors, use %s to jump)"
(length merlin-erroneous-buffer)
(substitute-command-keys "\\[merlin-error-prev]"))
(goto-char (car err))
(message "%s" (cdr (assoc 'message (cdr err))))
(merlin--highlight (cdr (assoc 'bounds (cdr err))) 'next-error))))))
(defun merlin-error-next (&optional group)
"Jump to next error."
(interactive)
(let ((old-errors merlin-erroneous-buffer))
(merlin--error-check nil)
(let ((err (merlin--error-next-cycle group)))
(unless (or err merlin-erroneous-buffer) (message "No errors"))
(when err
(if (and merlin-error-check-then-move
(not (equal old-errors merlin-erroneous-buffer)))
(message "(%d pending errors, use %s to jump)"
(length merlin-erroneous-buffer)
(substitute-command-keys "\\[merlin-error-next]"))
(goto-char (car err))
(message "%s" (cdr (assoc 'message (cdr err))))
(merlin--highlight (cdr (assoc 'bounds (cdr err))) 'next-error))))))
(defun merlin-error-next-in-group ()
"Jump to next error in same group, if any, next error otherwise."
(interactive)
(let ((err (merlin--error-at-position
(point) (merlin--errors-at-position (point)))))
(merlin-error-next (when err (overlay-get err 'merlin-error-group)))))
(defun merlin-error-prev-in-group ()
"Jump to previous error in same group, if any, previous error otherwise."
(interactive)
(let ((err (merlin--error-at-position
(point) (merlin--errors-at-position (point)))))
(merlin-error-prev (when err (overlay-get err 'merlin-error-group)))))
(defun merlin--error-warning-p (msg)
"Tell if the message MSG is a warning."
(string-match-p "^Warning" msg))
(defun merlin-error-reset ()
"Clear error list."
(interactive)
(setq merlin-erroneous-buffer nil)
(remove-overlays nil nil 'merlin-kind 'error))
(defun merlin--overlay-pending-error (overlay)
"Returns non-nil if OVERLAY is about a pending error."
(if overlay (overlay-get overlay 'merlin-pending-error) nil))
(defun merlin--kill-error-if-edited (overlay is-after _beg _end &optional _length)
"Remove an error from the pending error lists if it is edited by the user."
(when is-after (delete-overlay overlay)))
(defun merlin--transform-add-error-bounds (err)
(let ((bounds (merlin--make-bounds err))
(subs (cdr-safe (assoc 'sub err))))
(when merlin-error-on-single-line
(setq bounds (cons (car bounds)
(min (cdr bounds)
(save-excursion
(goto-char (car bounds))
(line-end-position))))))
(when (= (car bounds) (cdr bounds))
(setq bounds (if (> (car bounds) (point-min))
(cons (1- (car bounds)) (cdr bounds))
(cons (car bounds) (1+ (cdr bounds))))))
(setq bounds (cons (copy-marker (car bounds))
(copy-marker (cdr bounds))))
(cl-acons 'sub (mapcar 'merlin--transform-add-error-bounds subs)
(cl-acons 'bounds bounds err))))
(defun merlin-transform-display-errors (errors)
"Populate the error list with ERRORS, transformed into an emacs-friendly
form. Do display of error list."
(setq errors (mapcar 'merlin--transform-add-error-bounds errors))
(dolist (main errors)
(let ((subs (cdr-safe (assoc 'sub main))))
(dolist (err (cons main subs))
(let* ((bounds (cdr (assoc 'bounds err)))
(overlay (make-overlay (car bounds) (cdr bounds))))
(overlay-put overlay 'merlin-kind 'error)
(overlay-put overlay 'merlin-pending-error err)
(overlay-put overlay 'merlin-error-group main)
(push #'merlin--kill-error-if-edited
(overlay-get overlay 'modification-hooks))
(when (and merlin-error-in-fringe
(not (and (eq err main) subs)))
(if (merlin--error-warning-p (cdr (assoc 'message err)))
(merlin-add-display-properties overlay
'question-mark
"?"
'merlin-compilation-warning-face)
(merlin-add-display-properties overlay
'exclamation-mark
"!"
'merlin-compilation-error-face)))))))
errors)
(defun merlin--error-check (view-errors-p)
"Check for errors.
Return t if there were not any or nil if there were. Moreover, it displays the
errors in the fringe. If VIEW-ERRORS-P is non-nil, display a count of them."
(merlin-error-reset)
(let* ((errors (merlin-call "errors"))
(no-loc (cl-remove-if (lambda (e) (assoc 'start e)) errors)))
(setq errors (cl-remove-if-not (lambda (e) (assoc 'start e)) errors))
(unless merlin-report-warnings
(setq errors (cl-remove-if (lambda (e)
(let ((msg (cdr (assoc 'message e))))
(or (equal msg "warning")
(merlin--error-warning-p msg))))
errors)))
(setq merlin-erroneous-buffer (or errors no-loc))
(dolist (e no-loc)
(message "%s" (cdr (assoc 'message e))))
(merlin-transform-display-errors errors)
(when view-errors-p
(let ((prefix (current-message)))
(setq prefix (if prefix (concat prefix " ") ""))
(if merlin-erroneous-buffer
(message "%s(%d pending errors, use %s to jump)"
prefix
(length errors)
(substitute-command-keys "\\[merlin-error-next]"))
(message "%sNo errors" prefix))))))
(defun merlin-error-after-save ()
"Determine whether the buffer should be checked for errors depending on
the value of merlin-error-after-save setting."
(cond
((equal merlin-error-after-save t) t)
((equal merlin-error-after-save nil) nil)
((and (listp merlin-error-after-save)
(buffer-file-name (buffer-base-buffer)))
(member (file-name-extension (buffer-file-name (buffer-base-buffer)))
merlin-error-after-save))))
(defun merlin-toggle-view-errors ()
"Toggle the viewing of errors in the buffer."
(interactive)
(setq merlin-error-after-save (not (merlin-error-after-save)))
(if (merlin-error-after-save)
(progn
(merlin--after-save)
(message "Errors are now reported. Use %s to stop reporting them."
(substitute-command-keys "\\[merlin-toggle-view-errors]")))
(progn
(merlin-error-reset)
(message "Errors are not reported anymore. Use %s to start again reporting them."
(substitute-command-keys "\\[merlin-toggle-view-errors]")))))
;;;;;;;;;;;;;;;;;;;;;;;;
;; COMPLETION HELPERS ;;
;;;;;;;;;;;;;;;;;;;;;;;;
(defun merlin-completion-entry-short-description (entry)
"Return a short string describing the content a completion entry (e.g kind of
identifier, type of a value, etc)."
(let* ((kind (cdr (assoc 'kind entry)))
(desc (or (cdr (assoc 'desc entry)) (cdr (assoc 'type entry))))
(type (cond ((member kind '("Module" "module")) " <module>")
((string-equal kind "Type") (format " [%s]" desc))
(t desc))))
(replace-regexp-in-string "[\n ]+" " " type)))
(defun merlin-completion-entry-text (compl-prefix entry)
"Return the text that should replace COMPL-PREFIX in the buffer if the user
chooses this completion entry.
COMPL-PREFIX is the prefix that was used to start completion."
(let ((entry-name (cdr (assoc 'name entry))))
(if merlin--dwimed entry-name (concat compl-prefix entry-name))))
(defun merlin-completion-prefix (ident)
"Compute the prefix of IDENT. The prefix of `Foo.bar' is `Foo.' and the
prefix of `bar' is `'."
(car (merlin-completion-split-ident ident)))
(defun merlin-completion-split-ident (ident)
"Split IDENT into a (cons prefix suffix). See merlin-completion-prefix."
(let* ((l (split-string ident "\\."))
(s (mapconcat 'identity (butlast l) "."))
(suffix (if l (car (last l)) ident))
(prefix (if (string-equal s "") s (concat s "."))))
(cons prefix suffix)))
(defun merlin--completion-prepare-labels (labels prefix)
;; Remove non-matching entry, adjusting optional labels if needed
(cl-loop for x in labels
for name = (cdr (assoc 'name x))
when (or (string-prefix-p prefix name)
(when (equal (aref name 0) ??)
(aset name 0 ?~)
(string-prefix-p prefix name)))
collect (append x '((kind . "Label") (info . nil)))))