Question

When I am viewing long code files with verbose comments in Vim, I would like to be able to load the files with comments folded but everything else unfolded. The current folding configuration I have in my .vimrc is:

set foldmethod=syntax
set nofoldenable

That way, when I want to start doing folds, I can just start executing z commands. But is there a way to only fold the (block) comments?

Was it helpful?

Solution

You could execute a global command to close all the block comment folds:

:g/^\/\*/foldc

This will execute :help foldclose on any line that starts with /* (a common block comment indicator). Notice the / and * need to be escaped in this instance. You don't need to escape the / if you use a different delimiter (e.g. :g#^/\*#foldc). If you want this to happen automatically you could add it in an autocommand. For example:

set fdm=syntax fen
augroup closeCommentFolds
   au!
   au FileType javascript %foldo | g/^\/\*/foldc
   au FileType ruby %foldo | g/^=begin/foldc
augroup end

Note that in these examples the ^ character in regex specifies that the /* and =begin matches are at the beginning of the line. If you want to match if there's whitespace between the beginning of the line and the match then use ^\s* instead of ^. The %foldo will open all folds so that foldenable is set, but it won't fold everything (just comments in this case).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top