Folding repeated lines in vim

221 Views Asked by At

I have a file in which, below is the content.

A A A A A A A A A . . . A Piece of code... A A A . . A

I want something like this using folding in vim

  • A Piece of code
  • A

2 folds are created by folding repeated lines. This should happen automatically as I open the file. Is it possible by doing it in vimrc?

2

There are 2 best solutions below

0
On

It should be possible by using setlocal foldmethod=expr where you can write your own function:

setlocal foldmethod=expr
setlocal foldexpr=CustomFold(v:lnum)

function! CustomFold(lnum)
  if getline(a:lnum) == getline(a:lnum-1) || getline(a:lnum) == getline(a:lnum+1)
    return '1'
  endif

  return '0'
endfunction

However this is untested and you wouldn't want to do it for all files. But it should point you in the right direction. It also would not 100% match your criteria, but once you have a specific problem, you can always ask again

4
On

How about this :help fold-expr:

setlocal foldenable foldmethod=expr
let &l:foldtext = 'printf("+-%s %d times: %s", v:folddashes, (v:foldend - v:foldstart + 1), getline(v:foldstart))'
let &l:foldexpr = 'getline(v:lnum) ==# getline(v:lnum + 1) && v:lnum < line("$") ? 1 : (getline(v:lnum - 1) ==# getline(v:lnum) ? "<1" : 0)'