Code Folding and Sections in the RStudio IDE


Code Folding

The Source pane in the RStudio IDE supports both automatic and user-defined folding for regions of code. Code folding allows you to easily show and hide blocks of code to make it easier to navigate your source file and focus on the coding task at hand. For example, in the following source file the body of the plot.autoregressive.model has been folded:

You can expand the folded region by either clicking on the arrow in the gutter or on the icon that overlays the folded code.

Foldable Regions

The following types of code regions are automatically foldable within RStudio:

  • Braced regions (function definitions, conditional blocks, etc.)
  • Code chunks within R Sweave or R Markdown documents
  • Text sections between headers within R Markdown documents
  • Code sections (see below for details)

In the following example you can see that the top-level code section, function body, and conditional blocks are all foldable:

You can also fold an arbitrary selection of code by using Edit -> Folding -> Collapse (Alt-L).

Folded regions are preserved while editing a document; however all foldable regions are shown expanded by default when a file is closed and re-opened.

Code Sections

Code sections allow you to break a larger source file into a set of discrete regions for easy navigation between them. Code sections are automatically foldable—for example, the following source file has three sections (one expanded and the other two folded):

To insert a new code section you can use the Code -> Insert Section command. Alternatively, any comment line which includes at least four trailing dashes (-), equal signs (=), or pound signs (#) automatically creates a code section. For example, all of the following lines create code sections:

 # Section One ---------------------------------
 # Section Two =================================
 ### Section Three ############################# 

Note that as illustrated above the line can start with any number of pound signs (#) so long as it ends with four or more -, =, or # characters.

To navigate between code sections you can use the Jump To menu available at the bottom of the editor:

Menu Commands and Shortcuts

The following menu commands and shortcuts are available for working with folded regions and code sections:

  • Edit -> Folding:
    • Collapse — Alt+L
    • Expand — Shift+Alt+L
    • Collapse All — Alt+O
    • Expand All — Shift+Alt+O
  • Code:
    • Insert Section — Ctrl+Shift+R (Cmd+Shift+R on the Mac)
    • Jump To — Shift+Alt+J

Note that the Collapse All command collapses all of the outermost foldable regions (rather than all of the nested regions within the source file).

Related Topics