aboutsummaryrefslogtreecommitdiff
path: root/autoload/squeeze_repeat_blanks.vim
blob: 97766435a6be4dd0b231d4cab47264e86198164b (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
" Reduce all groups of blank lines within range to the last line in that
" group, deleting the others.
function! squeeze_repeat_blanks#Squeeze(start, end) abort

  " Save cursor position
  let pos = getpos('.')

  " List of line numbers to delete
  let deletions = []

  " Flag for whether we've encountered a blank line group
  let group = 0

  " Pattern for what constitutes a 'blank'; configurable per-buffer
  let pattern = get(b:, 'squeeze_repeat_blanks_blank', '^$')

  " Iterate through the lines, collecting numbers to delete
  for num in range(a:start, a:end)

    " End a blank group if the current line doesn't match the pattern
    if getline(num) !~# pattern
      let group = 0

    " If we've found a repeated blank line, flag the one before it for
    " deletion; this way we end up with the last line of the group
    elseif group
      let deletions += [num - 1]

    " If this is the first blank line, start a group
    else
      let group = 1
    endif

  endfor

  " Delete each flagged line, in reverse order so that renumbering doesn't
  " bite us
  for num in reverse(deletions)
    silent execute num . 'delete'
  endfor

  " Restore cursor position
  call setpos('.', pos)

  " Report how many lines were deleted
  echomsg len(deletions) . ' deleted'

endfunction