xref: /vim-8.2.3635/runtime/syntax/go.vim (revision 89a9c159)
1" Copyright 2009 The Go Authors. All rights reserved.
2" Use of this source code is governed by a BSD-style
3" license that can be found in the LICENSE file.
4"
5" go.vim: Vim syntax file for Go.
6" Language:             Go
7" Maintainer:           Billie Cleek <[email protected]>
8" Latest Revision:      2021-06-26
9" License:              BSD-style. See LICENSE file in source repository.
10" Repository:           https://github.com/fatih/vim-go
11
12" Quit when a (custom) syntax file was already loaded
13if exists("b:current_syntax")
14  finish
15endif
16
17let s:keepcpo = &cpo
18set cpo&vim
19
20function! s:FoldEnable(...) abort
21  if a:0 > 0
22    return index(s:FoldEnable(), a:1) > -1
23  endif
24  return get(g:, 'go_fold_enable', ['block', 'import', 'varconst', 'package_comment'])
25endfunction
26
27function! s:HighlightArrayWhitespaceError() abort
28  return get(g:, 'go_highlight_array_whitespace_error', 0)
29endfunction
30
31function! s:HighlightChanWhitespaceError() abort
32  return get(g:, 'go_highlight_chan_whitespace_error', 0)
33endfunction
34
35function! s:HighlightExtraTypes() abort
36  return get(g:, 'go_highlight_extra_types', 0)
37endfunction
38
39function! s:HighlightSpaceTabError() abort
40  return get(g:, 'go_highlight_space_tab_error', 0)
41endfunction
42
43function! s:HighlightTrailingWhitespaceError() abort
44  return get(g:, 'go_highlight_trailing_whitespace_error', 0)
45endfunction
46
47function! s:HighlightOperators() abort
48  return get(g:, 'go_highlight_operators', 0)
49endfunction
50
51function! s:HighlightFunctions() abort
52  return get(g:, 'go_highlight_functions', 0)
53endfunction
54
55function! s:HighlightFunctionParameters() abort
56  return get(g:, 'go_highlight_function_parameters', 0)
57endfunction
58
59function! s:HighlightFunctionCalls() abort
60  return get(g:, 'go_highlight_function_calls', 0)
61endfunction
62
63function! s:HighlightFields() abort
64  return get(g:, 'go_highlight_fields', 0)
65endfunction
66
67function! s:HighlightTypes() abort
68  return get(g:, 'go_highlight_types', 0)
69endfunction
70
71function! s:HighlightBuildConstraints() abort
72  return get(g:, 'go_highlight_build_constraints', 0)
73endfunction
74
75function! s:HighlightStringSpellcheck() abort
76  return get(g:, 'go_highlight_string_spellcheck', 1)
77endfunction
78
79function! s:HighlightFormatStrings() abort
80  return get(g:, 'go_highlight_format_strings', 1)
81endfunction
82
83function! s:HighlightGenerateTags() abort
84  return get(g:, 'go_highlight_generate_tags', 0)
85endfunction
86
87function! s:HighlightVariableAssignments() abort
88  return get(g:, 'go_highlight_variable_assignments', 0)
89endfunction
90
91function! s:HighlightVariableDeclarations() abort
92  return get(g:, 'go_highlight_variable_declarations', 0)
93endfunction
94
95syn case match
96
97syn keyword     goPackage           package
98syn keyword     goImport            import    contained
99syn keyword     goVar               var       contained
100syn keyword     goConst             const     contained
101
102hi def link     goPackage           Statement
103hi def link     goImport            Statement
104hi def link     goVar               Keyword
105hi def link     goConst             Keyword
106hi def link     goDeclaration       Keyword
107
108" Keywords within functions
109syn keyword     goStatement         defer go goto return break continue fallthrough
110syn keyword     goConditional       if else switch select
111syn keyword     goLabel             case default
112syn keyword     goRepeat            for range
113
114hi def link     goStatement         Statement
115hi def link     goConditional       Conditional
116hi def link     goLabel             Label
117hi def link     goRepeat            Repeat
118
119" Predefined types
120syn keyword     goType              chan map bool string error
121syn keyword     goSignedInts        int int8 int16 int32 int64 rune
122syn keyword     goUnsignedInts      byte uint uint8 uint16 uint32 uint64 uintptr
123syn keyword     goFloats            float32 float64
124syn keyword     goComplexes         complex64 complex128
125
126hi def link     goType              Type
127hi def link     goSignedInts        Type
128hi def link     goUnsignedInts      Type
129hi def link     goFloats            Type
130hi def link     goComplexes         Type
131
132" Predefined functions and values
133syn keyword     goBuiltins                 append cap close complex copy delete imag len
134syn keyword     goBuiltins                 make new panic print println real recover
135syn keyword     goBoolean                  true false
136syn keyword     goPredefinedIdentifiers    nil iota
137
138hi def link     goBuiltins                 Identifier
139hi def link     goBoolean                  Boolean
140hi def link     goPredefinedIdentifiers    goBoolean
141
142" Comments; their contents
143syn keyword     goTodo              contained TODO FIXME XXX BUG
144syn cluster     goCommentGroup      contains=goTodo
145
146syn region      goComment           start="//" end="$" contains=goGenerate,@goCommentGroup,@Spell
147if s:FoldEnable('comment')
148  syn region    goComment           start="/\*" end="\*/" contains=@goCommentGroup,@Spell fold
149  syn match     goComment           "\v(^\s*//.*\n)+" contains=goGenerate,@goCommentGroup,@Spell fold
150else
151  syn region    goComment           start="/\*" end="\*/" contains=@goCommentGroup,@Spell
152endif
153
154hi def link     goComment           Comment
155hi def link     goTodo              Todo
156
157if s:HighlightGenerateTags()
158  syn match       goGenerateVariables contained /\%(\$GOARCH\|\$GOOS\|\$GOFILE\|\$GOLINE\|\$GOPACKAGE\|\$DOLLAR\)\>/
159  syn region      goGenerate          start="^\s*//go:generate" end="$" contains=goGenerateVariables
160  hi def link     goGenerate          PreProc
161  hi def link     goGenerateVariables Special
162endif
163
164" Go escapes
165syn match       goEscapeOctal       display contained "\\[0-7]\{3}"
166syn match       goEscapeC           display contained +\\[abfnrtv\\'"]+
167syn match       goEscapeX           display contained "\\x\x\{2}"
168syn match       goEscapeU           display contained "\\u\x\{4}"
169syn match       goEscapeBigU        display contained "\\U\x\{8}"
170syn match       goEscapeError       display contained +\\[^0-7xuUabfnrtv\\'"]+
171
172hi def link     goEscapeOctal       goSpecialString
173hi def link     goEscapeC           goSpecialString
174hi def link     goEscapeX           goSpecialString
175hi def link     goEscapeU           goSpecialString
176hi def link     goEscapeBigU        goSpecialString
177hi def link     goSpecialString     Special
178hi def link     goEscapeError       Error
179
180" Strings and their contents
181syn cluster     goStringGroup       contains=goEscapeOctal,goEscapeC,goEscapeX,goEscapeU,goEscapeBigU,goEscapeError
182if s:HighlightStringSpellcheck()
183  syn region      goString            start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=@goStringGroup,@Spell
184  syn region      goRawString         start=+`+ end=+`+ contains=@Spell
185else
186  syn region      goString            start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=@goStringGroup
187  syn region      goRawString         start=+`+ end=+`+
188endif
189
190if s:HighlightFormatStrings()
191  " [n] notation is valid for specifying explicit argument indexes
192  " 1. Match a literal % not preceded by a %.
193  " 2. Match any number of -, #, 0, space, or +
194  " 3. Match * or [n]* or any number or nothing before a .
195  " 4. Match * or [n]* or any number or nothing after a .
196  " 5. Match [n] or nothing before a verb
197  " 6. Match a formatting verb
198  syn match       goFormatSpecifier   /\
199        \%([^%]\%(%%\)*\)\
200        \@<=%[-#0 +]*\
201        \%(\%(\%(\[\d\+\]\)\=\*\)\|\d\+\)\=\
202        \%(\.\%(\%(\%(\[\d\+\]\)\=\*\)\|\d\+\)\=\)\=\
203        \%(\[\d\+\]\)\=[vTtbcdoqxXUeEfFgGspw]/ contained containedin=goString,goRawString
204  hi def link     goFormatSpecifier   goSpecialString
205endif
206
207hi def link     goString            String
208hi def link     goRawString         String
209
210" Characters; their contents
211syn cluster     goCharacterGroup    contains=goEscapeOctal,goEscapeC,goEscapeX,goEscapeU,goEscapeBigU
212syn region      goCharacter         start=+'+ skip=+\\\\\|\\'+ end=+'+ contains=@goCharacterGroup
213
214hi def link     goCharacter         Character
215
216" Regions
217syn region      goParen             start='(' end=')' transparent
218if s:FoldEnable('block')
219  syn region    goBlock             start="{" end="}" transparent fold
220else
221  syn region    goBlock             start="{" end="}" transparent
222endif
223
224" import
225if s:FoldEnable('import')
226  syn region    goImport            start='import (' end=')' transparent fold contains=goImport,goString,goComment
227else
228  syn region    goImport            start='import (' end=')' transparent contains=goImport,goString,goComment
229endif
230
231" var, const
232if s:FoldEnable('varconst')
233  syn region    goVar               start='var ('   end='^\s*)$' transparent fold
234                        \ contains=ALLBUT,goParen,goBlock,goFunction,goTypeName,goReceiverType,goReceiverVar,goParamName,goParamType,goSimpleParams,goPointerOperator
235  syn region    goConst             start='const (' end='^\s*)$' transparent fold
236                        \ contains=ALLBUT,goParen,goBlock,goFunction,goTypeName,goReceiverType,goReceiverVar,goParamName,goParamType,goSimpleParams,goPointerOperator
237else
238  syn region    goVar               start='var ('   end='^\s*)$' transparent
239                        \ contains=ALLBUT,goParen,goBlock,goFunction,goTypeName,goReceiverType,goReceiverVar,goParamName,goParamType,goSimpleParams,goPointerOperator
240  syn region    goConst             start='const (' end='^\s*)$' transparent
241                        \ contains=ALLBUT,goParen,goBlock,goFunction,goTypeName,goReceiverType,goReceiverVar,goParamName,goParamType,goSimpleParams,goPointerOperator
242endif
243
244" Single-line var, const, and import.
245syn match       goSingleDecl        /\%(import\|var\|const\) [^(]\@=/ contains=goImport,goVar,goConst
246
247" Integers
248syn match       goDecimalInt        "\<-\=\(0\|[1-9]_\?\(\d\|\d\+_\?\d\+\)*\)\%([Ee][-+]\=\d\+\)\=\>"
249syn match       goDecimalError      "\<-\=\(_\(\d\+_*\)\+\|\([1-9]\d*_*\)\+__\(\d\+_*\)\+\|\([1-9]\d*_*\)\+_\+\)\%([Ee][-+]\=\d\+\)\=\>"
250syn match       goHexadecimalInt    "\<-\=0[xX]_\?\(\x\+_\?\)\+\>"
251syn match       goHexadecimalError  "\<-\=0[xX]_\?\(\x\+_\?\)*\(\([^ \t0-9A-Fa-f_)]\|__\)\S*\|_\)\>"
252syn match       goOctalInt          "\<-\=0[oO]\?_\?\(\o\+_\?\)\+\>"
253syn match       goOctalError        "\<-\=0[0-7oO_]*\(\([^ \t0-7oOxX_/)\]\}\:]\|[oO]\{2,\}\|__\)\S*\|_\|[oOxX]\)\>"
254syn match       goBinaryInt         "\<-\=0[bB]_\?\([01]\+_\?\)\+\>"
255syn match       goBinaryError       "\<-\=0[bB]_\?[01_]*\([^ \t01_)]\S*\|__\S*\|_\)\>"
256
257hi def link     goDecimalInt        Integer
258hi def link     goDecimalError      Error
259hi def link     goHexadecimalInt    Integer
260hi def link     goHexadecimalError  Error
261hi def link     goOctalInt          Integer
262hi def link     goOctalError        Error
263hi def link     goBinaryInt         Integer
264hi def link     goBinaryError       Error
265hi def link     Integer             Number
266
267" Floating point
268syn match       goFloat             "\<-\=\d\+\.\d*\%([Ee][-+]\=\d\+\)\=\>"
269syn match       goFloat             "\<-\=\.\d\+\%([Ee][-+]\=\d\+\)\=\>"
270
271hi def link     goFloat             Float
272
273" Imaginary literals
274syn match       goImaginary         "\<-\=\d\+i\>"
275syn match       goImaginary         "\<-\=\d\+[Ee][-+]\=\d\+i\>"
276syn match       goImaginaryFloat    "\<-\=\d\+\.\d*\%([Ee][-+]\=\d\+\)\=i\>"
277syn match       goImaginaryFloat    "\<-\=\.\d\+\%([Ee][-+]\=\d\+\)\=i\>"
278
279hi def link     goImaginary         Number
280hi def link     goImaginaryFloat    Float
281
282" Spaces after "[]"
283if s:HighlightArrayWhitespaceError()
284  syn match goSpaceError display "\%(\[\]\)\@<=\s\+"
285endif
286
287" Spacing errors around the 'chan' keyword
288if s:HighlightChanWhitespaceError()
289  " receive-only annotation on chan type
290  "
291  " \(\<chan\>\)\@<!<-  (only pick arrow when it doesn't come after a chan)
292  " this prevents picking up 'chan<- chan<-' but not '<- chan'
293  syn match goSpaceError display "\%(\%(\<chan\>\)\@<!<-\)\@<=\s\+\%(\<chan\>\)\@="
294
295  " send-only annotation on chan type
296  "
297  " \(<-\)\@<!\<chan\>  (only pick chan when it doesn't come after an arrow)
298  " this prevents picking up '<-chan <-chan' but not 'chan <-'
299  syn match goSpaceError display "\%(\%(<-\)\@<!\<chan\>\)\@<=\s\+\%(<-\)\@="
300
301  " value-ignoring receives in a few contexts
302  syn match goSpaceError display "\%(\%(^\|[={(,;]\)\s*<-\)\@<=\s\+"
303endif
304
305" Extra types commonly seen
306if s:HighlightExtraTypes()
307  syn match goExtraType /\<bytes\.\%(Buffer\)\>/
308  syn match goExtraType /\<context\.\%(Context\)\>/
309  syn match goExtraType /\<io\.\%(Reader\|ReadSeeker\|ReadWriter\|ReadCloser\|ReadWriteCloser\|Writer\|WriteCloser\|Seeker\)\>/
310  syn match goExtraType /\<reflect\.\%(Kind\|Type\|Value\)\>/
311  syn match goExtraType /\<unsafe\.Pointer\>/
312endif
313
314" Space-tab error
315if s:HighlightSpaceTabError()
316  syn match goSpaceError display " \+\t"me=e-1
317endif
318
319" Trailing white space error
320if s:HighlightTrailingWhitespaceError()
321  syn match goSpaceError display excludenl "\s\+$"
322endif
323
324hi def link     goExtraType         Type
325hi def link     goSpaceError        Error
326
327
328
329" included from: https://github.com/athom/more-colorful.vim/blob/master/after/syntax/go.vim
330"
331" Comments; their contents
332syn keyword     goTodo              contained NOTE
333hi def link     goTodo              Todo
334
335syn match goVarArgs /\.\.\./
336
337" Operators;
338if s:HighlightOperators()
339  " match single-char operators:          - + % < > ! & | ^ * =
340  " and corresponding two-char operators: -= += %= <= >= != &= |= ^= *= ==
341  syn match goOperator /[-+%<>!&|^*=]=\?/
342  " match / and /=
343  syn match goOperator /\/\%(=\|\ze[^/*]\)/
344  " match two-char operators:               << >> &^
345  " and corresponding three-char operators: <<= >>= &^=
346  syn match goOperator /\%(<<\|>>\|&^\)=\?/
347  " match remaining two-char operators: := && || <- ++ --
348  syn match goOperator /:=\|||\|<-\|++\|--/
349  " match ...
350
351  hi def link     goPointerOperator   goOperator
352  hi def link     goVarArgs           goOperator
353endif
354hi def link     goOperator          Operator
355
356" Functions;
357if s:HighlightFunctions() || s:HighlightFunctionParameters()
358  syn match goDeclaration       /\<func\>/ nextgroup=goReceiver,goFunction,goSimpleParams skipwhite skipnl
359  syn match goReceiverVar       /\w\+\ze\s\+\%(\w\|\*\)/ nextgroup=goPointerOperator,goReceiverType skipwhite skipnl contained
360  syn match goPointerOperator   /\*/ nextgroup=goReceiverType contained skipwhite skipnl
361  syn match goFunction          /\w\+/ nextgroup=goSimpleParams contained skipwhite skipnl
362  syn match goReceiverType      /\w\+/ contained
363  if s:HighlightFunctionParameters()
364    syn match goSimpleParams      /(\%(\w\|\_s\|[*\.\[\],\{\}<>-]\)*)/ contained contains=goParamName,goType nextgroup=goFunctionReturn skipwhite skipnl
365    syn match goFunctionReturn   /(\%(\w\|\_s\|[*\.\[\],\{\}<>-]\)*)/ contained contains=goParamName,goType skipwhite skipnl
366    syn match goParamName        /\w\+\%(\s*,\s*\w\+\)*\ze\s\+\%(\w\|\.\|\*\|\[\)/ contained nextgroup=goParamType skipwhite skipnl
367    syn match goParamType        /\%([^,)]\|\_s\)\+,\?/ contained nextgroup=goParamName skipwhite skipnl
368                          \ contains=goVarArgs,goType,goSignedInts,goUnsignedInts,goFloats,goComplexes,goDeclType,goBlock
369    hi def link   goReceiverVar    goParamName
370    hi def link   goParamName      Identifier
371  endif
372  syn match goReceiver          /(\s*\w\+\%(\s\+\*\?\s*\w\+\)\?\s*)\ze\s*\w/ contained nextgroup=goFunction contains=goReceiverVar skipwhite skipnl
373else
374  syn keyword goDeclaration func
375endif
376hi def link     goFunction          Function
377
378" Function calls;
379if s:HighlightFunctionCalls()
380  syn match goFunctionCall      /\w\+\ze(/ contains=goBuiltins,goDeclaration
381endif
382hi def link     goFunctionCall      Type
383
384" Fields;
385if s:HighlightFields()
386  " 1. Match a sequence of word characters coming after a '.'
387  " 2. Require the following but dont match it: ( \@= see :h E59)
388  "    - The symbols: / - + * %   OR
389  "    - The symbols: [] {} <> )  OR
390  "    - The symbols: \n \r space OR
391  "    - The symbols: , : .
392  " 3. Have the start of highlight (hs) be the start of matched
393  "    pattern (s) offsetted one to the right (+1) (see :h E401)
394  syn match       goField   /\.\w\+\
395        \%(\%([\/\-\+*%]\)\|\
396        \%([\[\]{}<\>\)]\)\|\
397        \%([\!=\^|&]\)\|\
398        \%([\n\r\ ]\)\|\
399        \%([,\:.]\)\)\@=/hs=s+1
400endif
401hi def link    goField              Identifier
402
403" Structs & Interfaces;
404if s:HighlightTypes()
405  syn match goTypeConstructor      /\<\w\+{\@=/
406  syn match goTypeDecl             /\<type\>/ nextgroup=goTypeName skipwhite skipnl
407  syn match goTypeName             /\w\+/ contained nextgroup=goDeclType skipwhite skipnl
408  syn match goDeclType             /\<\%(interface\|struct\)\>/ skipwhite skipnl
409  hi def link     goReceiverType      Type
410else
411  syn keyword goDeclType           struct interface
412  syn keyword goDeclaration        type
413endif
414hi def link     goTypeConstructor   Type
415hi def link     goTypeName          Type
416hi def link     goTypeDecl          Keyword
417hi def link     goDeclType          Keyword
418
419" Variable Assignments
420if s:HighlightVariableAssignments()
421  syn match goVarAssign /\v[_.[:alnum:]]+(,\s*[_.[:alnum:]]+)*\ze(\s*([-^+|^\/%&]|\*|\<\<|\>\>|\&\^)?\=[^=])/
422  hi def link   goVarAssign         Special
423endif
424
425" Variable Declarations
426if s:HighlightVariableDeclarations()
427  syn match goVarDefs /\v\w+(,\s*\w+)*\ze(\s*:\=)/
428  hi def link   goVarDefs           Special
429endif
430
431" Build Constraints
432if s:HighlightBuildConstraints()
433  syn match   goBuildKeyword      display contained "+build"
434  " Highlight the known values of GOOS, GOARCH, and other +build options.
435  syn keyword goBuildDirectives   contained
436        \ android darwin dragonfly freebsd linux nacl netbsd openbsd plan9
437        \ solaris windows 386 amd64 amd64p32 arm armbe arm64 arm64be ppc64
438        \ ppc64le mips mipsle mips64 mips64le mips64p32 mips64p32le ppc
439        \ s390 s390x sparc sparc64 cgo ignore race
440
441  " Other words in the build directive are build tags not listed above, so
442  " avoid highlighting them as comments by using a matchgroup just for the
443  " start of the comment.
444  " The rs=s+2 option lets the \s*+build portion be part of the inner region
445  " instead of the matchgroup so it will be highlighted as a goBuildKeyword.
446  syn region  goBuildComment      matchgroup=goBuildCommentStart
447        \ start="//\s*+build\s"rs=s+2 end="$"
448        \ contains=goBuildKeyword,goBuildDirectives
449  hi def link goBuildCommentStart Comment
450  hi def link goBuildDirectives   Type
451  hi def link goBuildKeyword      PreProc
452endif
453
454if s:HighlightBuildConstraints() || s:FoldEnable('package_comment')
455  " One or more line comments that are followed immediately by a "package"
456  " declaration are treated like package documentation, so these must be
457  " matched as comments to avoid looking like working build constraints.
458  " The he, me, and re options let the "package" itself be highlighted by
459  " the usual rules.
460  exe 'syn region  goPackageComment    start=/\v(\/\/.*\n)+\s*package/'
461        \ . ' end=/\v\n\s*package/he=e-7,me=e-7,re=e-7'
462        \ . ' contains=@goCommentGroup,@Spell'
463        \ . (s:FoldEnable('package_comment') ? ' fold' : '')
464  exe 'syn region  goPackageComment    start=/\v^\s*\/\*.*\n(.*\n)*\s*\*\/\npackage/'
465        \ . ' end=/\v\*\/\n\s*package/he=e-7,me=e-7,re=e-7'
466        \ . ' contains=@goCommentGroup,@Spell'
467        \ . (s:FoldEnable('package_comment') ? ' fold' : '')
468  hi def link goPackageComment    Comment
469endif
470
471" :GoCoverage commands
472hi def link goCoverageNormalText Comment
473
474" Search backwards for a global declaration to start processing the syntax.
475"syn sync match goSync grouphere NONE /^\(const\|var\|type\|func\)\>/
476
477" There's a bug in the implementation of grouphere. For now, use the
478" following as a more expensive/less precise workaround.
479syn sync minlines=500
480
481let b:current_syntax = "go"
482
483let &cpo = s:keepcpo
484unlet s:keepcpo
485
486" vim: sw=2 sts=2 et
487