aboutsummaryrefslogtreecommitdiff
path: root/vim/plugin/detect_indent.vim
blob: f8dd8966f17145879cf18f5a45da9df3d1639f17 (plain) (blame)
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
function Count() abort

  let spaces = {
        \ 'hist': {},
        \ 'total': 0,
        \}
  let tabs = 0
  let total = line('$')

  for lnum in range(1, total)
    let line = getline(lnum)
    let tabs += matchstr(line, '^\t*') != ''
    let indent = strlen(matchstr(line, '^ *'))
    if indent == 0
      continue
    endif
    if !has_key(spaces['hist'], indent)
      let spaces['hist'][indent] = 0
    endif
    let spaces['hist'][indent] += 1
    let spaces['total'] += 1
  endfor

  if &expandtab && tabs > spaces['total'] * 5
    setlocal noexpandtab softtabstop=0
    let &l:shiftwidth = &tabstop
    setlocal expandtab?
  elseif !&expandtab && spaces['total'] > tabs * 5
    let shiftwidth = 0
    for shiftwidth in sort(keys(spaces['hist']))
      if spaces['hist'][shiftwidth] * 100 / spaces['total'] >= 5
        break
      endif
    endfor
    setlocal expandtab
    let &l:shiftwidth = shiftwidth
    let &l:softtabstop = shiftwidth
    setlocal expandtab? shiftwidth?
  endif

endfunction

autocmd FileType * call Count()