Code folding in LaTeX

Thanks to Paulo, I have a solution for this particular problem. In Texmaker, the following will fold:

%\begin{}
\usepackage{foo}
%\end{}

This also works in:

  • Visual Studio Code (with the james-yu.latex-workshop extension)

The reason for this is the way environments in LaTeX work.

A \begin{...} command starts a group, stores the environment name and then executes the environment start command. A \end{...} command checks that you are closing the right environment, executes the environment end command and closes a group.

A group has quite some effects, one of them being that non-global assignments to variables (and similar stuff like command definitions) inside it are revoked when the group is closed. Because of this, you usually don't want to load packages inside a group. (It might be that \usepackage actually checks this.)

If you don't really want a group but just folding, I propose you have a look at your editor's configuration to see if you can use some comment structure which doesn't influence the actual code which LaTeX sees.

Otherwise, you might be able to do something similar like the document environment does - in its start command, it starts with closing the group started by \begin again, so there is no superfluous group. But then you might need to manage the current environment variable yourself so \end{folding} doesn't give you an error. Have a look at source2e to see how the kernel does it.