Search code examples
rrstudiocode-snippets

Dynamic Rstudio Code Snippet


I tend to use a lot of line breaks in my code like the following:

# Data =========================================================================

Where the entire comment is always 80 characters long (including the hashtag). What I would like to do is write a code snippet for Rstudio that will insert the hashtag, then a space, then allow the user to type out a series of words, then insert another space, and finally fill in a bunch of "=" until the 80 character limit is reached.

I'm not familiar with how snippets work at all so I'm not sure how difficult this is.

I have this much:

snippet lb
  # ${1:name}

but I have no idea how to add a dynamic number of "=" signs. Also, lb = linebreak.


Solution

  • You can't do this with snippets, unfortunately; a snippet is a text template that contains fixed text with slots for user-inserted text.

    There is a command built into RStudio to do something very similar, however; from the Code menu, choose Insert Section (or Ctrl+Shift+R). This will do exactly what you're describing, with two small differences:

    1. The line will extend to 5 characters before the print margin (you can adjust the print margin in Tools -> Global Options -> Code.

    2. The line is composed of - rather than = characters.

    One advantage to sections marked in this way is that you can use them to fold and navigate inside the file (look at the editor status bar after adding one).