-
-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathgo-mode.el
3055 lines (2577 loc) · 111 KB
/
go-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
;;; go-mode.el --- Major mode for the Go programming language
;;; Commentary:
;; Copyright 2013 The go-mode Authors. All rights reserved.
;; Use of this source code is governed by a BSD-style
;; license that can be found in the LICENSE file.
;; Author: The go-mode Authors
;; Version: 1.6.0
;; Keywords: languages go
;; Package-Requires: ((emacs "26.1"))
;; URL: https://github.com/dominikh/go-mode.el
;;
;; This file is not part of GNU Emacs.
;;; Code:
(require 'cl-lib)
(require 'compile)
(require 'etags)
(require 'ffap)
(require 'find-file)
(require 'ring)
(require 'url)
(require 'xref)
(eval-when-compile
(defmacro go--forward-word (&optional arg)
(if (fboundp 'forward-word-strictly)
`(forward-word-strictly ,arg)
`(forward-word ,arg))))
(defun go--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))))))
(defun go-goto-opening-parenthesis (&optional _legacy-unused)
"Move up one level of parentheses.
Return non-nil if there was a paren to move up to."
;; The old implementation of go-goto-opening-parenthesis had an
;; optional argument to speed up the function. It didn't change the
;; function's outcome.
;; Silently fail if there's no matching opening parenthesis.
(let ((open-char (nth 1 (syntax-ppss))))
(when open-char
(goto-char open-char))))
(defconst go-dangling-operators-regexp "[^-]-\\|[^+]\\+\\|[/*&><.=|^]")
(defconst go--max-dangling-operator-length 2
"The maximum length of dangling operators.
This must be at least the length of the longest string matched by
‘go-dangling-operators-regexp’ and must be updated whenever that
constant is changed.")
(defconst go-identifier-regexp "[[:word:][:multibyte:]]+")
(defconst go-type-name-no-prefix-regexp "\\(?:[[:word:][:multibyte:]]+\\.\\)?[[:word:][:multibyte:]]+")
(defconst go-qualified-identifier-regexp (concat go-identifier-regexp "\\." go-identifier-regexp))
(defconst go-label-regexp go-identifier-regexp)
(defconst go-type-regexp "[[:word:][:multibyte:]*]+")
(defconst go-func-regexp (concat "\\_<func\\_>\\s *\\(" go-identifier-regexp "\\)"))
(defconst go-func-meth-regexp (concat
"\\_<func\\_>\\s *\\(?:(\\s *"
"\\(" go-identifier-regexp "\\s +\\)?" go-type-regexp
"\\s *)\\s *\\)?\\("
go-identifier-regexp
"\\)("))
(defconst go--comment-start-regexp "[[:space:]]*\\(?:/[/*]\\)")
(defconst go--case-regexp "\\([[:space:]]*case\\([[:space:]]\\|$\\)\\)")
(defconst go--case-or-default-regexp (concat "\\(" go--case-regexp "\\|" "[[:space:]]*default:\\)"))
(defconst go-builtins
'("append" "cap" "close" "complex" "copy"
"delete" "imag" "len" "make" "new"
"panic" "print" "println" "real" "recover")
"All built-in functions in the Go language. Used for font locking.")
(defconst go-mode-keywords
'("break" "default" "func" "interface" "select"
"case" "defer" "go" "map" "struct"
"chan" "else" "goto" "package" "switch"
"const" "fallthrough" "if" "range" "type"
"continue" "for" "import" "return" "var")
"All keywords in the Go language. Used for font locking.")
(defconst go-constants '("nil" "true" "false" "iota"))
(defconst go-type-name-regexp (concat "\\**\\(\\(?:" go-identifier-regexp "\\.\\)?" go-identifier-regexp "\\)"))
(defvar go-dangling-cache)
(defvar go-godoc-history nil)
(defvar go--coverage-current-file-name)
(defgroup go nil
"Major mode for editing Go code."
:link '(url-link "https://github.com/dominikh/go-mode.el")
:group 'languages)
(defgroup go-cover nil
"Options specific to `cover`."
:group 'go)
(defgroup godoc nil
"Options specific to `godoc'."
:group 'go)
(defcustom go-fontify-function-calls t
"Fontify function and method calls if this is non-nil."
:type 'boolean
:group 'go)
(defcustom go-fontify-variables t
"Fontify variable declarations if this is non-nil."
:type 'boolean
:group 'go)
(defcustom go-mode-hook nil
"Hook called by `go-mode'."
:type 'hook
:group 'go)
(defcustom go-command "go"
"The 'go' command.
Some users have multiple Go development trees and invoke the 'go'
tool via a wrapper that sets GOROOT and GOPATH based on the
current directory. Such users should customize this variable to
point to the wrapper script."
:type 'string
:group 'go)
(defcustom gofmt-command "gofmt"
"The 'gofmt' command.
Some users may replace this with 'goimports'
from https://golang.org/x/tools/cmd/goimports."
:type 'string
:group 'go)
(defcustom gofmt-args nil
"Additional arguments to pass to gofmt."
:type '(repeat string)
:group 'go)
(defcustom gofmt-show-errors 'buffer
"Where to display gofmt error output.
It can either be displayed in its own buffer, in the echo area, or not at all.
Please note that Emacs outputs to the echo area when writing
files and will overwrite gofmt's echo output if used from inside
a `before-save-hook'."
:type '(choice
(const :tag "Own buffer" buffer)
(const :tag "Echo area" echo)
(const :tag "None" nil))
:group 'go)
(defcustom godef-command "godef"
"The 'godef' command."
:type 'string
:group 'go)
(defcustom go-other-file-alist
'(("_test\\.go\\'" (".go"))
("\\.go\\'" ("_test.go")))
"See the documentation of `ff-other-file-alist' for details."
:type '(repeat (list regexp (choice (repeat string) function)))
:group 'go)
(defcustom go-packages-function 'go-packages-go-list
"Function called by `go-packages' to determine the list of available packages.
This is used in e.g. tab completion in `go-import-add'.
This package provides two functions: `go-packages-go-list' uses
'go list all' to determine all Go packages. `go-packages-native' uses
elisp to find all .a files in all /pkg/ directories.
`go-packages-native' is obsolete as it doesn't behave correctly with
the Go build cache or Go modules."
:type 'function
:package-version '(go-mode . 1.4.0)
:group 'go)
(defcustom go-guess-gopath-functions (list #'go-plain-gopath)
"Functions to call in sequence to detect a project's GOPATH.
The functions in this list will be called one after another,
until a function returns non-nil. The order of the functions in
this list is important, as some project layouts may superficially
look like others."
:type '(repeat function)
:group 'go)
(make-obsolete-variable 'go-guess-gopath-functions "GOPATH has been deprecated in favour of Go modules." "1.7.0")
(defcustom go-confirm-playground-uploads t
"Ask before uploading code to the public Go Playground.
Set this to nil to upload without prompting."
:type 'boolean
:group 'go)
(defcustom godoc-command "go doc"
"Which executable to use for `godoc'.
This can be either an absolute path or an executable in PATH."
:type 'string
:group 'go)
(defcustom godoc-and-godef-command "go doc"
"Which executable to use for `godoc-and-godef'.
This can be either an absolute path or an executable in PATH."
:type 'string
:group 'go)
(defcustom godoc-use-completing-read nil
"Provide auto-completion for godoc.
Only really desirable when using `godoc' instead of `go doc'."
:type 'boolean
:group 'godoc)
(defcustom godoc-reuse-buffer nil
"Reuse a single *godoc* buffer to display godoc-at-point calls.
The default behavior is to open a separate buffer for each call."
:type 'boolean
:group 'godoc)
(defcustom godoc-at-point-function #'godoc-and-godef
"Function to call to display the documentation for an
identifier at a given position.
This package provides two functions: `godoc-and-godef' uses a
combination of godef and godoc to find the documentation. This
approach has several caveats. See its documentation for more
information. The second function, `godoc-gogetdoc' uses an
additional tool that correctly determines the documentation for
any identifier. It provides better results than
`godoc-and-godef'."
:type 'function
:group 'godoc)
(defun godoc-and-godef (point)
"Use a combination of godef and godoc to guess the documentation at POINT.
Due to a limitation in godoc, it is not possible to differentiate
between functions and methods, which may cause `godoc-at-point'
to display more documentation than desired. Furthermore, it
doesn't work on package names or variables.
Consider using ‘godoc-gogetdoc’ instead for more accurate results."
(condition-case nil
(let* ((output (godef--call point))
(file (car output))
(name-parts (split-string (cadr output) " "))
(first (car name-parts)))
(if (not (godef--successful-p file))
(message "%s" (godef--error file))
(go--godoc (format "%s %s"
(file-name-directory file)
(if (or (string= first "type") (string= first "const"))
(cadr name-parts)
(car name-parts)))
godoc-and-godef-command)))
(file-error (message "Could not run godef binary"))))
(defun godoc-gogetdoc (point)
"Use the gogetdoc tool to find the documentation for an identifier at POINT.
You can install gogetdoc with 'go get -u github.com/zmb3/gogetdoc'."
(if (not (buffer-file-name (go--coverage-origin-buffer)))
;; TODO: gogetdoc supports unsaved files, but not introducing
;; new artificial files, so this limitation will stay for now.
(error "Cannot use gogetdoc on a buffer without a file name"))
(let ((posn (format "%s:#%d" (file-truename buffer-file-name) (1- (position-bytes point))))
(out (godoc--get-buffer "<at point>")))
(with-temp-buffer
(go--insert-modified-files)
(call-process-region (point-min) (point-max) "gogetdoc" nil out nil
"-modified"
(format "-pos=%s" posn)))
(with-current-buffer out
(goto-char (point-min))
(godoc-mode)
(display-buffer (current-buffer) t))))
(defun go--kill-new-message (url)
"Make URL the latest kill and print a message."
(kill-new url)
(message "%s" url))
(defcustom go-play-browse-function 'go--kill-new-message
"Function to call with the Playground URL.
See `go-play-region' for more details."
:type '(choice
(const :tag "Nothing" nil)
(const :tag "Kill + Message" go--kill-new-message)
(const :tag "Browse URL" browse-url)
(function :tag "Call function"))
:group 'go)
(defcustom go-coverage-display-buffer-func 'display-buffer-reuse-window
"How `go-coverage' should display the coverage buffer.
See `display-buffer' for a list of possible functions."
:type 'function
:group 'go-cover)
(defface go-coverage-untracked
'((t (:foreground "#505050")))
"Coverage color of untracked code."
:group 'go-cover)
(defface go-coverage-0
'((t (:foreground "#c00000")))
"Coverage color for uncovered code."
:group 'go-cover)
(defface go-coverage-1
'((t (:foreground "#808080")))
"Coverage color for covered code with weight 1."
:group 'go-cover)
(defface go-coverage-2
'((t (:foreground "#748c83")))
"Coverage color for covered code with weight 2."
:group 'go-cover)
(defface go-coverage-3
'((t (:foreground "#689886")))
"Coverage color for covered code with weight 3."
:group 'go-cover)
(defface go-coverage-4
'((t (:foreground "#5ca489")))
"Coverage color for covered code with weight 4."
:group 'go-cover)
(defface go-coverage-5
'((t (:foreground "#50b08c")))
"Coverage color for covered code with weight 5."
:group 'go-cover)
(defface go-coverage-6
'((t (:foreground "#44bc8f")))
"Coverage color for covered code with weight 6."
:group 'go-cover)
(defface go-coverage-7
'((t (:foreground "#38c892")))
"Coverage color for covered code with weight 7."
:group 'go-cover)
(defface go-coverage-8
'((t (:foreground "#2cd495")))
"Coverage color for covered code with weight 8.
For mode=set, all covered lines will have this weight."
:group 'go-cover)
(defface go-coverage-9
'((t (:foreground "#20e098")))
"Coverage color for covered code with weight 9."
:group 'go-cover)
(defface go-coverage-10
'((t (:foreground "#14ec9b")))
"Coverage color for covered code with weight 10."
:group 'go-cover)
(defface go-coverage-covered
'((t (:foreground "#2cd495")))
"Coverage color of covered code."
:group 'go-cover)
(defvar go-mode-syntax-table
(let ((st (make-syntax-table)))
(modify-syntax-entry ?+ "." st)
(modify-syntax-entry ?- "." st)
(modify-syntax-entry ?% "." st)
(modify-syntax-entry ?& "." st)
(modify-syntax-entry ?| "." st)
(modify-syntax-entry ?^ "." st)
(modify-syntax-entry ?! "." st)
(modify-syntax-entry ?= "." st)
(modify-syntax-entry ?< "." st)
(modify-syntax-entry ?> "." st)
(modify-syntax-entry ?/ ". 124b" st)
(modify-syntax-entry ?* ". 23" st)
(modify-syntax-entry ?\n "> b" st)
(modify-syntax-entry ?\" "\"" st)
(modify-syntax-entry ?\' "\"" st)
(modify-syntax-entry ?` "\"" st)
(modify-syntax-entry ?\\ "\\" st)
;; TODO make _ a symbol constituent now that xemacs is gone
(modify-syntax-entry ?_ "w" st)
st)
"Syntax table for Go mode.")
(defun go--fontify-type-switch-case-pre ()
"Move point to line following the end of case statement.
This is used as an anchored font lock keyword PRE-MATCH-FORM. We
expand the font lock region to include multiline type switch case
statements."
(save-excursion
(beginning-of-line)
(while (or (looking-at "[[:space:]]*\\($\\|//\\)") (go--line-suffix-p ","))
(forward-line))
(when (go--line-suffix-p ":")
(forward-line))
(point)))
(defun go--build-font-lock-keywords ()
;; we cannot use 'symbols in regexp-opt because GNU Emacs <24
;; doesn't understand that
(append
`(
;; Match param lists in func signatures. This uses the
;; MATCH-ANCHORED format (see `font-lock-keywords' docs).
;;
;; Parent/anchor match. It matches the param list opening "(".
(go--match-param-start
;; Sub-matcher that matches individual params in the param list.
(go--fontify-param
;; Pre-match form that runs before the first sub-match.
(go--fontify-param-pre)
;; Post-match form that runs after last sub-match.
(go--fontify-param-post)
;; Subexp 1 is the param variable name, if any.
(1 font-lock-variable-name-face nil t)
;; Subexp 2 is the param type name, if any. We set the LAXMATCH
;; flag to allow optional regex groups.
(2 font-lock-type-face nil t)))
;; Special case to match non-parenthesized function results. For
;; example, "func(i int) string".
(go--match-single-func-result 1 font-lock-type-face)
;; Match name+type pairs, such as "foo bar" in "var foo bar".
(go--match-ident-type-pair 2 font-lock-type-face)
;; An anchored matcher for type switch case clauses.
(go--match-type-switch-case
(go--fontify-type-switch-case
(go--fontify-type-switch-case-pre)
nil
(1 font-lock-type-face)))
;; Match variable names in var decls, constant names in const
;; decls, and type names in type decls.
(go--match-decl
(1 font-lock-variable-name-face nil t)
(2 font-lock-constant-face nil t)
(3 font-lock-type-face nil t))
(,(concat "\\_<" (regexp-opt go-mode-keywords t) "\\_>") . font-lock-keyword-face)
(,(concat "\\(\\_<" (regexp-opt go-builtins t) "\\_>\\)[[:space:]]*(") 1 font-lock-builtin-face)
(,(concat "\\_<" (regexp-opt go-constants t) "\\_>") . font-lock-constant-face)
;; Function (not method) name
(,go-func-regexp 1 font-lock-function-name-face))
(if go-fontify-function-calls
;; Function call/method name
`((,(concat "\\(" go-identifier-regexp "\\)[[:space:]]*(") 1 font-lock-function-name-face)
;; Bracketed function call
(,(concat "[^[:word:][:multibyte:]](\\(" go-identifier-regexp "\\))[[:space:]]*(") 1 font-lock-function-name-face))
;; Method name
`((,go-func-meth-regexp 2 font-lock-function-name-face)))
`(
;; Raw string literal, needed for font-lock-syntactic-keywords
("\\(`[^`]*`\\)" 1 font-lock-multiline)
;; RHS of type alias.
(go--match-type-alias 2 font-lock-type-face)
;; Arrays/slices: []<type> | [123]<type> | [some.Const]<type> | [someConst]<type> | [...]<type>
(,(concat "\\(?:^\\|[^[:word:][:multibyte:]]\\)\\[\\(?:[[:digit:]]+\\|" go-qualified-identifier-regexp "\\|" go-identifier-regexp "\\|\\.\\.\\.\\)?\\]" go-type-name-regexp) 1 font-lock-type-face)
;; Unary "!"
("\\(!\\)[^=]" 1 font-lock-negation-char-face)
;; Composite literal type
(,(concat go-type-name-regexp "{") 1 font-lock-type-face)
;; Map value type
(go--match-map-value 1 font-lock-type-face)
;; Map key type
(,(concat "\\_<map\\_>\\[" go-type-name-regexp) 1 font-lock-type-face)
;; Channel type
(,(concat "\\_<chan\\_>[[:space:]]*\\(?:<-[[:space:]]*\\)?" go-type-name-regexp) 1 font-lock-type-face)
;; "new()"/"make()" type
(,(concat "\\_<\\(?:new\\|make\\)\\_>\\(?:[[:space:]]\\|)\\)*(" go-type-name-regexp) 1 font-lock-type-face)
;; Type assertion
(,(concat "\\.\\s *(" go-type-name-regexp) 1 font-lock-type-face)
;; Composite literal field names and label definitions.
(go--match-ident-colon 1 font-lock-constant-face)
;; Labels in goto/break/continue
(,(concat "\\_<\\(?:goto\\|break\\|continue\\)\\_>[[:space:]]*\\(" go-label-regexp "\\)") 1 font-lock-constant-face))))
(let ((m (define-prefix-command 'go-goto-map)))
(define-key m "a" #'go-goto-arguments)
(define-key m "d" #'go-goto-docstring)
(define-key m "f" #'go-goto-function)
(define-key m "i" #'go-goto-imports)
(define-key m "m" #'go-goto-method-receiver)
(define-key m "n" #'go-goto-function-name)
(define-key m "r" #'go-goto-return-values))
(defvar go-mode-map
(let ((m (make-sparse-keymap)))
(unless (boundp 'electric-indent-chars)
(define-key m "}" #'go-mode-insert-and-indent)
(define-key m ")" #'go-mode-insert-and-indent))
(define-key m (kbd "C-c C-a") #'go-import-add)
(define-key m (kbd "C-c C-j") #'godef-jump)
(define-key m (kbd "C-x 4 C-c C-j") #'godef-jump-other-window)
(define-key m (kbd "C-c C-d") #'godef-describe)
(define-key m (kbd "C-c C-f") 'go-goto-map)
m)
"Keymap used by ‘go-mode’.")
(easy-menu-define go-mode-menu go-mode-map
"Menu for Go mode."
'("Go"
["Describe Expression" godef-describe t]
["Jump to Definition" godef-jump t]
"---"
["Add Import" go-import-add t]
["Go to Imports" go-goto-imports t]
"---"
("Playground"
["Send Buffer" go-play-buffer t]
["Send Region" go-play-region t]
["Download" go-download-play t])
"---"
["Coverage" go-coverage t]
["Gofmt" gofmt t]
["Godoc" godoc t]
"---"
["Customize Mode" (customize-group 'go) t]))
(defun go-mode-insert-and-indent (key)
"Invoke the global binding of KEY, then reindent the line."
(interactive (list (this-command-keys)))
(call-interactively (lookup-key (current-global-map) key))
(indent-according-to-mode))
(defmacro go-paren-level ()
`(car (syntax-ppss)))
(defmacro go-in-string-or-comment-p ()
`(nth 8 (syntax-ppss)))
(defmacro go-in-string-p ()
`(nth 3 (syntax-ppss)))
(defmacro go-in-comment-p ()
`(nth 4 (syntax-ppss)))
(defmacro go-goto-beginning-of-string-or-comment ()
`(goto-char (nth 8 (syntax-ppss))))
(defun go--backward-irrelevant (&optional stop-at-string)
"Skip backwards over any characters that are irrelevant for
indentation and related tasks.
It skips over whitespace, comments, cases and labels and, if
STOP-AT-STRING is not true, over strings."
(let (pos (start-pos (point)))
(skip-chars-backward "\n\s\t")
(if (and (save-excursion (beginning-of-line) (go-in-string-p))
(= (char-before) ?`)
(not stop-at-string))
(backward-char))
(if (and (go-in-string-p)
(not stop-at-string))
(go-goto-beginning-of-string-or-comment))
(if (looking-back "\\*/" (line-beginning-position))
(backward-char))
(if (go-in-comment-p)
(go-goto-beginning-of-string-or-comment))
(setq pos (point))
(beginning-of-line)
(if (or (looking-at (concat "^" go-label-regexp ":"))
(looking-at "^[[:space:]]*\\(case .+\\|default\\):"))
(end-of-line 0)
(goto-char pos))
(if (/= start-pos (point))
(go--backward-irrelevant stop-at-string))
(/= start-pos (point))))
(defun go--buffer-narrowed-p ()
"Return non-nil if the current buffer is narrowed."
(/= (buffer-size)
(- (point-max)
(point-min))))
(defun go-previous-line-has-dangling-op-p ()
"Return non-nil if the current line is a continuation line.
The return value is cached based on the current `line-beginning-position'."
(let* ((line-begin (line-beginning-position))
(val (gethash line-begin go-dangling-cache 'nope)))
(when (or (go--buffer-narrowed-p) (equal val 'nope))
(save-excursion
(go--forward-line -1)
(if (go--current-line-has-dangling-op-p)
(setq val (line-end-position))
(setq val nil))
(if (not (go--buffer-narrowed-p))
(puthash line-begin val go-dangling-cache))))
val))
(defun go--current-line-has-dangling-op-p ()
"Return non-nil if current line ends in a dangling operator.
The return value is not cached."
(or
(and
(go--line-suffix-p go-dangling-operators-regexp)
;; "=" does not behave like a dangling operator in decl statements.
(not (go--line-suffix-p "\\(?:var\\|type\\|const\\)[[:space:]].*="))
;; Don't mistake "1234." for a dangling operator.
(not (go--line-suffix-p "[[:space:]]-?[[:digit:]][_0-9]*\\.")))
;; treat comma as dangling operator in certain cases
(and
(go--line-suffix-p ",")
(save-excursion (end-of-line) (go--commas-indent-p)))))
(defun go--commas-indent-p ()
"Return non-nil if in a context where dangling commas indent next line."
(not (or
(go--open-paren-position)
(go--in-composite-literal-p)
(go--in-case-clause-list-p)
(go--in-struct-definition-p))))
(defun go--in-case-clause-list-p ()
"Return non-nil if inside a multi-line case cause list.
This function is only concerned with list items on lines after the
case keyword. It returns nil for the case line itself."
(save-excursion
(beginning-of-line)
(when (not (looking-at go--case-or-default-regexp))
(let (saw-colon)
;; optionally skip line with the colon
(when (go--line-suffix-p ":")
(setq saw-colon t)
(forward-line -1))
;; go backwards while at a comment or a line ending in comma
(while (and
(or
(go--boring-line-p)
(go--line-suffix-p ","))
(not (looking-at go--case-regexp))
(go--forward-line -1)))
(and
(looking-at-p go--case-regexp)
;; we weren't in case list if first line ended in colon
;; and the "case" line ended in colon
(not (and saw-colon (looking-at ".*:[[:space:]]*$"))))))))
(defun go--in-composite-literal-p ()
"Return non-nil if point is in a composite literal."
(save-excursion
(save-match-data
(and
(go-goto-opening-parenthesis)
;; Opening paren-like character is a curly.
(eq (char-after) ?{)
(or
;; Curly is preceded by non space (e.g. "Foo{"), definitely
;; composite literal.
(zerop (skip-syntax-backward " "))
;; Curly preceded by comma or semicolon. This is a composite
;; literal with implicit type name.
(looking-back "[,:]" (1- (point)))
;; If we made it to the beginning of line we are either a naked
;; block or a composite literal with implicit type name. If we
;; are the latter, we must be contained in another composite
;; literal.
(and (bolp) (go--in-composite-literal-p)))))))
(defun go--in-paren-with-prefix-p (paren prefix)
(save-excursion
(and
(go-goto-opening-parenthesis)
(eq (char-after) paren)
(skip-syntax-backward " ")
(> (point) (length prefix))
(string= prefix (buffer-substring (- (point) (length prefix)) (point))))))
(defun go--in-struct-definition-p ()
"Return non-nil if point is inside a struct definition."
(go--in-paren-with-prefix-p ?{ "struct"))
(defun go--in-interface-p ()
"Return non-nil if point is inside an interface definition."
(go--in-paren-with-prefix-p ?{ "interface"))
(defun go--in-type-switch-p ()
"Return non-nil if point is inside a type switch statement."
(go--in-paren-with-prefix-p ?{ ".(type)"))
(defun go--open-paren-position ()
"Return non-nil if point is between '(' and ')'.
The return value is the position of the opening paren."
(save-excursion
(let ((start-paren-level (go-paren-level)))
(and
(go-goto-opening-parenthesis)
;; opening paren-like character is actually a paren
(eq (char-after) ?\()
;; point is before the closing paren
(< (go-paren-level) start-paren-level)
(point)))))
(defun go-indentation-at-point ()
"Return the appropriate indentation for the current line."
(save-excursion
(beginning-of-line)
(if (go-in-comment-p)
(go--multiline-comment-indent)
(go--indentation-at-point))))
;; It's unfortunate that the user cannot reindent the current line to
;; align with the previous line; however, if they could, then people
;; who use reindent-then-newline-and-indent wouldn't be able to
;; explicitly indent lines inside comments.
(defun go--multiline-comment-indent ()
"Return the appropriate indent inside multiline comment.
Assumes point is at beginning of line within comment. This
function has basic logic to indent as you add new lines to a
multiline comment, and to line up all the `*' if each line starts
with `*'. The gofmt behavior for multiline comments is
surprisingly complex and strange/buggy, so we just aim to do
something simple rather than encode all the subtle behavior."
(let* (;; Indent of current line.
(indent (current-indentation))
;; Indent of opening "/*".
start-indent
;; Default indent to use based on preceding context.
natural-indent
;; Non-nil means keep existing indent and give up calculating indent.
give-up
;; Whether all comment lines (except first) begin with "*".
(all-star t))
(save-excursion
(go-goto-beginning-of-string-or-comment)
(setq start-indent (current-indentation))
;; If other stuff precedes start of multiline comment, give up.
(setq give-up (/= (current-column) start-indent))
;; Skip "/*".
(forward-char 2)
(skip-syntax-forward " ")
(if (not (eolp))
;; If we aren't at EOL, we have content on the first line.
;; Base our natural indent on that.
(setq natural-indent (current-column))
;; Otherwise default to 1 space beyond "/*".
(setq natural-indent (+ start-indent 3)))
(let (done)
(while (not done)
(setq done (or (looking-at ".*\\*/") (not (zerop (forward-line)))))
(setq all-star (and all-star (looking-at "[[:space:]]*\\*"))))))
;; If previous line has comment content, use its indent as our
;; natural indent.
(save-excursion
(when (zerop (forward-line -1))
(beginning-of-line)
(when (and (go-in-comment-p) (> (current-indentation) 0))
(setq natural-indent (current-indentation)))))
(cond
(give-up indent)
(all-star (1+ start-indent))
;; Closing "*/" with no preceding content always lines up with "/*".
((looking-at "[[:space:]]*\\*/") start-indent)
;; If the line is already indented, leave it.
(t (if (zerop indent) natural-indent indent)))))
(defun go--indentation-at-point ()
"Return the appropriate indentation for the current non-comment line.
This function works by walking a line's characters backwards. When it
encounters a closing paren or brace it bounces to the corresponding
opener. If it arrives at the beginning of the line you are indenting,
it moves to the end of the previous line if the current line is a
continuation line, else it moves to the containing opening paren or
brace. If it arrives at the beginning of a line other than the line
you are indenting, it will continue to the previous dangling line if
the line you are indenting was not a continuation line, otherwise it
is done."
(save-excursion
(beginning-of-line)
(let (
;; Beginning of our starting line.
(start-line (point))
;; Whether this is our first iteration of the outer while loop.
(first t)
;; Whether we start in a block (i.e. our first line is not a
;; continuation line and is in an "if", "for", etc. block).
(in-block)
;; Our desired indent relative to our ending line's indent.
(indent 0))
;; Skip leading whitespace.
(skip-syntax-forward " ")
;; Decrement indent if the first character on the line is a closer.
(when (or (eq (char-after) ?\)) (eq (char-after) ?}))
(cl-decf indent tab-width))
(while (or
;; Always run the first iteration so we process empty lines.
first
;; Otherwise stop if we are at the start of a line.
(not (bolp)))
(setq first nil)
(cl-case (char-before)
;; We have found a closer (paren or brace).
((?\) ?})
(backward-char)
(let ((bol (line-beginning-position)))
;; Jump back to corresponding opener.
(go-goto-opening-parenthesis)
;; Here we decrement the indent if we are closing an indented
;; expression. In other words, the closer's line was indented
;; relative to the opener's line, and that indent should not
;; be inherited by our starting line.
(when (and
;; We care about dangling expressions, not child blocks.
(not in-block)
;; Opener and closer aren't on same line.
(< (point) bol)
(go-previous-line-has-dangling-op-p)
;; Opener is at same paren level as start of line (ignore sub-expressions).
(eq (go-paren-level) (save-excursion (beginning-of-line) (go-paren-level)))
;; This dangling line opened indent relative to previous dangling line.
(go--continuation-line-indents-p))
(cl-decf indent tab-width))))
;; Brackets don't affect indentation, so just skip them.
((?\])
(backward-char)))
;; Skip non-closers since we are only interested in closing parens/braces.
(skip-syntax-backward "^)" (line-beginning-position))
(when (go-in-string-or-comment-p)
(go-goto-beginning-of-string-or-comment))
;; At the beginning of the starting line.
(when (= start-line (point))
;; We are a continuation line.
(if (go-previous-line-has-dangling-op-p)
(progn
;; Presume a continuation line always gets an extra indent.
;; We reduce the indent after the loop, if necessary.
(cl-incf indent tab-width)
;; Go to the end of the dangling line.
(goto-char (go-previous-line-has-dangling-op-p)))
;; If we aren't a continuation line and we have an enclosing paren
;; or brace, jump to opener and increment our indent.
(when (go-goto-opening-parenthesis)
(setq in-block (go--flow-block-p))
(cl-incf indent tab-width))))
;; If we started in a child block we must follow dangling lines
;; until they don't dangle anymore. This is to handle cases like:
;;
;; if foo ||
;; foo &&
;; foo {
;; X
;;
;; There can be an arbitrary number of indents, so we must go back to
;; the "if" to determine the indent of "X".
(when (and in-block (bolp) (go-previous-line-has-dangling-op-p))
(goto-char (go-previous-line-has-dangling-op-p))))
;; If our ending line is a continuation line but doesn't open
;; an extra indent, reduce indent. We tentatively gave indents to all
;; dangling lines and all lines inside open parens, so here we take that
;; indent back.
;;
;; 1 + 1 +
;; ending line 1 + foo( 1 + foo(
;; starting line 1, becomes 1,
;; ) )
;;
;;
;; 1 + 1 +
;; ending line 1 + becomes 1 +
;; starting line 1 1
(when (and
(go-previous-line-has-dangling-op-p)
(not (go--continuation-line-indents-p)))
(cl-decf indent tab-width))
;; Apply our computed indent relative to the indent of the
;; ending line, or 0 if we are at the top level.
(if (and
(= 0 (go-paren-level))
(not (go-previous-line-has-dangling-op-p)))
indent
(+ indent (current-indentation))))))
(defconst go--operator-chars "*/%<>&\\^+\\-|=!,."
"Individual characters that appear in operators.
Comma and period are included because they can be dangling operators, so
they need to be considered by `go--continuation-line-indents-p'")
(defun go--operator-precedence (op)
"Go operator precedence (higher binds tighter)."
(cl-case (intern op)
(\. 7) ; "." in "foo.bar", binds tightest
(! 6)
((* / % << >> & &^) 5)
((+ - | ^) 4)
((== != < <= > >=) 3)
(&& 2)
(|| 1)
(t 0)))
(defun go--flow-block-p ()
"Return whether looking at a { that opens a control flow block.
We check for a { that is preceded by a space and is not a func
literal opening brace."
(save-excursion
(when (and
(eq (char-after) ?{)
(not (zerop (skip-syntax-backward " "))))
(let ((eol (line-end-position))