/
dart-mode.el
1570 lines (1317 loc) · 58.7 KB
/
dart-mode.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
;;; dart-mode.el --- Major mode for editing Dart files -*- lexical-binding: t; -*-
;; Author: Natalie Weizenbaum
;; URL: https://github.com/nex3/dart-mode
;; Version: 1.0.4
;; Package-Requires: ((emacs "24.5") (cl-lib "0.5") (dash "2.10.0") (flycheck "0.23") (s "1.10"))
;; Keywords: language
;; Copyright (C) 2011 Google Inc.
;;
;; 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/>.
;; This file contains several functions and variables adapted from the
;; code in https://github.com/dominikh/go-mode.el
;;
;; go-mode.el uses this license:
;;
;; Copyright (c) 2014 The go-mode Authors. All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are
;; met:
;;
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above
;; copyright notice, this list of conditions and the following disclaimer
;; in the documentation and/or other materials provided with the
;; distribution.
;; * Neither the name of the copyright holder nor the names of its
;; contributors may be used to endorse or promote products derived from
;; this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;; Commentary:
;; To install, see https://github.com/nex3/dart-mode/blob/master/README.md
;;
;; Known bugs:
;;
;; * Multiline strings using """ and ''' are not recognized. They fontify
;; correctly, but only because they look like three strings in a row.
;; * In a map with identifier keys, the first key is fontified like a label.
;; * Return values for operator methods aren't fontified correctly.
;; * Untyped parameters aren't fontified correctly.
;; * Quotes immediately after string interpolation are marked as unclosed.
;; * Sexp movement doesn't properly ignore quotes in interpolation.
;; * Methods using "=>" can cause indentation woes.
;; * C and C++ modes seem to be hosed.
;; Definitions adapted from go-mode.el are
;;
;; gofmt-command gofmt-args gofmt-show-errors gofmt go--apply-rcs-patch
;; gofmt--kill-error-buffer gofmt--process-errors gofmt-before-save
;; go--goto-line go--delete-whole-line
;;; Code:
(require 'cl-lib)
(require 'compile)
(require 'dash)
(ignore-errors
(require 'flycheck))
(require 'help-mode)
(require 'json)
(require 'rx)
(require 's)
;;; Utility functions and macros
(defun dart-beginning-of-statement ()
"Moves to the beginning of a Dart statement.
Unlike `c-beginning-of-statement', this handles maps correctly
and will move to the top level of a bracketed statement."
(while
(progn
(back-to-indentation)
(while (eq (char-after) ?})
(forward-char)
(forward-sexp -1)
(back-to-indentation))
(when (not (dart--beginning-of-statement-p)) (forward-line -1)))))
(defun dart--beginning-of-statement-p ()
"Returns whether the point is at the beginning of a statement.
Statements are assumed to begin on their own lines. This returns
true for positions before the start of the statement, but on its line."
(and
(save-excursion
(skip-syntax-forward " ")
(not (or (bolp) (eq (char-after) ?}))))
(save-excursion
(skip-syntax-backward " ")
(when (bolp)
(cl-loop do (forward-char -1)
while (looking-at "^ *$"))
(skip-syntax-backward " ")
(cl-case (char-before)
((?} ?\;) t)
((?{) (dart-in-block-p (c-guess-basic-syntax))))))))
(defun dart--delete-whole-line (&optional arg)
"Delete the current line without putting it in the `kill-ring'.
Derived from function `kill-whole-line'. ARG is defined as for that
function."
(setq arg (or arg 1))
(if (and (> arg 0)
(eobp)
(save-excursion (forward-visible-line 0) (eobp)))
(signal 'end-of-buffer nil))
(if (and (< arg 0)
(bobp)
(save-excursion (end-of-visible-line) (bobp)))
(signal 'beginning-of-buffer nil))
(cond ((zerop arg)
(delete-region (progn (forward-visible-line 0) (point))
(progn (end-of-visible-line) (point))))
((< arg 0)
(delete-region (progn (end-of-visible-line) (point))
(progn (forward-visible-line (1+ arg))
(unless (bobp)
(backward-char))
(point))))
(t
(delete-region (progn (forward-visible-line 0) (point))
(progn (forward-visible-line arg) (point))))))
(defconst dart--identifier-re
"[a-zA-Z_$][a-zA-Z0-9_$]*"
"A regular expression that matches keywords.")
(defun dart--forward-identifier ()
"Moves the point forward through a Dart identifier."
(when (looking-at dart--identifier-re)
(goto-char (match-end 0))))
(defun dart--kill-buffer-and-window (buffer)
"Kills BUFFER, and its window if it has one.
This is different than `kill-buffer' because, if the buffer has a
window, it respects the `quit-restore' window parameter. See
`quit-window' for details."
(-if-let (window (get-buffer-window buffer))
(quit-window t window)
(kill-buffer buffer)))
(defun dart--get (alist &rest keys)
"Recursively calls `cdr' and `assoc' on ALIST with KEYS.
Returns the value rather than the full alist cell."
(--reduce-from (cdr (assoc it acc)) alist keys))
(defmacro dart--json-let (json fields &rest body)
"Assigns variables named FIELDS to the corresponding fields in JSON.
FIELDS may be either identifiers or (ELISP-IDENTIFIER JSON-IDENTIFIER) pairs."
(declare (indent 2))
(let ((json-value (make-symbol "json")))
`(let ((,json-value ,json))
(let ,(--map (if (symbolp it)
`(,it (dart--get ,json-value ',it))
(-let [(variable key) it]
`(,variable (dart--get ,json-value ',key))))
fields)
,@body))))
(defun dart--property-string (text prop value)
"Returns a copy of TEXT with PROP set to VALUE.
Converts TEXT to a string if it's not already."
(let ((copy (substring (format "%s" text) 0)))
(put-text-property 0 (length copy) prop value copy)
copy))
(defun dart--face-string (text face)
"Returns a copy of TEXT with its font face set to FACE.
Converts TEXT to a string if it's not already."
(dart--property-string text 'face face))
(defmacro dart--fontify-excursion (face &rest body)
"Applies FACE to the region moved over by BODY."
(declare (indent 1))
(-let [start (make-symbol "start")]
`(-let [,start (point)]
,@body
(put-text-property ,start (point) 'face ,face))))
(defun dart--flash-highlight (offset length)
"Briefly highlights the text defined by OFFSET and LENGTH.
OFFSET and LENGTH are expected to come from the analysis server,
rather than Elisp."
(-let [overlay (make-overlay (+ 1 offset) (+ 1 offset length))]
(overlay-put overlay 'face 'highlight)
(run-at-time "1 sec" nil (lambda () (delete-overlay overlay)))))
(defun dart--read-file (filename)
"Returns the contents of FILENAME."
(with-temp-buffer
(insert-file-contents filename)
(buffer-string)))
(defmacro dart--with-temp-file (name-variable &rest body)
"Creates a temporary file for the duration of BODY.
Assigns the filename to NAME-VARIABLE. Doesn't change the current buffer.
Returns the value of the last form in BODY."
(declare (indent 1))
`(-let [,name-variable (make-temp-file "dart-mode.")]
(unwind-protect
(progn ,@body)
(delete-file ,name-variable))))
(defun dart--run-process (executable &rest args)
"Runs EXECUTABLE with ARGS synchronously.
Returns (STDOUT STDERR EXIT-CODE)."
(dart--with-temp-file stderr-file
(with-temp-buffer
(-let [exit-code
(apply #'call-process
executable nil (list t stderr-file) nil args)]
(list
(buffer-string)
(dart--read-file stderr-file)
exit-code)))))
(defun dart--try-process (executable &rest args)
"Like `dart--run-process', but only returns stdout.
Any stderr is logged using dart-log. Returns nil if the exit code is non-0."
(-let [result (apply #'dart--run-process executable args)]
(unless (string-empty-p (nth 1 result))
(dart-log (format "Error running %S:\n%s" (cons executable args) (nth 1 result))))
(if (eq (nth 2 result) 0) (nth 0 result))))
(defvar dart--do-it-again-callback nil
"A callback to call when `dart-do-it-again' is invoked.
Only set in `dart-popup-mode'.")
(make-variable-buffer-local 'dart--do-it-again-callback)
;;; General configuration
(defcustom dart-sdk-path
;; Use Platform.resolvedExecutable so that this logic works through symlinks
;; and wrapper scripts.
(-when-let (dart (executable-find "dart"))
(dart--with-temp-file input
(with-temp-file input (insert "
import 'dart:io';
void main() {
print(Platform.resolvedExecutable);
}
"))
(-when-let (result (dart--try-process dart input))
(file-name-directory
(directory-file-name
(file-name-directory (string-trim result)))))))
"The absolute path to the root of the Dart SDK."
:group 'dart-mode
:type 'directory
:package-version '(dart-mode . "1.0.0"))
(defun dart-executable-path ()
"The absolute path to the 'dart' executable.
Returns nil if `dart-sdk-path' is nil."
(when dart-sdk-path
(concat dart-sdk-path
(file-name-as-directory "bin")
(if (memq system-type '(ms-dos windows-nt))
"dart.exe"
"dart"))))
;;; Configuration
(defvar dart-mode-map (make-sparse-keymap)
"Keymap used in dart-mode buffers.")
(define-key dart-mode-map (kbd "C-c ?") 'dart-show-hover)
(define-key dart-mode-map (kbd "C-c C-g") 'dart-goto)
(define-key dart-mode-map (kbd "C-c C-f") 'dart-find-refs)
(define-key dart-mode-map (kbd "C-c C-e") 'dart-find-member-decls)
(define-key dart-mode-map (kbd "C-c C-r") 'dart-find-member-refs)
(define-key dart-mode-map (kbd "C-c C-t") 'dart-find-top-level-decls)
(define-key dart-mode-map (kbd "C-c C-o") 'dart-format)
(define-key dart-mode-map (kbd "M-/") 'dart-expand)
(define-key dart-mode-map (kbd "M-?") 'dart-expand-parameters)
;;; Indentation support
(defun dart-indent-line-function ()
(let (pt)
(save-excursion
(back-to-indentation)
(let ((depth (car (syntax-ppss))))
(if (= (char-syntax (char-after)) ?\))
(setq depth (1- depth)))
(indent-line-to (* depth tab-width)))
(setq pt (point)))
(when (< (point) pt)
(back-to-indentation))))
;;; Additional fontification support
(setq dart--builtins
;; ECMA 408; Section: Identifier Reference
;; "Built-in identifiers"
'("abstract" "as" "deferred" "dynamic" "export" "external"
"factory" "get" "implements" "import" "library" "operator"
"part" "set" "static" "typedef"))
(setq dart--keywords
;; ECMA 408; Section: Reserved Words
'("assert" "break" "case" "catch" "class" "const" "continue"
"default" "do" "else" "enum" "extends" "false" "final"
"finally" "for" "if" "in" "is" "new" "null" "rethrow" "return"
"super" "switch" "this" "throw" "true" "try" "var" "void"
"while" "with"))
(setq dart--types '("double" "int" "num" "string"))
(setq dart--number-re
(rx (and symbol-start
(one-or-more digit)
(zero-or-one (and "." (one-or-more digit))))))
(setq dart-font-lock-defaults
`((,(regexp-opt dart--keywords 'words)
(,(regexp-opt dart--builtins 'words) . font-lock-builtin-face)
(,dart--number-re . font-lock-constant-face)
(,(regexp-opt dart--types 'words) . font-lock-type-face))))
(defun dart-fontify-region (beg end)
"Use fontify the region between BEG and END as Dart.
This will overwrite fontification due to strings and comments."
(->
(-let [font-lock-dont-widen t]
(narrow-to-region (- beg 1) end)
;; font-lock-fontify-region apparently isn't inclusive,
;; so we have to move the beginning back one char
(font-lock-fontify-region (point-min) (point-max)))
save-excursion save-match-data save-restriction))
(defun dart-limited-forward-sexp (limit &optional arg)
"Move forward using `forward-sexp' or to limit,
whichever comes first."
(let (forward-sexp-function)
(condition-case err
(save-restriction
(narrow-to-region (point) limit)
(forward-sexp arg))
(scan-error
(unless (equal (nth 1 err) "Unbalanced parentheses")
(signal 'scan-error (cdr err)))
(goto-char limit)))))
(defun dart-highlight-interpolation (limit)
"Highlight interpolation (${foo})."
(-let [start (point)]
(when (re-search-forward "\\(\\${\\)" limit t)
(if (elt (parse-partial-sexp start (point)) 3) ; in a string
(save-match-data
(forward-char -1)
(-let [beg (point)]
(dart-limited-forward-sexp limit)
(dart-fontify-region (+ 1 beg) (point)))
;; Highlight the end of the interpolation.
(when (eq (char-before) ?})
(put-text-property (- (point) 1) (point) 'face font-lock-variable-name-face))
t)
(looking-at "\\<\\>")))))
;;; Boilerplate font-lock piping
(defcustom dart-font-lock-extra-types nil
"*List of extra types (aside from the type keywords) to recognize in DART mode.
Each list item should be a regexp matching a single identifier."
:group 'dart-mode)
;;; Dart analysis server
(cl-defstruct
(dart--analysis-server
(:constructor dart--make-analysis-server))
"Struct containing data for an instance of a Dart analysis server.
The slots are:
- `process': the process of the running server.
- `buffer': the buffer where responses from the server are written."
process buffer)
(defgroup dart-mode nil
"Major mode for editing Dart code."
:group 'languages)
(defvar dart-debug nil
"If non-nil, enables writing debug messages for dart-mode.")
(defcustom dart-enable-analysis-server nil
"If non-nil, enables support for Dart analysis server.
The Dart analysis server adds support for error checking, code completion,
navigation, and more."
:group 'dart-mode
:type 'boolean
:package-version '(dart-mode . "0.12"))
(defvar dart--analysis-server nil
"The instance of the Dart analysis server we are communicating with.")
(defun dart--analysis-server-snapshot-path ()
"The absolute path to the snapshot file that runs the Dart analysis server."
(when dart-sdk-path
(concat dart-sdk-path
(file-name-as-directory "bin")
(file-name-as-directory "snapshots")
"analysis_server.dart.snapshot")))
(defvar dart-analysis-roots nil
"The list of analysis roots that are known to the analysis server.
All Dart files underneath the analysis roots are analyzed by the analysis
server.")
(defvar dart--analysis-server-next-id 0
"The ID to use for the next request to the Dart analysis server.")
(defvar dart--analysis-server-callbacks nil
"An alist of ID to callback to be called when the analysis server responds.
Each request to the analysis server has an associated ID. When the analysis
server sends a response to a request, it tags the response with the ID of the
request. We look up the callback for the request in this alist and run it with
the JSON decoded server response.")
(defvar dart--analysis-server-subscriptions nil
"An alist of event names to lists of callbacks to be called for those events.
These callbacks take the event object and an opaque subcription
object which can be passed to `dart--analysis-server-unsubscribe'.")
(defun dart-info (msg)
"Logs MSG to the dart log if `dart-debug' is non-nil."
(when dart-debug (dart-log msg)))
(defun dart-log (msg)
"Logs MSG to the dart log."
(let* ((log-buffer (get-buffer-create "*dart-debug*"))
(iso-format-string "%Y-%m-%dT%T%z")
(timestamp-and-log-string
(format-time-string iso-format-string (current-time))))
(with-current-buffer log-buffer
(goto-char (point-max))
(insert "\n\n\n")
(insert (concat timestamp-and-log-string
"\n"
msg))
(insert "\n"))))
(defun dart--normalize-path (path)
(if (equal system-type 'windows-nt)
(replace-regexp-in-string (rx "/") (rx "\\") path)
path))
(defun dart--start-analysis-server-for-current-buffer ()
"Initialize Dart analysis server for current buffer.
This starts Dart analysis server and adds either the pub root
directory or the current file directory to the analysis roots."
(unless dart--analysis-server (dart-start-analysis-server))
;; TODO(hterkelsen): Add this file to the priority files.
(dart-add-analysis-root-for-file)
(add-hook 'first-change-hook 'dart-add-analysis-overlay t t)
(add-hook 'after-change-functions 'dart-change-analysis-overlay t t)
(add-hook 'after-save-hook 'dart-remove-analysis-overlay t t)
(when (featurep 'flycheck)
(add-to-list 'flycheck-checkers 'dart-analysis-server)))
(defun dart-start-analysis-server ()
"Start the Dart analysis server.
Initializes analysis server support for all `dart-mode' buffers."
(when dart--analysis-server
(-let [process (dart--analysis-server-process dart--analysis-server)]
(when (process-live-p process) (kill-process process)))
(kill-buffer (dart--analysis-server-buffer dart--analysis-server)))
(let* ((process-connection-type nil)
(dart-process
(start-process "dart-analysis-server"
"*dart-analysis-server*"
(dart-executable-path)
(dart--analysis-server-snapshot-path))))
(set-process-query-on-exit-flag dart-process nil)
(setq dart--analysis-server
(dart--analysis-server-create dart-process)))
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(when (eq major-mode 'dart-mode)
(dart--start-analysis-server-for-current-buffer)
(when (buffer-modified-p buffer) (dart-add-analysis-overlay))))))
(defun dart--analysis-server-create (process)
"Create a Dart analysis server from PROCESS."
(-let [instance (dart--make-analysis-server
:process process
:buffer (generate-new-buffer (process-name process)))]
(buffer-disable-undo (dart--analysis-server-buffer instance))
(set-process-filter
process
(lambda (_ string)
(dart--analysis-server-process-filter instance string)))
instance))
(defun dart-add-analysis-overlay ()
"Report to the Dart analysis server that it should overlay this buffer.
The Dart analysis server allows clients to 'overlay' file contents with
a client-supplied string. This is needed because we want Emacs to report
errors for the current contents of the buffer, not whatever is saved to disk."
;; buffer-file-name can be nil within revert-buffer, but in that case the
;; buffer is just being reverted to its format on disk anyway.
(when buffer-file-name
(dart--analysis-server-send
"analysis.updateContent"
`((files
. ((,(dart--normalize-path buffer-file-name)
. ((type . "add")
(content
. ,(save-restriction (widen) (buffer-string)))))))))))
(defun dart-change-analysis-overlay
(change-begin change-end change-before-length)
"Report to analysis server that it should change the overlay for this buffer.
The region that changed ranges from CHANGE-BEGIN to CHANGE-END, and the
length of the text before the change is CHANGE-BEFORE-LENGTH. See also
`dart-add-analysis-overlay'."
(dart--analysis-server-send
"analysis.updateContent"
`((files
. ((,(dart--normalize-path buffer-file-name)
. ((type . "change")
(edits
. (((offset . ,(- change-begin 1))
(length . ,change-before-length)
(replacement
. ,(buffer-substring change-begin change-end))))))))))))
(defun dart-remove-analysis-overlay ()
"Remove the overlay for the current buffer since it has been saved.
See also `dart-add-analysis-overlay'."
(dart--analysis-server-send
"analysis.updateContent"
`((files . ((,(dart--normalize-path buffer-file-name) . ((type . "remove"))))))))
(defun dart-add-analysis-root-for-file (&optional file)
"Add the given FILE's root to the analysis server's analysis roots.
A file's root is the pub root if it is in a pub package, or the file's directory
otherwise. If no FILE is given, then this will default to the variable
`buffer-file-name'."
(let* ((file-to-add (or file buffer-file-name))
(pub-root (locate-dominating-file file-to-add "pubspec.yaml"))
(current-dir (file-name-directory file-to-add)))
(if pub-root
(dart-add-to-analysis-roots (directory-file-name (expand-file-name pub-root)))
(dart-add-to-analysis-roots (directory-file-name (expand-file-name current-dir))))))
(defun dart-add-to-analysis-roots (dir)
"Add DIR to the analysis server's analysis roots.
The analysis roots are directories that contain Dart files. The analysis server
analyzes all Dart files under the analysis roots and provides information about
them when requested."
(add-to-list 'dart-analysis-roots (dart--normalize-path dir))
(dart--send-analysis-roots))
(defun dart--send-analysis-roots ()
"Send the current list of analysis roots to the analysis server."
(dart--analysis-server-send
"analysis.setAnalysisRoots"
`(("included" . ,dart-analysis-roots)
("excluded" . nil))))
(defun dart--analysis-server-send (method &optional params callback)
"Send the METHOD request to the server with optional PARAMS.
PARAMS should be JSON-encodable. If you provide a CALLBACK, it will be called
with the JSON decoded response. Otherwise, the output will just be checked."
(-let [req-without-id (dart--analysis-server-make-request method params)]
(dart--analysis-server-enqueue req-without-id callback)))
(defun dart--analysis-server-make-request (method &optional params)
"Construct a request for the analysis server.
The constructed request will call METHOD with optional PARAMS."
`((method . ,method) (params . ,params)))
(defun dart--analysis-server-on-error-callback (response)
"If RESPONSE has an error, report it."
(-when-let (resp-err (assoc-default 'error response))
(error "Analysis server error: %s" (assoc-default 'message resp-err))))
(defun dart--analysis-server-enqueue (req-without-id callback)
"Send REQ-WITHOUT-ID to the analysis server, call CALLBACK with the result."
(setq dart--analysis-server-next-id (1+ dart--analysis-server-next-id))
(-let [request
(json-encode (cons (cons 'id (format "%s" dart--analysis-server-next-id))
req-without-id))]
;; Enqueue the request so that we can be sure all requests are processed in
;; order.
(push (cons dart--analysis-server-next-id
(or callback #'dart--analysis-server-on-error-callback))
dart--analysis-server-callbacks)
(cond
((not dart--analysis-server)
(message "Starting Dart analysis server.")
(dart-start-analysis-server))
((not (process-live-p (dart--analysis-server-process dart--analysis-server)))
(message "Dart analysis server crashed, restarting.")
(dart-start-analysis-server)))
(dart-info (concat "Sent: " request))
(process-send-string (dart--analysis-server-process dart--analysis-server)
(concat request "\n"))))
(cl-defun dart--analysis-server-process-filter (das string)
"Handle the event or method response from the dart analysis server.
The server DAS has STRING added to the buffer associated with it.
Method responses are paired according to their pending request and
the callback for that request is given the json decoded response."
(-let [buf (dart--analysis-server-buffer das)]
;; The buffer may have been killed if the server was restarted
(unless (buffer-live-p buf)
(cl-return-from dart--analysis-server-process-filter))
;; We use a buffer here because emacs might call the filter before the
;; entire line has been written out. In this case we store the
;; unterminated line in a buffer to be read when the rest of the line is
;; output.
(with-current-buffer buf
(goto-char (point-max))
(insert string)
(-let [buf-lines (s-lines (buffer-string))]
(delete-region (point-min) (point-max))
(insert (-last-item buf-lines))
(-let [messages
(--filter (and it (not (string-empty-p it)))
(-butlast buf-lines))]
(dolist (message messages)
(dart-info (concat "Received: " message))
(dart--analysis-server-handle-msg
(-let [json-array-type 'list]
(json-read-from-string message)))))))))
(defun dart--analysis-server-handle-msg (msg)
"Handle the parsed MSG from the analysis server."
(-if-let* ((raw-id (dart--get msg 'id))
(id (string-to-number raw-id)))
;; This is a response to a request, so we should invoke a callback in
;; dart--analysis-server-callbacks.
(-if-let (resp-closure (dart--get dart--analysis-server-callbacks id))
(progn
(setq dart--analysis-server-callbacks
(assq-delete-all id dart--analysis-server-callbacks))
(funcall resp-closure msg))
(-if-let (err (dart--get msg 'error))
(dart--analysis-server-on-error-callback msg)
(dart-info (format "No callback was associated with id %s" raw-id))))
;; This is a notification, so we should invoke callbacks in
;; dart--analysis-server-subscriptions.
(-when-let* ((event (dart--get msg 'event))
(params (dart--get msg 'params))
(callbacks (dart--get dart--analysis-server-subscriptions event)))
(dolist (callback callbacks)
(-let [subscription (cons event callback)]
(funcall callback params subscription))))))
(defun dart--analysis-server-subscribe (event callback)
"Registers CALLBACK to be called for each EVENT of the given type.
CALLBACK should take two parameters: the event object and an
opaque subscription object that can be passed to
`dart--analysis-server-unsubscribe'. Returns the same opaque
subscription object."
(-if-let (cell (assoc event dart--analysis-server-subscriptions))
(nconc cell (list callback))
(push (cons event (list callback)) dart--analysis-server-subscriptions))
(cons event callback))
(defun dart--analysis-server-unsubscribe (subscription)
"Unregisters the analysis server SUBSCRIPTION.
SUBSCRIPTION is an opaque object provided by
`dart--analysis-server-subscribe'."
(-let [(event . callback) subscription]
(delq callback (assoc event dart--analysis-server-subscriptions))))
;;;; Flycheck Error Reporting
(defun dart--flycheck-start (_ callback)
"Run the CHECKER and report the errors to the CALLBACK."
(dart-info (format "Checking syntax for %s" (current-buffer)))
(dart--analysis-server-send
"analysis.getErrors"
`((file . ,(dart--normalize-path (buffer-file-name))))
(-let [buffer (current-buffer)]
(lambda (response)
(dart--report-errors response buffer callback)))))
(when (featurep 'flycheck)
(flycheck-define-generic-checker
'dart-analysis-server
"Checks Dart source code for errors using Dart analysis server."
:start 'dart--flycheck-start
:modes '(dart-mode)))
(defun dart--report-errors (response buffer callback)
"Report the errors returned from the analysis server.
The errors contained in RESPONSE from Dart analysis server run on BUFFER are
reported to CALLBACK."
(dart-info (format "Reporting to flycheck: %s" response))
(-let [fly-errors (--map (dart--to-flycheck-err it buffer)
(dart--get response 'result 'errors))]
(dart-info (format "Parsed errors: %s" fly-errors))
(funcall callback 'finished fly-errors)))
(defun dart--to-flycheck-err (err buffer)
"Create a flycheck error from a dart ERR in BUFFER."
(flycheck-error-new
:buffer buffer
:checker 'dart-analysis-server
:filename (dart--get err 'location 'file)
:line (dart--get err 'location 'startLine)
:column (dart--get err 'location 'startColumn)
:message (dart--get err 'message)
:level (dart--severity-to-level (dart--get err 'severity))))
(defun dart--severity-to-level (severity)
"Convert SEVERITY to a flycheck level."
(cond
((string= severity "INFO") 'info)
((string= severity "WARNING") 'warning)
((string= severity "ERROR") 'error)))
;;;; Hover
(defun dart-show-hover (&optional show-in-buffer)
"Displays hover information for the current point.
With a prefix argument, opens a new buffer rather than using the
minibuffer."
(interactive "P")
(-when-let (filename (dart--normalize-path (buffer-file-name)))
(let ((show-in-buffer show-in-buffer)
(buffer (current-buffer))
(pos (point)))
(dart--analysis-server-send
"analysis.getHover"
`(("file" . ,filename) ("offset" . ,pos))
(lambda (response)
(-when-let (hover (car (dart--get response 'result 'hovers)))
(dart--json-let hover
(offset
length
dartdoc
(element-description elementDescription)
(element-kind elementKind)
(is-deprecated isDeprecated)
parameter)
(setq is-deprecated (not (eq is-deprecated :json-false)))
;; Briefly highlight the region that's being shown.
(with-current-buffer buffer
(dart--flash-highlight offset length))
(with-temp-buffer
(when is-deprecated
(insert (dart--face-string "DEPRECATED" 'font-lock-warning-face) ?\n))
(when element-description
(insert (dart--highlight-description element-description)
(dart--face-string (concat " (" element-kind ")") 'italic))
(when (or dartdoc parameter) (insert ?\n)))
(when parameter
(insert
(dart--highlight-description parameter)
(dart--face-string " (parameter type)" 'italic))
(when dartdoc) (insert ?\n))
(when dartdoc
(when (or element-description parameter) (insert ?\n))
(insert (dart--highlight-dartdoc dartdoc (not show-in-buffer))))
(let ((text (buffer-string)))
(if show-in-buffer
(with-current-buffer-window
"*Dart Analysis*" nil nil
(insert text)
(dart-popup-mode)
(setq dart--do-it-again-callback
(lambda ()
(save-excursion
(with-current-buffer buffer
(goto-char pos)
(dart-show-hover t))))))
(message "%s" text)))))))))))
(defconst dart--highlight-keyword-re
(regexp-opt
'("get" "set" "as" "abstract" "class" "extends" "implements" "enum" "typedef"
"const" "covariant" "deferred" "factory" "final" "import" "library" "new"
"operator" "part" "static" "async" "sync" "var")
'words)
"A regular expression that matches keywords.")
(defun dart--highlight-description (description)
"Returns a highlighted copy of DESCRIPTION."
(with-temp-buffer
(insert description)
(goto-char (point-min))
(while (not (eq (point) (point-max)))
(cond
;; A keyword.
((looking-at dart--highlight-keyword-re)
(dart--fontify-excursion 'font-lock-keyword-face
(goto-char (match-end 0))))
;; An identifier could be a function name or a type name.
((looking-at dart--identifier-re)
(goto-char (match-end 0))
(put-text-property
(match-beginning 0) (point) 'face
(if (dart--at-end-of-function-name-p) 'font-lock-function-name-face
'font-lock-type-face))
(cl-case (char-after)
;; Foo.bar()
(?.
(forward-char)
(dart--fontify-excursion 'font-lock-function-name-face
(dart--forward-identifier)))
;; Foo bar
(?\s
(forward-char)
(dart--fontify-excursion 'font-lock-variable-name-face
(dart--forward-identifier)))))
;; Anything else is punctuation that we ignore.
(t (forward-char))))
(buffer-string)))
(defun dart--at-end-of-function-name-p ()
"Returns whether the point is at the end of a function name."
(cl-case (char-after)
(?\( t)
(?<
(and (looking-at (concat "\\(" dart--identifier-re "\\|[<>]\\)*"))
(eq (char-after (match-end 0)) ?\()))))
(defun dart--highlight-dartdoc (dartdoc truncate)
"Returns a higlighted copy of DARTDOC."
(with-temp-buffer
(insert dartdoc)
;; Cut off long dartdocs so that the full signature is always visible.
(when truncate
(forward-line 11)
(delete-region (- (point) 1) (point-max)))
(goto-char (point-min))
(while (re-search-forward "\\[.*?\\]" nil t)
(put-text-property (match-beginning 0) (match-end 0)
'face 'font-lock-reference-face))
(buffer-string)))
;;;; Navigation
(defun dart-goto ()
(interactive)
(-when-let (filename (dart--normalize-path (buffer-file-name)))
(dart--analysis-server-send
"analysis.getNavigation"
`(("file" . ,filename) ("offset" . ,(point)) ("length" . 0))
(lambda (response)
(-when-let (result (dart--get response 'result))
(dart--json-let result (files targets regions)
(-when-let (region (car regions))
(let* ((target-index (car (dart--get region 'targets)))
(target (elt targets target-index))
(file-index (dart--get target 'fileIndex))
(offset (dart--get target 'offset))
(length (dart--get target 'length))
(file (elt files file-index)))
(find-file file)
(goto-char (+ 1 offset))
(dart--flash-highlight offset length)))))))))
;;;; Search
(defun dart-find-refs (pos &optional include-potential)
(interactive "dP")
(-when-let (filename (dart--normalize-path (buffer-file-name)))
(dart--analysis-server-send
"search.findElementReferences"
`(("file" . ,filename)
("offset" . ,pos)
("includePotential" . ,(or include-potential json-false)))
(let ((buffer (current-buffer))
(include-potential include-potential))
(lambda (response)
(-when-let (result (dart--get response 'result))
(let ((name (dart--get result 'element 'name))
(location (dart--get result 'element 'location)))
(dart--display-search-results
(dart--get result 'id)
(lambda ()
(setq dart--do-it-again-callback
(lambda ()
(with-current-buffer buffer
(dart-find-refs pos include-potential))))
(insert "References to ")
(insert-button
name
'action (lambda (_) (dart--goto-location location)))
(insert ":\n\n"))))))))))
(defun dart-find-member-decls (name)
"Find member declarations named NAME."
(interactive "sMember name: ")
(dart--find-by-name
"search.findMemberDeclarations" "name" name "Members named "))
(defun dart-find-member-refs (name)
"Find member references named NAME."
(interactive "sMember name: ")
(dart--find-by-name
"search.findMemberReferences" "name" name "References to "))
(defun dart-find-top-level-decls (name)
"Find top-level declarations named NAME."
(interactive "sDeclaration name: ")
(dart--find-by-name
"search.findTopLevelDeclarations" "pattern" name "Declarations matching "))
(defun dart--find-by-name (method argument name header)
"A helper function for running an analysis server search for NAME.
Calls the given analysis server METHOD passing NAME to the given
ARGUMENT. Displays a header beginning with HEADER in the results."
(dart--analysis-server-send
method
(list (cons argument name))
(lambda (response)