Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 246
stat_student Avatar asked Feb 10 '23 00:02

stat_student


2 Answers

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).

like image 184
Jonathan Avatar answered Feb 11 '23 21:02

Jonathan


You can use the rstudioapi (which can return column position) inside the snippet to get something like what you want.

Below is a snippet I use called endhead. I use it by commenting my header title and then applying the snippet, eg:

# Section name endhead

which results in:

# Section name -----------------------------------------------------------------
snippet endhead
    `r paste0(rep.int("-", 88 - rstudioapi::primary_selection(rstudioapi::getActiveDocumentContext())$range$start[2]), collapse = "")`

like image 22
nwbort Avatar answered Feb 11 '23 20:02

nwbort