in src/org/jetbrains/r/rinterop/rstudioapi/DocumentUtils.kt [161:232]
suspend fun documentNew(rInterop: RInteropImpl, args: RObject): RObject {
val type = args.list.getRObjects(0).rString.getStrings(0)
val text = args.list.getRObjects(1).rString.getStrings(0)
val line = args.list.getRObjects(2).rInt.getInts(0).toInt()
val column = args.list.getRObjects(2).rInt.getInts(1).toInt()
val execute = args.list.getRObjects(3).rBoolean.getBooleans(0)
val filePath = withContext(Dispatchers.EDT) {
val fileChooser = rInterop.interpreter.createFileChooserForHost(rInterop.interpreter.basePath, false)
val panel = panel {
row { label(RBundle.message("rstudioapi.new.document.select.file.message")) }
row { cell(fileChooser).columns(40).focused() }
}
val dialog = dialog("", panel)
if (dialog.showAndGet()) {
fileChooser.text
}
else null
} ?: return rError("No file selected")
val path = if (PathUtilRt.getFileExtension(filePath) == null) {
filePath + when (type) {
"r" -> ".R"
"rmarkdown" -> ".rmd"
"sql" -> ".sql"
else -> ""
}
}
else {
filePath
}
val newFilePath = rInterop.interpreter.createFileOnHost(path, text.toByteArray(), "")
val file = rInterop.interpreter.findFileByPathAtHost(newFilePath) ?: return rError("Failed to create file")
withBackgroundProgress(rInterop.project, RBundle.message("rstudioapi.create.new.document")) {
withContext(Dispatchers.EDT) {
FileTypeChooser.getKnownFileTypeOrAssociate(newFilePath)
val editor = FileEditorManager.getInstance(rInterop.project)
.openTextEditor(OpenFileDescriptor(rInterop.project, file, line, column), true)
if (editor != null) {
val offset = editor.visualPositionToOffset(VisualPosition(line, column))
editor.selectionModel.setSelection(offset, offset)
}
if (!execute) return@withContext
when (type) {
"r" -> rInterop.replSourceFile(file)
"rmarkdown" -> {
if (editor == null) return@withContext
val psiFile = PsiManager.getInstance(rInterop.project).findFile(file) ?: return@withContext
val state = editor.chunkExecutionState
if (state == null) {
RunChunkHandler.getInstance(rInterop.project).runAllChunks(psiFile, editor)
}
else {
state.terminationRequired.set(true)
val element = state.currentPsiElement.get()
RunChunkHandler.getInstance(element.project).interruptChunkExecution()
}
}
else -> {}
}
}
}
return RObject.getDefaultInstance()
}