Question

I know you can use

set foldcolumn=1

to enable fold column

but is there a way to automatic turn it on only when there are folds exist in the file?

Was it helpful?

Solution

Most probably you can create a function to check if the file has any folds, like:

function HasFoldedLine() 
    let lnum=1 
    while lnum <= line("$") 
        if (foldclosed(lnum) > -1) 
            return 1 
        endif 
        let lnum+=1 
    endwhile 
    return 0 
 endfu 

Now you can use it with some autocommand, e.g.:

au CursorHold * if HasFoldedLine() == 1 | set fdc=1 | else |set fdc=0 | endif 

HTH

OTHER TIPS

My method is faster than @Zsolt Botykai's when files get large enough. For small files I'd imagine the time difference is insignificant. Instead of checking every line for a fold, the function simply tries to move between folds. If the cursor never moves, there are no folds.

function HasFolds()
    "Attempt to move between folds, checking line numbers to see if it worked.
    "If it did, there are folds.

    function! HasFoldsInner()
        let origline=line('.')  
        :norm zk
        if origline==line('.')
            :norm zj
            if origline==line('.')
                return 0
            else
                return 1
            endif
        else
            return 1
        endif
        return 0
    endfunction

    let l:winview=winsaveview() "save window and cursor position
    let foldsexist=HasFoldsInner()
    if foldsexist
        set foldcolumn=1
    else
        "Move to the end of the current fold and check again in case the
        "cursor was on the sole fold in the file when we checked
        if line('.')!=1
            :norm [z
            :norm k
        else
            :norm ]z
            :norm j
        endif
        let foldsexist=HasFoldsInner()
        if foldsexist
            set foldcolumn=1
        else
            set foldcolumn=0
        endif
    end
    call winrestview(l:winview) "restore window/cursor position
endfunction

au CursorHold,BufWinEnter ?* call HasFolds()

(Shameless self plugin)

I created a plugin to do this called Auto Origami, modeled on @SnoringFrog's answer.

Drop the following example into your vimrc after installing it to see the magic happen (and read :help auto-origami to find out how to fine-tune it):

augroup autofoldcolumn
  au!

  " Or whatever autocmd-events you want
  au CursorHold,BufWinEnter * AutoOrigamiFoldColumn
augroup END
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top