2

How can force close an open script file - or in general an open tab - in RStudio using code?

As pointed here I already know that file.edit('test.R') can open a given file.

This is how I usually end a given script file before moving to an other section.

What I'd like to do, is to start the new section (script file) from closing what was used before.

For example:
import_data.R has code that does all file reading / importing and when that's done, it opens data_wrangle.R by calling file.edit("data_wrangle.R") where all the transforming, mutating etc is done. Since I don't need the import code any more, I'd like to close previous script (import_data.R in this case) with a line of code.

I did some guesswork calling close("./script/test.R") or rm("./script/test.R") but they clearly don't serve this purpose.

Community
  • 1
  • 1
blazej
  • 1,678
  • 3
  • 19
  • 41
  • Are you just opening the file in order to execute the contents of the file? Then maybe you should just be using `source()` rather than `file.edit()`. – MrFlick Feb 16 '18 at 15:49
  • 1
    If it would be available from anywhere I'd think it would have to come from the [rstudioapi](https://github.com/rstudio/rstudioapi) but there doesn't appear to be functions for closing windows. – MrFlick Feb 16 '18 at 16:02
  • I know of `source()` but here i'm thinking of a interactive scenario where script files are not 100% ready – blazej Feb 16 '18 at 16:24

4 Answers4

3

You can have a look to the .rs.api.documentClose() function.

Regards

Vincent Guyader
  • 2,927
  • 1
  • 26
  • 43
1

The rstudioapi package doesn't have a function to close a file, but it does have one to navigate to it. So your script could end something like

rstudioapi::navigateTo("data_wrangle.R")
rstudioapi::navigateTo("import_data.R")

and then I think a Ctrl-W as suggested by @Joyvalley would do what you want.

user2554330
  • 37,248
  • 4
  • 43
  • 90
1

Here in 2023, 'executeCommand' is your friend:

rstudioapi::executeCommand('closeAllSourceDocs')

matto
  • 77
  • 7
0

Ctrl - w does the job

Its not exactly what you ask for, but does what you want.

https://support.rstudio.com/hc/en-us/articles/200711853-Keyboard-Shortcuts

Joyvalley
  • 154
  • 1
  • 7
  • Problem with `Ctrl+w` is, that `file.edit("...")` automatically moves me to the new file. To use `Ctrl+w` i'd have to point-click on the old window and then close it. Not really a shortcut :) – blazej Feb 16 '18 at 15:21
  • 1
    True, i guess i wouldnt use Rstudio at all to avoid the clicky-pointy thing :-) – Joyvalley Feb 16 '18 at 15:24