When I type an expression into the R prompt, the result is normally printed to the terminal, unless something prevents it:
> 1+1
[1] 2
> 1:10
[1] 1 2 3 4 5 6 7 8 9 10
> invisible(1:10) # This prints nothing
I am trying to set up R to evaluate a bit of code immediately before printing anything. The obvious thing to do is to use trace
to add an expression to the body of print
. This has the expected effect when calling print
explicitly, but not when simply evaluating an expression and letting it print automatically:
> trace(print, tracer = expression({cat("printing\n")}), print = FALSE)
> print(1:10) # Explicit print: trace code is executed
printing
[1] 1 2 3 4 5 6 7 8 9 10
> 1:10 # Implicit print: no trace
[1] 1 2 3 4 5 6 7 8 9 10
So evidently R is not actually calling print
when it simply wants to print the result of an expression, even though the result is the same as calling print
explicitly. So what function is it calling, if any? Is there any function I can trace in place of print
to make R evaluate my code prior to implicit printing?
If anyone is wondering, the code I actually want to execute is this function, which tells R the current terminal window width so it can use the full width when printing things:
get_terminal_width <- function() {
cols <- as.numeric(Sys.getenv("COLUMNS"))
if (!is.na(cols)) {
return(cols)
}
cols <- as.numeric(system2("tput", "cols", stdout = TRUE))
if (!is.na(cols)) {
return(cols)
}
return(NA_integer_)
}
update_width <- function(...) {
try(options(width=as.character(get_terminal_width()-1)), silent = TRUE)
}
I think you are asking about low level R behaviour that is governed by functionality that was coded in C, so you may struggle to capture and alter that behaviour in traditional R ( i.e. not compile your own version of R) take a look at 1.6 : https://cran.r-project.org/doc/manuals/r-release/R-ints.html