Code Sections
Code sections provide structure for both navigation and folding of long functions or other code control flow.
Code folding
The Source pane in RStudio supports both automatic and user-defined folding for regions of code. Code folding provides the ability to easily show and hide blocks of code to make it easier to navigate source files and focus on the coding task at hand. For example, in the following source file the body of the rescale01
has been folded, indicated by the gutter arrow pointing to the right, instead of the down or up:
To expand the folded region:
- Click on the arrow in the gutter or
- Click the icon that overlays the folded code or
- Use the keyboard shortcut Ctrl+Alt+Shift+L
Foldable regions
The following types of code regions are automatically foldable within RStudio:
Braced regions (function definitions, conditional blocks, etc.)
Code chunks within Quarto or R Markdown documents
Text sections between headers within Quarto or R Markdown documents
Code sections (see below for details)
The following screenshot displays the arrow indicators for all the foldable regions in scripts:
- Top-level code section
- Function body
- Conditional blocks
Arbitrary selections of code can be folded by using Edit > Folding > Collapse, or the keyboard shortcut: Alt+L (Cmd+Option+L on Mac).
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.
Computational documents
In Quarto and R Markdown documents, the following sections can also be collapsed separately:
- YAML metadata
- Headings and subheadings
- Code chunks
Code sections
Code sections allow breaking 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 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 valid code sections:
# Section One ---------------------------------
# Section One ----
# Section Two =================================
# Section Two ====
### Section Three #############################
### Section Three ####
Code section levels
As illustrated above, the line can start with any number of pound signs (#) so long as it ends with a space followed by four or more -
, =
, or #
characters.
To navigate between code sections, use the Jump To menu available at the bottom of the editor:
Code sections can also be navigated with the Document Outline on the Source Pane menu bar.
Computational documents
In Quarto and R Markdown documents, headings/subheadings and labeled code chunks are automatically added to the document Outline and Jump To menus: