vscode does not send multi-line commands to terminal with quarto - r

I recently switched to quarto for reporting with r. The only problem is that in vscode, I cannot send multiple lines of code to the terminal as I am used to.
In .Rmd and .R documents, I can use Cmd+Enter with the cursor on any line of a connected multi-line bit of code and it gets exectuted. I can also highlight a part and execute only that. Both behaviors do not work for .qmd documents.
In .qmd documents, the only way to execute these kinds of statements is to highlight the entire part, or have the cursor one line above the first code line. That I cannot send highlighted parts is also quite annoying.
# would only execute with the cursor one line above or all highlighted
diamonds %>%
arrange(carat)
# also does not work --> not only pipe commands
purrr::map(diamonds$carat,
exp)
My settings are as follows:
{
[...]
"r.bracketedPaste": true,
"r.rterm.mac": "/usr/local/bin/radian",
"r.lsp.debug": true,
"r.lsp.diagnostics": true,
"files.associations": {
"*.Rmd": "rmd"
},
"quarto.mathjax.theme": "dark",
"quarto.render.previewType": "external"
[...]
}
I have the same problem on a Mac and Ubuntu, so I suppose it's not system dependent.
Would be great if anybody could point me to a solution. Thanks!

You can the R extension's command in Quarto too by adding a keyboard shortcut as described here:
{
"key": "ctrl+enter",
"command": "r.runSelection",
"when": "editorTextFocus && editorLangId == quarto || editorLangId == r"
}

Related

Is there an Rstudio shortcut key for ``?

I use it a lot on Rmarkdow for referring to code, so I created an Addin, but wanted to know if there's a shortcut. If it isn't the case, how could I do to configure the addin so when calling it, the position of the caret or cursor stands between both symbols, exactly as it happens when using "" or () in RStudio.
insertInAddin <- function() { rstudioapi::insertText("``") } is the code I used for the Add-in
I'm looking help understanding how to setup
rstudioapi::setCursorPosition()
and document_position() inside the location argument of insertText.
You can use the shrtcts package for this task. It lets you assign Keyboard Shortcuts to arbitrary R Code.
Create a new R Markdown Snippet which can also be used on its own by typing e.g. in (for inline code font) and press Shift+Tab:
snippet in
`${1}`$0
Use the command shrtcts::edit_shortcuts() in the RStudio Console to open the file where you define your custom shortcuts.
Paste the following code inside that file (set your preferred keybinding in the #shortcut line). Note that the inserted text in the second line of the function must match the new Snippet from Step 1:
#' Code Font
#'
#' #description
#' If Editor has selection, transform current selection to code font.
#' If Editor has no selection, write between backticks.
#' #interactive
#' #shortcut Cmd+E
function() {
if (rstudioapi::selectionGet()$value == "") {
rstudioapi::insertText("in")
rstudioapi::executeCommand("insertSnippet") |>
capture.output() |>
invisible()
} else {
# Gets The Active Document
ctx <- rstudioapi::getActiveDocumentContext()
# Checks that a document is active
if (!is.null(ctx)) {
# Extracts selection as a string
selected_text <- ctx$selection[[1]]$text
# modify string
selected_text <- stringr::str_glue("`{selected_text}`")
# replaces selection with string
rstudioapi::modifyRange(ctx$selection[[1]]$range, selected_text)
}
}
}
This solution uses the native pipe |> and thus requires R 4.1.
You can of course just define separate variables in each line or use the magrittr pipe if you use earlier versions of R.
Further the stringr::str_glue() command can be easily replaced with a base R solution to avoid dependencies.
Use the command shrtcts::add_rstudio_shortcuts(set_keyboard_shortcuts = TRUE) in the RStudio Console to add the new shortcut with its assigned keybinding. Then restart RStudio.
Now you can use e.g. cmd+e without selection to place your cursor within backticks and press Tab to continue writing after the second backtick.
Or you can select text and then press cmd+e to surround the selected text by backticks.
The solution above can be easily generalized for bold and italic text in RMarkdown documents or to write within Dollar signs to add Inline Latex Math.
You can check RMarkdown Code Chunks and RStudio Shortcuts.
The shortcut you're looking for is: Ctrl+Alt+I.
Or you can create your own Code Snippet. To do this, follow the instructions on this page: Code Snippets in the RStudio IDE.

How to choose Jupyter syntax highlighting language

I regularly read and edit .cu files (cuda) in Jupyter. Is there a way to get Jupyter to use C++ syntax highlighting for .cu files? (They are basically C++ files)
You can create a JupyterLab extension (guide, tutorial), there are some examples out there like jupyterlab_robotmode (this and this part) and this comment. You will want to reuse CodeMirror's clike mode, probably incorporating these c++ bits. It would roughly look like this:
import { JupyterFrontEnd, JupyterFrontEndPlugin } from '#jupyterlab/application';
import { ICodeMirror } from '#jupyterlab/codemirror';
const extension: JupyterFrontEndPlugin<void> = {
id: 'jupyterlab-cuda-mode',
autoStart: true,
requires: [ICodeMirror],
activate: (app: JupyterFrontEnd, codeMirrorToken: ICodeMirror) => {
const cm = codeMirrorToken.CodeMirror as any;
cm.defineMIME(
"text/x-cuda",
{
name: "clike",
// add more configuration below
namespaceSeparator: "::",
modeProps: {fold: ["brace", "include"]}
}
);
// add more keywords
cm.registerHelper('hintWords', 'text/x-cuda', {'__global__': true});
cm.modeInfo.push({
ext: ["cu"],
mime: "text/x-cuda",
mode: "clike",
name: "cuda"
});
}
};
export default extension;
Now if you also want to have nice icon in the lanucher you would need to register it with the DocumentRegistry like the builtin file types are here
Of note, JupyterLab 4.0 and Jupyter Notebook 7.0 will use CodeMirror 6 which has a reworked parser. The old modes will still be supported via a legacy shim, but if you are thinking about developing a new mode, you might want to target lazer parser from CodeMirror 6.
An easy way without any extension can be using Markdown in Jupyter Notebook and Markdown Syntax Highlighting. You can use it for most of the languages but a drawback of this, you cannot see highlighting while you are editing code, just you can see after run. If your purpose is to see highlighted code between other blocks then it is useful. An example usage:
```c++
// your code goes here
```
Then, run markdown block.

How to correctly config a Google Functions Framework with Go inside a Firebase app

I'm writing an app in Flutter, and I want to be supported by Firebase and Google Cloud Functions: I can't use Firebase Functions since I'm planning to write Functions in Go.
At the moment my project's folder looks like this:
./lib/
./functions/
myFunc1/
myFunc2/
...
[other files and folders...]
Inside ./lib/ lies my Dart source codes.
Inside ./functions/, as you can see, I'm planning to create a folder for each go Function.
Inside a single './myFunc1/' folder, there's a .go file (my function), the go.mod file and the go.sum file.
Now, it looks like that the Go extension in VS code show me errors that don't make sense to me. Whenever I try to do a go mod tidy, I get the following error: "Error loading workspace: err: exit status 1: stderr: go: updates to go.sum needed, disabled by -mod=readonly : packages.Load error".
If I run the command manually (without the extension), nothing happens (no errors are shown in the terminal) and I still get a visual red squiggle. If I run my main.go test file manually, everything is just OK.
I have no clue what's this about, I just want to start deploying my function without the whole folder being red-colored and error-flagged by the VS code extension and I have no idea what to do to solve this.
EDIT. Here's my VS Code's settings.json file:
{
"[dart]": {
"editor.formatOnSave": true,
"editor.formatOnType": true,
"editor.rulers": [
80
],
"editor.selectionHighlight": false,
"editor.suggest.snippetsPreventQuickSuggestions": false,
"editor.suggestSelection": "first",
"editor.tabCompletion": "onlySnippets",
"editor.wordBasedSuggestions": false
},
"git.confirmSync": false,
"editor.fontSize": 18,
"workbench.iconTheme": "eq-material-theme-icons-darker",
"workbench.colorTheme": "Community Material Theme",
"dart.debugExternalLibraries": false,
"dart.debugSdkLibraries": false,
"window.zoomLevel": 1,
"[go]": {
"editor.insertSpaces": true,
"editor.autoClosingBrackets": "always",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"editor.suggest.snippetsPreventQuickSuggestions": true
},
}

Detecting whether shiny runs the R code

I would like to run R code in two locations, in an Rnw file and as an interactive shiny R markdown document.
Thus, what I need, since interactive shiny components do not work in Rnw files, is a code snippet in R that detects whether to load the interactive code or not.
This seems to work, but it feels like a quick hack:
if (exists("input")) { # input is provided by shiny
# interactive components like renderPlot for shiny
} else {
# non-interactive code for Rnw file
}
Is there a stable solution or something like a global variable that I can access that says whether shiny is running at the moment? Or should I check whether the shiny package is loaded?
What's safest?
There is now a function shiny::isRunning().
This information is provided directly via Shiny’s isRunning function.
Outdated answer below:
You can do the following:
shiny_running = function () {
# Look for `runApp` call somewhere in the call stack.
frames = sys.frames()
calls = lapply(sys.calls(), `[[`, 1)
call_name = function (call)
if (is.function(call)) '<closure>' else deparse(call)
call_names = vapply(calls, call_name, character(1))
target_call = grep('^runApp$', call_names)
if (length(target_call) == 0)
return(FALSE)
# Found a function called `runApp`, verify that it’s Shiny’s.
target_frame = frames[[target_call]]
namespace_frame = parent.env(target_frame)
isNamespace(namespace_frame) && environmentName(namespace_frame) == 'shiny'
}
Now you can simply use shiny_running() in code and get a logical value back that indicates whether the document is run as a Shiny app.
This is probably (close to) the best way, according to a discussion on Shiny the mailing list — but do note the caveats mentioned in the discussion.
Adapted from code in the “modules” package.
Alternatively, the following works. It may be better suited for the Shiny/RMarkdown use-case, but requires the existence of the YAML front matter: It works by reading the runtime value from that.
shiny_running = function ()
identical(rmarkdown::metadata$runtime, 'shiny')
Update: After Konrad Rudolphs comment I rethought my approach. My original answer can be found down below.
My approach is different from Konrad Rudolphs and maybe different to the OPs initial thoughts. The code speaks for itself:
if (identical(rmarkdown::metadata$runtime, "shiny")) {
"shinyApp"
} else {
"static part"
}
I would not run this code from inside an app but use it as a wrapper around the app. If the code resides within a .Rmd with runtime: shiny in the YAML front matter it will start the app, if not, it will show the static part.
I guess that should do what you wanted, and be as stable as it could get.
My original thought would have been to hard code whether or not you were in an interactive document:
document_is_interactive <- TRUE
if (document_is_interactive) {
# interactive components like renderPlot for shiny
} else {
# non-interactive code for Rnw file
}
Although possible, this could lead to problems and would therefore be less stable than other the approach with rmarkdown::metadata$runtime.

Access/manipulate history stack in R (up/down arrow)

I am working on a little interactive shell-like tool in R that uses readline to prompt stdin, like this:
console <- function(){
while(nchar(input <- readline(">>> "))) {
message("You typed: ", input)
}
}
It works but the only thing that bothers me is that lines entered this way do not get pushed upon the history stack. Pressing the up-arrow in R gives the last R command that was entered before starting the console.
Is there any way I can manually push the input lines upon the history stack, such that pressing the up-arrow will show the latest line entered in the console function?
I use this in rite to add commands to the command history. In essence, you can just savehistory and loadhistory from a local file. I do:
tmphistory <- tempfile()
savehistory(tmphistory)
histcon <- file(tmphistory, open="a")
writeLines(code, histcon)
close(histcon)
loadhistory(tmphistory)
unlink(tmphistory)
Note: Mac doesn't use history in the same way as other OS's, so be careful with this.

Resources