当文件中有折叠时,gvim自动显示foldcolumn



我知道你可以使用

set foldcolumn=1

启用折叠柱

但是有没有一种方法可以只在文件中存在折叠时自动打开它?

当文件变得足够大时,我的方法比@Zsolt Botykai的方法更快。对于小文件,我认为时间差是微不足道的。该函数只是尝试在折叠之间移动,而不是检查每一行是否有折叠。如果光标从不移动,则没有折叠。

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()

很可能您可以创建一个函数来检查文件是否有折叠,例如:

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

现在您可以将它与一些autocommand一起使用,例如:

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

HTH

(无耻自我插件

我创建了一个名为Auto Origami的插件来实现这一点,它是以@SnoringFrog的答案为模型的。

安装后,将以下示例放入vimrc中,看看神奇的事情发生了(并阅读:help auto-origami了解如何对其进行微调):

augroup autofoldcolumn
  au!
  " Or whatever autocmd-events you want
  au CursorHold,BufWinEnter * AutoOrigamiFoldColumn
augroup END

最新更新