Weird behavior when trying to comment a selected line in a R Markdown doc

I noticed the following behavior in RStudio. Consider this small piece of an R Markdown document:

## My doc
Doc with a chunk
```{r chunk}
print("foo")
getwd()
```

Suppose I want to comment the last line before the closing triple backticks, i.e., getwd() in my example. If I just position the cursor anywhere on that line, then the comment shortcut Ctrl+Shift+C, or the Comment/Uncomment lines item of the Code menu work perfectly, and I comment my code. If however I selected the whole line before, using Ctrl+DownArrow, this doesn't work. It works, however, if there is an empty line between getwd() and the closing triple backticks, i.e.,

## My doc
Doc with a chunk
```{r chunk}
print("foo")
getwd()

```

Of course it's not like I have to select the line with Ctrl+DownArrow to comment it: it's just an habit I got from using other Windows editors. However, I was wondering why it works this way.

> library(rstudioapi)
> versionInfo()
$citation

To cite RStudio in publications use:

  RStudio Team (2016). RStudio: Integrated Development for R. RStudio, Inc., Boston, MA URL
  http://www.rstudio.com/.

A BibTeX entry for LaTeX users is

  @Manual{,
    title = {RStudio: Integrated Development Environment for R},
    author = {{RStudio Team}},
    organization = {RStudio, Inc.},
    address = {Boston, MA},
    year = {2016},
    url = {http://www.rstudio.com/},
  }


$mode
[1] "desktop"

$version
[1] ‘1.1.383’

This seems like a buglet: when invoking the 'Comment Selection' command, RStudio tries to figure out whether the current selection crosses multiple language modes (e.g. imagine you had a highlight region from the middle of a chunk, exiting out to the 'Markdown' part of a chunk). When the selection does cross multiple language modes, we err on the side of not commenting at all.

In this particular case, RStudio seems to believe you're highlighting across language modes, and so fails to comment the selection. In theory, the ``` bit is part of the Markdown mode of the document, and since the end of the selection lies on that line RStudio falls into that state.

Would you mind filing a bug report at https://github.com/rstudio/rstudio/issues?

1 Like

Sure! I had a look at the bug issues and it looks like it hasn't been reported until now, so I will file a report later today. Thanks for the answer!

@kevinushey bug report filed!

1 Like