How to resize a window taking into account only logical lines?

I want to write a function that I can call from a map. The idea is to resize the window to fit the contents of the buffer. This is not too complicated:

fu! ResizeWindow(vert) "{{{
    if a:vert
        let longest = max(map(range(1, line('$')), "virtcol([v:val, '$'])"))
        exec "vertical resize " . (longest+4)
    else
        exec 'resize ' . line('$')
        1
    endif
endfu "}}}

However, I would like the function to take logical lines into account when calculating the height (I'm not too worried about the width).

For example, a line that is wrapped (due to :set wrap) will be considered two or more lines. A block of 37 lines that add up will be considered only one.

- " ", ? , - , , ?

+5
1

, , . , . ; , . .

fu! Sum(vals) "{{{
    let acc = 0
    for val in a:vals
        let acc += val
    endfor
    return acc
endfu "}}}
fu! LogicalLineCounts() "{{{
    if &wrap
        let width = winwidth(0)
        let line_counts = map(range(1, line('$')), "foldclosed(v:val)==v:val?1:(virtcol([v:val, '$'])/width)+1")
    else
        let line_counts = [line('$')]
    endif
    return line_counts
endfu "}}}
fu! LinesHiddenByFoldsCount() "{{{
    let lines = range(1, line('$'))
    call filter(lines, "foldclosed(v:val) > 0 && foldclosed(v:val) != v:val")
    return len(lines)
endfu "}}}
fu! AutoResizeWindow(vert) "{{{
    if a:vert
        let longest = max(map(range(1, line('$')), "virtcol([v:val, '$'])"))
        exec "vertical resize " . (longest+4)
    else
        let line_counts  = LogicalLineCounts()
        let folded_lines = LinesHiddenByFoldsCount()
        let lines        = Sum(line_counts) - folded_lines
        exec 'resize ' . lines
        1
    endif
endfu "}}}
+2

All Articles