go.vim 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. " Copyright 2011 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. " indent/go.vim: Vim indent file for Go.
  6. "
  7. " TODO:
  8. " - function invocations split across lines
  9. " - general line splits (line ends in an operator)
  10. if exists("b:did_indent")
  11. finish
  12. endif
  13. let b:did_indent = 1
  14. " C indentation is too far off useful, mainly due to Go's := operator.
  15. " Let's just define our own.
  16. setlocal nolisp
  17. setlocal autoindent
  18. setlocal indentexpr=GoIndent(v:lnum)
  19. setlocal indentkeys+=<:>,0=},0=)
  20. if exists("*GoIndent")
  21. finish
  22. endif
  23. " use shiftwidth function only if it's available
  24. if exists('*shiftwidth')
  25. func s:sw()
  26. return shiftwidth()
  27. endfunc
  28. else
  29. func s:sw()
  30. return &sw
  31. endfunc
  32. endif
  33. function! GoIndent(lnum)
  34. let prevlnum = prevnonblank(a:lnum-1)
  35. if prevlnum == 0
  36. " top of file
  37. return 0
  38. endif
  39. " grab the previous and current line, stripping comments.
  40. let prevl = substitute(getline(prevlnum), '//.*$', '', '')
  41. let thisl = substitute(getline(a:lnum), '//.*$', '', '')
  42. let previ = indent(prevlnum)
  43. let ind = previ
  44. if prevl =~ '[({]\s*$'
  45. " previous line opened a block
  46. let ind += s:sw()
  47. endif
  48. if prevl =~# '^\s*\(case .*\|default\):$'
  49. " previous line is part of a switch statement
  50. let ind += s:sw()
  51. endif
  52. " TODO: handle if the previous line is a label.
  53. if thisl =~ '^\s*[)}]'
  54. " this line closed a block
  55. let ind -= s:sw()
  56. endif
  57. " Colons are tricky.
  58. " We want to outdent if it's part of a switch ("case foo:" or "default:").
  59. " We ignore trying to deal with jump labels because (a) they're rare, and
  60. " (b) they're hard to disambiguate from a composite literal key.
  61. if thisl =~# '^\s*\(case .*\|default\):$'
  62. let ind -= s:sw()
  63. endif
  64. return ind
  65. endfunction
  66. " vim: sw=2 ts=2 et