gestalt
gestalt copied to clipboard
Printing in Jupyter notebook
Executing a cell like
abs %>>>% log
ignores the class and prints
structure(function (x)
`__2__`(`__1__`(x)), class = c("CompositeFunction", "function"
))
whereas
print(abs %>>>% log)
applies the correct print method
<Function Composition>
In order of application:
[[1]]
function (x) .Primitive("abs")
[[2]]
function (x, base = exp(1)) .Primitive("log")
Recover the list of functions with 'as.list()'.
Similar problem occurs for other custom gestalt classes ("PartialFunction"
, etc.).
Is this an issue with Jupyter and/or gestalt?
This is an issue in the repr package, which circumvents dispatching print
to the proper method when the object class is "function"
. As a workaround, one can explicitly invoke print()
.
Implement and export repr::repr_html
methods for Gestalt's function classes.
Initial implementation:
# repr/R/utils.r:
html_escape <- local({
html_specials <- c(
`&` = "&",
`<` = "<",
`>` = ">"
)
pre_wrap <- "<span style=white-space:pre-wrap>%s</span>"
function(text) {
for (chr in names(html_specials))
text <- gsub(chr, html_specials[[chr]], text, fixed = TRUE)
consec_spaces <- grepl("\ \ ", text)
text[consec_spaces] <- sprintf(pre_wrap, text[consec_spaces])
text
}
})
#' @importFrom utils capture.output
as_repr_html <- function(class) {
printer <- get(paste0("print.", class))
wrap <- "<pre class=language-r><code>%s</code></pre>"
function(obj, ...) {
code <- capture.output(printer(obj))
sprintf(wrap, paste(html_escape(code), collapse = "\n"))
}
}
#' @importFrom repr repr_html
NULL
#' @export
repr_html.CompositeFunction <- as_repr_html("CompositeFunction")
#' @export
repr_html.PartialFunction <- as_repr_html("PartialFunction")
Enable option to syntax-highlight.