Using snippets
A code snippet is a text shortcut that is used to insert a predefined chunk of code. It’s like super-completion. The RStudio IDE contains a lot of predefined code snippets. For instance:
src
can be used to insertsource("file.R")
lib
can be used to insertlibrary(package)
tapply
can be used to inserttapply(vector, index, function)
To use a snippet, enter the shortcut of the snippet (for example src
) and press SHIFT
+
TAB
to insert the corresponding chunk of code (for example source("file.R")
).
Code snippets are language-specific meaning that they will work only with the appropriate language. For instance, in Markdown documents (.md
, .Rmd
and .qmd
files), by using the snippet ![
(and SHIFT
+
TAB
) you will write the markdown syntax to insert an image: ![label](location)
. This snippet won’t work inside .R
files.
Use the key TAB
to navigate inside the code snippet. In the snippet ![label](location)
, label
and location
are two variables. Once the snippet is created the cursor is in label
. Use TAB
to go to location
.
You will find a list of predefined snippets in Tools > Edit Code Snippets...
Customizing snippets
You can easily add your own code snippets by editing the code snippets editor in Tools > Edit Code Snippets...
Let’s add a snippet that will create a new code section for us:
This snippet has two variables: ${1:Title}
and ${0}
.
When we write sec
and press SHIFT
+
TAB
a new section will be created. The cursor will be on Title
and after pressing TAB
we go to the next line.
When creating a new snippet, make sure to select the appropriate language (Figure 2).
For further information visit this article.