What is code folding in the MPLAB® X IDE?

Last modified by Microchip on 2024/06/24 06:31

Code folding is a feature of the MPLAB® X editor that makes it possible to collapse (hide) and expand parts of a file, making it easier to focus just on the parts of interest. In general, any code block surrounded by braces '{' and '}' will be collapsible. This includes function bodies, compound statements, and also groups of compiler directives. Code folds may be nested, providing a high degree of control over which parts of a file are visible at any one time. Code folding is configurable to include or exclude numerous code structures and also provides a means of creating custom code folds to hide and reveal any part of a file you desire.

How to Use Code Folding

On the far left of the editor window, immediately to the right of the glyph margin, you will see some small boxes with either a '+' or a '-' inside them. When a block is expanded, you will see a '-' that may be clicked to collapse the code. Likewise, when the code is collapsed, clicking on the '+' will expand it.

Function Unfolded:

Example of unfolded function

Function Folded:

Example of a folded function

How to Configure Code Folding Options

General code folding is enabled by default, but many of its features are not. To change code folding options (or disable them altogether if you are so inclined) do the following:

Go to the menu Tools > Options

In the window that opens, select the Editor icon Editor icon from the top.

Select the General tab.

Check or uncheck each item under the Code Folding section as desired.

Code folding options window

How to Create Custom Code Folds in C

Sometimes, you may want to collapse sections of code that are not automatically detected as are function bodies and other blocks within braces. To do this, there are special comments that may be used to force the editor to create a collapsible block, set its default state and even provide a label to be displayed when it is collapsed.
To create a custom code fold, use the following comment tags around your code like this:

// <editor-fold defaultstate="collapsed" desc="user-description">
Code to collapse here...
// </editor-fold>

(Note the '/' inside the ending </editor-fold> tag.)

Instead of typing in the tags shown above, you can take advantage of code templates and simply type in "fcom" followed by the TAB key, and both the <editor-fold…> and the </editor-fold> tags will automatically appear.

Code Expanded:

Code expanded

Code Collapsed:

Code folded

The above example is simplistic so that it can easily be seen on one screen. You can have as much code or other text between the two comment tags as you like.