aboutsummaryrefslogtreecommitdiff
path: root/vim/plugin/detect_indent.vim
blob: cbd2cf91cf3c03b91d09172d961de984389f3b63 (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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 set = []
    for indent in keys(spaces['hist'])
      if spaces['hist'][indent] * 100 / spaces['total'] >= 5
        call add(set, indent)
      endif
    endfor
    let shiftwidth = 1
    let continue = 1
    for divisor in range(2, max(set))
      for indent in set
        if indent % divisor != 0
          let continue = 0
          break
        endif
      endfor
      if !continue
        break
      endif
      let gcd = div
    endfor
    setlocal expandtab
    let &l:shiftwidth = gcd
    let &l:softtabstop = gcd
    setlocal expandtab? shiftwidth?
  endif

endfunction

autocmd FileType * call Count()