vim-polyglot/indent/go.vim

91 lines
2.2 KiB
VimL
Raw Normal View History

if exists('g:polyglot_disabled') && index(g:polyglot_disabled, 'go') != -1
finish
endif
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" indent/go.vim: Vim indent file for Go.
"
" TODO:
" - function invocations split across lines
" - general line splits (line ends in an operator)
if exists("b:did_indent")
2016-06-26 12:03:28 -04:00
finish
endif
let b:did_indent = 1
" C indentation is too far off useful, mainly due to Go's := operator.
" Let's just define our own.
setlocal nolisp
setlocal autoindent
setlocal indentexpr=GoIndent(v:lnum)
setlocal indentkeys+=<:>,0=},0=)
if exists("*GoIndent")
2016-06-26 12:03:28 -04:00
finish
2015-03-09 00:32:50 -04:00
endif
2018-12-26 04:41:57 -05:00
" don't spam the user when Vim is started in Vi compatibility mode
let s:cpo_save = &cpo
set cpo&vim
function! GoIndent(lnum) abort
2016-06-26 12:03:28 -04:00
let prevlnum = prevnonblank(a:lnum-1)
if prevlnum == 0
" top of file
return 0
endif
2016-06-26 12:03:28 -04:00
" grab the previous and current line, stripping comments.
let prevl = substitute(getline(prevlnum), '//.*$', '', '')
let thisl = substitute(getline(a:lnum), '//.*$', '', '')
let previ = indent(prevlnum)
2016-06-26 12:03:28 -04:00
let ind = previ
2018-12-26 04:41:57 -05:00
for synid in synstack(a:lnum, 1)
if synIDattr(synid, 'name') == 'goRawString'
if prevl =~ '\%(\%(:\?=\)\|(\|,\)\s*`[^`]*$'
" previous line started a multi-line raw string
return 0
endif
" return -1 to keep the current indent.
return -1
endif
endfor
2016-06-26 12:03:28 -04:00
if prevl =~ '[({]\s*$'
" previous line opened a block
2018-10-08 13:00:59 -04:00
let ind += shiftwidth()
2016-06-26 12:03:28 -04:00
endif
if prevl =~# '^\s*\(case .*\|default\):$'
" previous line is part of a switch statement
2018-10-08 13:00:59 -04:00
let ind += shiftwidth()
2016-06-26 12:03:28 -04:00
endif
" TODO: handle if the previous line is a label.
2016-06-26 12:03:28 -04:00
if thisl =~ '^\s*[)}]'
" this line closed a block
2018-10-08 13:00:59 -04:00
let ind -= shiftwidth()
2016-06-26 12:03:28 -04:00
endif
2016-06-26 12:03:28 -04:00
" Colons are tricky.
" We want to outdent if it's part of a switch ("case foo:" or "default:").
" We ignore trying to deal with jump labels because (a) they're rare, and
" (b) they're hard to disambiguate from a composite literal key.
if thisl =~# '^\s*\(case .*\|default\):$'
2018-10-08 13:00:59 -04:00
let ind -= shiftwidth()
2016-06-26 12:03:28 -04:00
endif
2016-06-26 12:03:28 -04:00
return ind
endfunction
2015-03-09 00:32:50 -04:00
2018-12-26 04:41:57 -05:00
" restore Vi compatibility settings
let &cpo = s:cpo_save
unlet s:cpo_save
2016-06-26 12:03:28 -04:00
" vim: sw=2 ts=2 et