blob: a9b1d8d19b9d684d4178dd34f16ba921d4c021bf [file] [log] [blame]
Bram Moolenaarfb539272014-08-22 19:21:47 +02001" Vim indent file
2" Language: Go
3" Maintainer: David Barnett (https://github.com/google/vim-ft-go)
Bram Moolenaar3ec574f2017-06-13 18:12:01 +02004" Last Change: 2017 Jun 13
dkearns0382f052023-08-29 05:32:59 +10005" 2023 Aug 28 by Vim Project (undo_indent)
Bram Moolenaarfb539272014-08-22 19:21:47 +02006"
7" TODO:
8" - function invocations split across lines
9" - general line splits (line ends in an operator)
10
11if exists('b:did_indent')
12 finish
13endif
14let b:did_indent = 1
15
16" C indentation is too far off useful, mainly due to Go's := operator.
17" Let's just define our own.
18setlocal nolisp
19setlocal autoindent
20setlocal indentexpr=GoIndent(v:lnum)
21setlocal indentkeys+=<:>,0=},0=)
22
dkearns0382f052023-08-29 05:32:59 +100023let b:undo_indent = "setl ai< inde< indk< lisp<"
24
Bram Moolenaarfb539272014-08-22 19:21:47 +020025if exists('*GoIndent')
26 finish
27endif
28
Bram Moolenaarfb539272014-08-22 19:21:47 +020029function! GoIndent(lnum)
30 let l:prevlnum = prevnonblank(a:lnum-1)
31 if l:prevlnum == 0
32 " top of file
33 return 0
34 endif
35
36 " grab the previous and current line, stripping comments.
37 let l:prevl = substitute(getline(l:prevlnum), '//.*$', '', '')
38 let l:thisl = substitute(getline(a:lnum), '//.*$', '', '')
39 let l:previ = indent(l:prevlnum)
40
41 let l:ind = l:previ
42
43 if l:prevl =~ '[({]\s*$'
44 " previous line opened a block
Bram Moolenaar3ec574f2017-06-13 18:12:01 +020045 let l:ind += shiftwidth()
Bram Moolenaarfb539272014-08-22 19:21:47 +020046 endif
47 if l:prevl =~# '^\s*\(case .*\|default\):$'
48 " previous line is part of a switch statement
Bram Moolenaar3ec574f2017-06-13 18:12:01 +020049 let l:ind += shiftwidth()
Bram Moolenaarfb539272014-08-22 19:21:47 +020050 endif
51 " TODO: handle if the previous line is a label.
52
53 if l:thisl =~ '^\s*[)}]'
54 " this line closed a block
Bram Moolenaar3ec574f2017-06-13 18:12:01 +020055 let l:ind -= shiftwidth()
Bram Moolenaarfb539272014-08-22 19:21:47 +020056 endif
57
58 " Colons are tricky.
59 " We want to outdent if it's part of a switch ("case foo:" or "default:").
60 " We ignore trying to deal with jump labels because (a) they're rare, and
61 " (b) they're hard to disambiguate from a composite literal key.
62 if l:thisl =~# '^\s*\(case .*\|default\):$'
Bram Moolenaar3ec574f2017-06-13 18:12:01 +020063 let l:ind -= shiftwidth()
Bram Moolenaarfb539272014-08-22 19:21:47 +020064 endif
65
66 return l:ind
67endfunction
68
69" vim: sw=2 sts=2 et