Test if active document in Rstudio is RMarkdown

35 views Asked by At

I want to add a small function to my RStudio AddIn which extracts all chunks from an Rmarkdown document, does some transformation and displays it as new editor window in RStudio. Basically, that will be a thin wrapper around knitr::purl. The function will eventually be called via the AddIns interface in RStudio and should consider the currently opened editor window as input.

What I was wondering though, is how to include a check whether the current editor window shows indeed an RMarkdown document.

I could use the file extension like this:

if (grepl("\\.Rmd$", rstudioapi::getSourceEditorContext()$path)) {
   ## Rmarkdown -> do knitr::purl
} else {
   ## No Rmarkdown -> give a warning
}

But this feels hackish and a new Rmarkdown document, which is not saved yet (and opened via File -> New File -> RMarkdown...) will fail this check.

As RStudio itself does somehow recognize whether a file is meant to be an Rmarkdown document (creating a file as highlighted will add the Knit button for example, even if it not saved yet), I was wondering how I would ultimately find out the "file" type of an editor window?

I skimmed through the Admin Guide Appendix hoping to find a function like isRMarkdown to be called via rstudioApi::executeCommand but to no avail.

What would be a reliable way to check the file type associated to the current editor window in RStudio?

0

There are 0 answers