Code Monkey home page Code Monkey logo

vim-anyfold's Introduction

vim-anyfold

Generic folding mechanism and motion based on indentation. Fold anything that is structured into indented blocks. Quickly navigate between blocks.

Short Instructions

Using this plugin is easy: Activate vim-anyfold by the command :AnyFoldActivate and deal with folds using Vim's built-in fold commands. Use key combinations [[ and ]] to navigate to the beginning and end of the current open fold. Use ]k and [j to navigate to the end of the previous block and to the beginning of the next block. For more detailed documentation, read the included vim doc :h anyfold or continue reading.

Introduction

This Vim plugin comes with the following features:

  • Folding mechanism based on indented blocks that has a very intuitive and predictable behaviour (see examples below).
  • Results comparable to syntax aware folding methods but fast and generic algorithm that does not rely on language specific rules.
  • Works out of the box for any filetypes, optimal results for all indented languages (including properly indented curly brace languages).
  • Shortcuts to navigate to beginning / end of a block and to previous / next indented block.
  • Can handle corner cases with ease (comments, varying indentation widths, line breaks).
  • Fast update mechanism that keeps folds in sync with buffer.

It has the following shortcomings:

  • Can not correctly fold mismatched indentation and thus should only be used together with disciplined programming style (or in combination with Vim's equalprg autoindent feature).

Advantages over foldmethod=indent

  • foldmethod=indent only works for indents that are a multiple of shiftwidth and thus fails for aligned code lines and inconsistent indentation. Vim-anyfold correctly defines folds for arbitrary indents.
  • vim-anyfold recognizes braces as part of indented blocks and correctly folds them. Vim-anyfold thus produces good folds not only for indented languages but also for e.g. C++ or Java.
  • vim-anyfold optionally folds multiline comments.

Be aware that vim-anyfold is much slower than foldmethod=indent and can reduce Vim's responsiveness. This is noticeable only when editing large files.

Examples

Python

python

Fortran

fortran

C++

cpp

Java

Note: this example is outdated since better defaults have been implemented for curly braces. java

Examples were recorded using

autocmd Filetype * AnyFoldActivate
let g:anyfold_fold_comments=1
set foldlevel=0
colorscheme solarized
hi Folded term=NONE cterm=NONE

Setup and usage

  1. Install this plugin with a vim plugin manager.

  2. Add the following lines to your vimrc (if not already present).

    filetype plugin indent on " required
    syntax on                 " required
    
    autocmd Filetype * AnyFoldActivate               " activate for all filetypes
    " or
    autocmd Filetype <your-filetype> AnyFoldActivate " activate for a specific filetype
    
    set foldlevel=0  " close all folds
    " or
    set foldlevel=99 " Open all folds

If you prefer to not activate vim-anyfold automatically, you can always invoke this plugin manually inside vim by typing :AnyFoldActivate.

  1. Use Vim's fold commands zo, zO, zc, za, ... to fold / unfold folds (read :h fold-commands for more information). Use key combinations [[ and ]] to navigate to the beginning and end of the current open fold. Use ]k and [j to navigate to the end of the previous block and to the beginning of the next block.

Additional remarks

  1. Supported folding commands: anyfold uses foldmethod=expr to define folds. Thus all commands that work with expression folding are supported.

  2. Fold display: anyfold's minimalistic display of closed fold assumes that folds are highlighted by your color scheme. If that is not the case, consider installing a suitable color scheme or highlight folds yourself by a command similar to

    hi Folded term=underline
  3. Lines to ignore: By default, anyfold uses the foldignore option to identify lines to ignore (such as comment lines and preprocessor statements). Vim's default is foldignore = #. Lines starting with characters in foldignore will get their fold level from surrounding lines. If anyfold_fold_comments = 1 these lines get their own folds. For instance, in order to ignore C++ style comments starting with // and preprocessor statements starting with #, set

    autocmd Filetype cpp set foldignore=#/

    This approach is fast but does not work for e.g. C style multiline comments and Python doc strings. If you'd like anyfold to correctly ignore these lines, add

    let g:anyfold_identify_comments=2

    to your vimrc. Please note that this may considerably slow down your Vim performance (mostly when opening large files).

  4. Large Files: anyfold causes long load times on large files, significantly longer than plain indent folding. By adding the following to your vimrc (and replacing <filetype>), anyfold is not initialized for large files:

    " activate anyfold by default
    augroup anyfold
        autocmd!
        autocmd Filetype <filetype> AnyFoldActivate
    augroup END
    
    " disable anyfold for large files
    let g:LargeFile = 1000000 " file is large if size greater than 1MB
    autocmd BufReadPre,BufRead * let f=getfsize(expand("<afile>")) | if f > g:LargeFile || f == -2 | call LargeFile() | endif
    function LargeFile()
        augroup anyfold
            autocmd! " remove AnyFoldActivate
            autocmd Filetype <filetype> setlocal foldmethod=indent " fall back to indent folding
        augroup END
    endfunction
    
  5. Customization: For expert configuration, anyfold triggers an event anyfoldLoaded after initialisation. This enables user-defined startup steps such as

    autocmd User anyfoldLoaded normal zv

    which unfolds the line in which the cursor is located when opening a file.

  6. Documentation: For more detailed instructions and information, read the included vim doc :h anyfold.

Options

All options can be either set globally

let g:<option>=<value>

or filetype specific

autocmd Filetype <filetype> let g:<option>=<value>
Option Values Default value Description
anyfold_fold_display 0, 1 1 Minimalistic display of closed folds
anyfold_motion 0, 1 1 Map motion commands to [[, ]], [j, ]k
anyfold_identify_comments 0, 1, 2 1 Identify lines to ignore for better fold behavior. 1: use foldignore, 2: use foldignore and syntax (slow)
anyfold_fold_comments 0, 1 0 Fold multiline comments
anyfold_comments list of strings ['comment', 'string'] Names of syntax items that should be ignored. Only used if anyfold_identify_comments = 2.
anyfold_fold_toplevel 0, 1 0 Fold subsequent unindented lines
anyfold_fold_size_str string '%s lines' Format of fold size string in minimalistic display
anyfold_fold_level_str string ' + ' Format of fold level string in minimalistic display

Complementary plugins

Here is a small list of plugins that I find very useful in combination with vim-anyfold:

  • Cycle folds with one key, much more efficient than Vim's built-in folding commands: vim-fold-cycle
  • Indent based text objects are not (yet) implemented in vim-anyfold, but this plugin works fine (even though blocks are defined in a slightly different way): vim-indent-object

Acknowledgements

I thank the following people for their contribution

  • Greg Sexton for allowing me to use his function for improved fold display.

vim-anyfold's People

Contributors

erebuxy avatar moon-musick avatar pseewald avatar roryokane avatar yhuangatimvucom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

vim-anyfold's Issues

Question re: brace terminators (C/C++)

Is it possible to configure it so that the line with the terminating brace } and/or blank lines gets included in the fold?

If I have:

void f() {
   std::puts("foo");
}

void g() {
   std::puts("bar");
}

struct baz {
  int x;
  int y;
};

I'd like it to fold into:

void f() { ---------------------------------- 4 lines
void g() { ---------------------------------- 4 lines
struct baz { -------------------------------- 5 lines

instead of:

void f() { ---------------------------------- 2 lines
}

void g() { ---------------------------------- 2 lines
}

struct baz { -------------------------------- 3 lines
};

EDIT 1:

It seems like putting the opening brace on its own line might accomplish what I want, I'll report back here after further testing.


EDIT 2:

Never mind that... same results regardless, but in some cases it seems to fold as I want, and in others it doesn't. Not quite sure yet what's causing the difference in behaviour for me.

But one issues seems to be when the brace ends with a semi-colon such as in the case of struct, class, union, enum, or brace initialization. But then again, in some cases it works... for example:

In one file I have these (white space annotated for clarity):

// ...
<blank line>
// using aliases:
<tab> using U8  = uint8_t;
<tab> using U16 = uint16_t;
<tab> using U32 = uint32_t;
<tab> using U64 = uint64_t;
<tab> using I8  = int8_t;
<tab> using I16 = int16_t;
<tab> using I32 = int32_t;
<tab> using I64 = int64_t;
<tab> using F32 = float;
<tab> using F64 = double;
<blank line>
struct FG { // foreground color
<tab> U8 code = 255;
};
<blank line>
[[nodiscard]] inline auto to_string( FG const fg ) -> std::string {
<tab> return std::string("38;5;") + std::to_string(fg.code);
}
<blank line>
struct BG { // background color
<tab> U8 code = 238;
};
<blank line>
// ...

and I can fold all the using aliases into the comment, the function and BG properly, but not FG.

If I do try to fold them all it becomes:

// ...
// using aliases:                                                      12 lines
struct FG { // foreground color                                         2 lines
};
<blank line>
[[nodiscard]] inline auto to_string( FG const fg ) -> std::string {     4 lines
struct BG { // background color                                         4 lines
// ...

So in the above case all but FG work as desired. Super weird.

[feature] add augroup

" deprecated initialization using anyfold_activate variable
" still works but echoes a warning
au BufNewFile,BufRead * call anyfold#init(0)

First, this autocmd don't be included in an augroup, which make user cannot use autocmd! augroup_name to disable it.

Second, this autocmd make vim call this function when read or create a buffer, which means vim will source autoload/anyfold.vim. If we change it to (just move some lines from autoload function to plugin/anyfold.vim)

au BufNewFile,BufRead * call s:init()
function! s:init() abort
    if exists("g:anyfold_activate")
        let b:anyfold_activate = g:anyfold_activate
    endif

    if !exists("b:anyfold_activate")
        return
    elseif !b:anyfold_activate
        return
    endif
    call anyfold#init(1)
endfunction

Now, if g: or b:anyfold_activate don't exist, the autoload function anyfold#init will not be called, so autoload/anyfold.vim will not be sourced, it can save time of sourcing a script.

I think it will be better.

Thanks!

[feature] allow user to customize hotkey

if g:anyfold_motion
    noremap <script> <buffer> <silent> ]]
                \ :<c-u>call <SID>JumpFoldEnd(0,v:count1)<cr>

    noremap <script> <buffer> <silent> [[
                \ :<c-u>call <SID>JumpFoldStart(0,v:count1)<cr>

    noremap <script> <buffer> <silent> ]k
                \ :<c-u>call <SID>JumpPrevFoldEnd(0,v:count1)<cr>

Why not use anyfold#jumpfoldend to replace <SID>? <SID> make it is impossible for user to customize their hotkeys in vimrc.

Folding Import/include statements

vim-anyfold doesn't fold import/include statements currently.

We should fold #import/#include statements for java, cpp, c, python etc.
Most major IDEs currently do this.

Errors in neovim when opening built-in terminal

Hi,

it seems running :vsplit term://top or even term://bash in neovim (v0.2.1-dev from official Ubuntu PPA, Ubuntu 16.04 amd64, ), actually an example taken directly from neovim documentation yields Error detected while processing function <SNR>195_ReloadFolds.

I suppose it is not really a good idea to fold terminal content - anyfold could most likely be safely disabled in some way for this type of buffer. I could do that in my vimrc, but I have no idea how to do that. Could you perhaps point me in the right direction?

[feature] add augroup

" deprecated initialization using anyfold_activate variable
" still works but echoes a warning
au BufNewFile,BufRead * call anyfold#init(0)

First, this autocmd don't be included in an augroup, which make user cannot use autocmd! augroup_name to disable it.

Second, this autocmd make vim call this function when read or create a buffer, which means vim will source autoload/anyfold.vim. If we change it to (just move some lines from autoload function to plugin/anyfold.vim)

au BufNewFile,BufRead * call s:init()
function! s:init() abort
    if exists("g:anyfold_activate")
        let b:anyfold_activate = g:anyfold_activate
    endif

    if !exists("b:anyfold_activate")
        return
    elseif !b:anyfold_activate
        return
    endif
    call anyfold#init(1)
endfunction

Now, if g: or b:anyfold_activate don't exist, the autoload function anyfold#init will not be called, so autoload/anyfold.vim will not be sourced, it can save time of sourcing a script.

I think it will be better.

Thanks!

Bad interaction with nerdtree and tagbar

Opening nerdtree or tagbar and pressing e.g. ? triggers:

Error detected while processing function <SNR>93_ReloadFolds..<SNR>93_NextNonBlankLine..<SNR>93_ConsiderLine..<SNR>93_IsComment:
line    3:
E684: list index out of range: 1

AnyFold incorrectly detects foldable block boundaries in C files

At least in Linux kernel's scripts/kconfig/menu.c file I observe how wrongly the plugin detects the foldable blocks.

  1. In expr_print() go to the closing curly brace of switch() and press spacebar. The text is folded up to the "default:" label above while it had to fold up to the beginning of switch()
  2. In expr_print_gstr_helper() go to the function's closing brace and press spacebar. The text is folded up to "if (sym && sym->type != S_UNKNOWN)" while it should be folded up the the start of function definition.

Besides that, it would be nice to not fold all foldable blocks automatically at file opening, but instead find and mark them as foldable so that the user could fold them when he wants by just pressing 'za' or whatever mapped key.

GitGutter Preview throws error in neovim when vim-anyfold is used

I am using vim-anyfold with GitGutter plugin. :GitGutterPreviewHunk opens a pop window to view changes. But when autocmd Filetype * AnyFoldActivate is present in my vimrc, it throws the following error:

Error detected while processing function gitgutter#hunk#preview[3]..<SNR>153_hunk_op[62]..<SNR>153_preview[6]..<SNR>153_populate_hunk_preview_window:
line   14:
E16: Invalid range:       call nvim_win_set_height(s:winid, height)
line   18:
E16: Invalid range:       call nvim_buf_set_lines(winbufnr(s:winid), 0, -1, v:false, [])
line   19:
E16: Invalid range:       call nvim_buf_set_lines(winbufnr(s:winid), 0, -1, v:false, a:body)
line   20:
E16: Invalid range:       call nvim_buf_set_option(winbufnr(s:winid), 'modified', v:false)
line   23:
E16: Invalid range:       call nvim_buf_clear_namespace(winbufnr(s:winid), ns_id, 0, -1)
Error detected while processing function gitgutter#hunk#preview[3]..<SNR>153_hunk_op[62]..<SNR>153_preview[6]..<SNR>153_populate_hunk_preview_window[24]..gitgutter#diff_highlight#process:
line   21:
E16: Invalid range:     call s:diff(rline, aline, i, i+removed, 0, 0, regions, 1)
Error detected while processing function gitgutter#hunk#preview[3]..<SNR>153_hunk_op[62]..<SNR>153_preview[6]..<SNR>153_populate_hunk_preview_window:
line   29:
E16: Invalid range:       call nvim_win_set_cursor(s:winid, [1,0])
Error detected while processing function gitgutter#hunk#preview[3]..<SNR>153_hunk_op[62]..<SNR>153_preview:
line    7:
E16: Invalid range:   call s:enable_staging_from_hunk_preview_window()

I understand that this is also related to GitGutter, but I just wanted to confirm if vim-anyfold does anything which might cause issue when opening pop-up windos in neovim v0.4.4

error after making modifications or otherwise leaving insert mode

When I run with autocmd FileType * AnyFoldActivate in my vimrc, I get the following error after modifying the buffer:

Error detected while processing InsertLeave Autocommands for "<buffer=1>"..function <SNR>103_ReloadFolds:
line   38:
E111: Missing ']'

This has started happening only recently. Strangely, you haven't modified vim-anyfold recently. I've tried removing each of my other plugins in turn, and the problem remains. Perhaps a newer version of vim is causing this?

What's the difference to foldmethod=indent

Hi,
To be honest, I haven't installed the plugin, but just from reading the README, I don't get what the benefit of this plugin is, in contrast to vim's foldmethod=indent.
Would be nice to have this information in the README. :-)
Greets
Jounathaen

error when reloading .git/index file

Hi,
When I reload a .git/index file in vim, I got following errors:

E121: Undefined variable: b:anyfold_ind_actual
Press ENTER or type command to continue
Error detected while processing function 112_ReloadFolds:
line 14:
E116: Invalid arguments for function len(b:anyfold_ind_actual)
Press ENTER or type command to continue
Error detected while processing function 112_ReloadFolds:
line 14:
E15: Invalid expression: line('$') - len(b:anyfold_ind_actual)
Press ENTER or type command to continue
Error detected while processing function 112_ReloadFolds:
line 14:
E121: Undefined variable: b:anyfold_ind_actual
Press ENTER or type command to continue
Error detected while processing function 112_ReloadFolds:
line 14:
E116: Invalid arguments for function len(b:anyfold_ind_actual)
Press ENTER or type command to continue
Error detected while processing function 112_ReloadFolds:
line 14:
E15: Invalid expression: line('$') - len(b:anyfold_ind_actual)
Press ENTER or type command to continue
Error detected while processing function 112_ReloadFolds:
line 14:
E121: Undefined variable: b:anyfold_ind_actual
Press ENTER or type command to continue
Error detected while processing function 112_ReloadFolds:
line 14:
E116: Invalid arguments for function len(b:anyfold_ind_actual)
Press ENTER or type command to continue
Error detected while processing function 112_ReloadFolds:
line 14:
E15: Invalid expression: line('$') - len(b:anyfold_ind_actual)
Press ENTER or type command to continue
Error detected while processing function 112_ReloadFolds:
line 14:
E121: Undefined variable: b:anyfold_ind_actual

vim-anyfold is adding jumps to jumplist

Opening a file with folds messes up the jump list.

Replication steps

  1. Open a file for the first time with folds and let vim-anyfold fold the file
  2. Press [ctrl - O] repetitively to traverse back the jump list
  3. Notice it traverses through all the folds one by one
  4. You can view the jump stack by calling :jump command.

Possible Solution

We can make use of :keepjumps command to keep the jumplist intact.
Please read :help :keepjumps

Cursor jumps to top of class after folding

So I have this issue where… when writing a Ruby class, the cursor jumps to the top of the class after I write a method in it. I originally thought this was some Ruby plugin enforcing best-practices, but that's not the case. Turns out vim-anyfold tries responds to TextChangedI and tries to recompute folds on the fly. The behaviour I see is that it tries to fold the class soon as the end keyword for the function is typed.

I tried this on a test PHP file, and anyfold only folds on InsertLeave

Any ideas?

Screen.Recording.2022-12-04.at.11.13.59.mov

Identification of comment lines is slow

The following comparison in function CommentLine is executed for each line and the bottleneck in the current implementation:
synIDattr(synID(a:lnum,indent(a:lnum)+1,1),"name") =~? 'Comment'
A faster alternative may be to parse the comments string (see h: comments).

Error detected while processing function <SNR>80_ReloadFolds:

Not easy to reproduce, I haven't found the 100% scenario to reproduce this issue. But I am sure it happened at my side 4-5 times daily.
I only saw this issue when open/close PROJECTROOT/.git/index repeatedly.
.git/index file is a special file under .git folder. Its content is dynamically changed in background.
Not sure whether it is related to neovim.
I am using neovim, vim is too too too slow for me. And transfer from vim to neovim is very very easy.

Bellowing are the neovim output:

Error detected while processing function 80_ReloadFolds:
line 14:
E121: Undefined variable: b:anyfold_ind_actual
Press ENTER or type command to continue
Error detected while processing function 80_ReloadFolds:
line 14:
E116: Invalid arguments for function len
Press ENTER or type command to continue
Error detected while processing function 80_ReloadFolds:
line 14:
E15: Invalid expression: line('$') - len(b:anyfold_ind_actual)
Press ENTER or type command to continue
Error detected while processing function 80_ReloadFolds:
line 14:
E121: Undefined variable: b:anyfold_ind_actual
Press ENTER or type command to continue
Error detected while processing function 80_ReloadFolds:
line 14:
E116: Invalid arguments for function len
Press ENTER or type command to continue
Error detected while processing function 80_ReloadFolds:
line 14:
E15: Invalid expression: line('$') - len(b:anyfold_ind_actual)

undo key triggers "E684: list index out of range: 5"

Error detected while processing function <SNR>335_ReloadFolds:                                                                 
line   10:                                                                                                                     
E684: list index out of range: 5                                                                                               
Press ENTER or type command to continue                                                                                        
Error detected while processing function <SNR>335_ReloadFolds:                                                                 
line   10:                                                                                                                     
E15: Invalid expression: s:LineIndent(curr_line) != b:anyfold_ind_actual[curr_line - 1]  

Does not seem to work with yaml

Thanks for this plugin.

This is how I have anyfold configured:

  " Minimalistic display of closed folds
  let g:anyfold_fold_display = 1

  " Fold multiline comments
  let g:anyfold_fold_comments = 1
  let g:anyfold_identify_comments = 2
  let g:anyfold_comments = []

I am trying to have folds in yaml files based on indent. The following file:

- dfdfdf: 223
  dfdf: 23423
  sdfsdf:
    sdfsdf: 1232
    sdfsdf: 1232
    sdfsdf: 1232
  sdfsdf:
    sdfsdf: 1232
    sdfsdf: 1232
    sdfsdf: 1232

however produces a single fold with anyfold that folds the whole file. I would expect it to produce two more folds on the inner indents. Am I doing sth wrong? Is this by design? Can I somehow enable the inner folds as well?

Fail when reload a changed php file.

For example, this php code block.
default: echo("ERROR: Invalid vm kind '$kind'\n"); usage(); die();
This is my dropbox link to the php file:
https://www.dropbox.com/s/lmquuigc5ysot0v/zend_vm_gen.php?dl=0
The first time, it could fold on "default:". While, if I check out to another git commit/branch from outside, and inside vim, therefore, I reload it, then it will say
E490: No fold found
I have tested the similar scenario for python file, it works.
I really love your plugin, I am trying to fix this issue, if you could help, greatly appreciate.

Conflict with gitgutter's preview command

If I set autocmd Filetype * AnyFoldActivate in my neovim's config, then if I use GitGutterPreviewhunk, errors occurred as below

Error detected while processing function gitgutter#hunk#preview[3]..<SNR>164_hunk_op[62]..<SNR>164_preview[6]..<SNR>164
_populate_hunk_preview_window:
line   14:
E16: Invalid range:       call nvim_win_set_height(s:winid, height)
line   18:
E16: Invalid range:       call nvim_buf_set_lines(winbufnr(s:winid), 0, -1, v:false, [])
line   19:
E16: Invalid range:       call nvim_buf_set_lines(winbufnr(s:winid), 0, -1, v:false, a:body)
line   20:
E16: Invalid range:       call nvim_buf_set_option(winbufnr(s:winid), 'modified', v:false)
line   23:
E16: Invalid range:       call nvim_buf_clear_namespace(winbufnr(s:winid), ns_id, 0, -1)
Error detected while processing function gitgutter#hunk#preview[3]..<SNR>164_hunk_op[62]..<SNR>164_preview[6]..<SNR>164
_populate_hunk_preview_window[24]..gitgutter#diff_highlight#process:
line   21:
E16: Invalid range:     call s:diff(rline, aline, i, i+removed, 0, 0, regions, 1)
Error detected while processing function gitgutter#hunk#preview[3]..<SNR>164_hunk_op[62]..<SNR>164_preview[6]..<SNR>164
_populate_hunk_preview_window:
line   29:
E16: Invalid range:       call nvim_win_set_cursor(s:winid, [1,0])
Error detected while processing function gitgutter#hunk#preview[3]..<SNR>164_hunk_op[62]..<SNR>164_preview:
line    7:
E16: Invalid range:   call s:enable_staging_from_hunk_preview_window()

If not set autocmd Filetype * AnyFoldActivate, gitgutter's preview works well.

Errors at the bottom of a file

Firstly, thanks for developing this. Folding can be kind of a pain in vim, and this makes it better!

I'm getting errors when editing the end of a file

E684: list index out of range: 2266
E15: Invalid expression: b:anyfold_ind_buffer[v:lnum-1]
Press ENTER or type command to continue
...

This error repeats a few times before completing my command and returning.

This happens, for example, when I try adding a line to the bottom of the file.

Version Info

$ vim --version
VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Jun 23 2016 20:22:47)
Compiled by [email protected]
Normal version without GUI.  Features included (+) or not (-):
-arabic +autocmd -balloon_eval -browse +builtin_terms +byte_offset +cindent
-clientserver -clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments
-conceal +cryptv +cscope +cursorbind +cursorshape +dialog_con +diff +digraphs
-dnd -ebcdic -emacs_tags +eval +ex_extra +extra_search -farsi +file_in_path
+find_in_path +float +folding -footer +fork() -gettext -hangul_input +iconv
+insert_expand +jumplist -keymap -langmap +libcall +linebreak +lispindent
+listcmds +localmap -lua +menu +mksession +modify_fname +mouse -mouseshape
-mouse_dec -mouse_gpm -mouse_jsbterm -mouse_netterm -mouse_sysmouse
+mouse_xterm +multi_byte +multi_lang -mzscheme +netbeans_intg -osfiletype
+path_extra -perl +persistent_undo +postscript +printer -profile +python/dyn
-python3 +quickfix +reltime -rightleft +ruby/dyn +scrollbind +signs
+smartindent -sniff +startuptime +statusline -sun_workshop +syntax +tag_binary
+tag_old_static -tag_any_white -tcl +terminfo +termresponse +textobjects +title
 -toolbar +user_commands +vertsplit +virtualedit +visual +visualextra +viminfo
+vreplace +wildignore +wildmenu +windows +writebackup -X11 -xfontset -xim -xsmp
 -xterm_clipboard -xterm_save
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
      user exrc file: "$HOME/.exrc"
  fall-back for $VIM: "/usr/share/vim"
Compilation: gcc -c -I. -D_FORTIFY_SOURCE=0 -Iproto -DHAVE_CONFIG_H -arch i386 -arch x86_64 -g -Os -pipe
Linking: gcc -arch i386 -arch x86_64 -o vim -lncurses

customization of folds

Hi,

I like this project. Just moved away from simpylfold.

BACKGROUND

I was wondering if something like customization was possible using vim-anyfold. Please have a look at the two pictures attached to this message. The first screenshot shows the editor without folds:

anyfold__customize_folds__01_current

You see four "blocks" of code all preceded with a characteristic form of comment (three hashes in a row and the comment text restricted to the 2nd row, at least for Python code). This specific format is intended to be different from the "normal" line comments, as they kind of are on a different level and relate rather to a block than to a line of code or the inner program structures (for, if,...). Now, I would like to always keep these "block comments" visible, regardless on which indentation level they are written. Folds of this type should start with one of these block comments and end just before the next block comment (or the end of the file / function / ... ). See the next picture for clarification of the outcome:

anyfold__customize_folds__02_goal

This modified screenshot shows the editor scope after applying the fold method on the specifically designed block comments. So, the developer can concentrate on the block comments alone and is free to step into deeper levels of the code as he wishes.

QUESTION

Is there something like a mechanism to specify a language-specific regular expression statement (e.g. ^[\s]*#[\s]*[\r\n]+[\s]*#[\s]*[a-zA-z0-9]+[\s]*[\r\n]+[\s]*#) matching the very specific form of a block comment? So that folds can be realized between these block comments?

HINTS

If there is nothing like this possible at the moment, I would be glad for any developer who could give me some hints where to start implementing this feature myself. I hope, this would be possible starting off with the current code base.

Any Ideas?

Thanks.
Nnako

Allow for Markdown-style (and/or other style) of Headers

Currently, when using anyfold to fold away lists in a plain text files, any section headings in the file get confused as part of the list.

For e.g., given

# Heading 1

## Heading 1.1

-   List level 1
    -   List level 2
        -   List level 3
        -   List level 3
    -   List level 2
        -   List level 3
        -   List level 3

## Heading 1.2

-   List level 1
    -   List level 2
        -   List level 3
        -   List level 3
    -   List level 2
        -   List level 3
        -   List level 3

## Heading 2

## Heading 2.2

-   List level 1
    -   List level 2
        -   List level 3
        -   List level 3
    -   List level 2
        -   List level 3
        -   List level 3

## Heading 2.2

-   List level 1
    -   List level 2
        -   List level 3
        -   List level 3
    -   List level 2
        -   List level 3
        -   List level 3

we see:

Screenshot from 2021-09-25 22-34-40

Would it be possible to have vim-anyfold optionally recognize these headings and not fold them, so it looks like this:

Screenshot from 2021-09-25 22-37-19

This can be a command, e.g., "AnyFoldIncludeTextHeaders on" (which will fold headers, as it does now, by default), "AnyFoldIncludeTextHeaders off" (which will result in the second case).

How to leave a space at the bottom of each fold

image
image

Compare the above images. The first is from vscode, the second from vim using anyfold. It's the same code, but there's one obvious difference: the folding. You see, the source code has at least one empty space after every class and function definition. Vscode's folding does the right thing - it leaves the space there. But anyfold gets rid of the space. If I add two empty lines, it gets rid of both of them. This makes my code feel very crowded when it's folded, and as someone who uses folding constantly, this is very annoying.

re-fold

The description on this site says zx can be used to re-fold everything. This command does nothing for me. However, zM does re-fold.

Avoid adding blank lines at end of fold

I am using anyfold to fold a markdown document, e.g.

First Heading
========

- note
    -   foldline1
    -   foldline2
    -   foldline 3


Second heading

The Plugin folds the indented "foldlines" and includes the two trailing empty
lines until the 2nd heading into the fold. This means that, when folded, the
fold is immediately followed by the heading without a separating blank line.
This makes navigation with { or } impossible.

Could this be fixed?

foldmethod=syntax by default

Any chance to configure foldmethod=syntax instead of foldmethod=expr by default?
Tried with vim's autocmd BufRead,BufNewFile * set foldmethod=syntax but it's working randomly for me πŸ˜•

Vim's built-in za shortcut makes anyfold_toggle_key redundant

Hello,

I find the mandatory mapping of anyfold_toggle_key to be unnecessary and imposing because Vim already has a za shortcut that essentially does the same thing: the only difference between them is that anyfold_toggle_key honors the g:anyfold_auto_reload setting whereas Vim's za does not. 😞

If you could expose the ReloadFolds() function as a <Plug>(AnyFold-Reload-Folds) shortcut, then we could do away with the πŸ™€ mandatory anyfold_toggle_key and instead allow the user to decide πŸ–οΈ if they really want to trigger ReloadFolds() through a mapping (which is also of their choice):

nmap za <Plug>(AnyFold-Reload-Folds):normal! za<CR>

Thanks for your consideration.

Unexpected folding and noticeable lag when paired with vim-multiple-cursors

Unintentional folding (without set foldlevel=99)

example

Noticeable lag (with set foldlevel=99)

example2

Cause

Seems to be caused by this line.

Minimal vim config to recreate this

set nocompatible              " be iMproved, required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

Plugin 'pseewald/vim-anyfold'
Plugin 'terryma/vim-multiple-cursors'

call vundle#end()            " required
filetype plugin indent on    " required

autocmd Filetype * AnyFoldActivate

let g:multi_cursor_start_word_key = '<C-s>'
let g:multi_cursor_next_key = '<C-s>'
let g:multi_cursor_quit_key = '<Esc>'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.