Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Rework view() to better work with RStudio and Positron #1603

Merged
merged 3 commits into from
Sep 30, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 42 additions & 15 deletions R/view.R
Original file line number Diff line number Diff line change
Expand Up @@ -24,28 +24,55 @@
view <- function(x, title = NULL, ..., n = NULL) {
check_dots_empty()

if (!interactive()) return(invisible(x))
if (!is_interactive()) {
return(invisible(x))
}

# The user's expression and the environment to re-evaluate it in
quo <- enquo0(x)
expr <- quo_get_expr(quo)
env <- quo_get_env(quo)

if (is.null(title)) {
title <- expr_deparse(substitute(x), width = Inf)
title <- as_label(expr)
}

# Retrieve the `View()` function, which includes the special
# hooks created by RStudio or Positron
fn <- get("View", envir = as.environment("package:utils"))

if (!is.data.frame(x)) {
if (is.null(n)) {
n <- get_tibble_option_view_max()
}
x <- head(x, n + 1)
x <- as.data.frame(x)
if (nrow(x) > n) {
message("Showing the first ", n, " rows.")
x <- head(x, n)
}
return(view_with_coercion(x, n, title, fn))
}

# Make a `View()` call that we evaluate in the parent frame,
# as if the user called `View()` directly rather than `view()`.
# If `expr` directly references a data frame in the parent frame, this
# allows RStudio and Positron to "track" that original object
# for live updates in the data viewer.
inject((!!fn)(!!expr, !!title), env = env)

invisible(x)
}

view_with_coercion <- function(x, n, title, fn) {
if (is.null(n)) {
n <- get_tibble_option_view_max()
}

x <- head(x, n + 1)
x <- as.data.frame(x)

if (nrow(x) > n) {
message("Showing the first ", n, " rows.")
x <- x[seq_len(n), , drop = FALSE]
krlmlr marked this conversation as resolved.
Show resolved Hide resolved
}

view_fun <- get("View", envir = as.environment("package:utils"))
# Construct call with defused arguments, some versions of RStudio evaluate
# in the global environment (?).
eval_tidy(quo(view_fun(!!x, !!title)))
# Since we just created `x`, there won't be anything for
# RStudio or Positron to "track", so don't even make an effort
# to try and evaluate in the parent frame with the original
# expression
fn(x, title)

invisible(x)
}
Loading