gestalt icon indicating copy to clipboard operation
gestalt copied to clipboard

Printing in Jupyter notebook

Open egnha opened this issue 6 years ago • 4 comments

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?

egnha avatar Jun 14 '18 18:06 egnha

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().

egnha avatar Jun 16 '18 12:06 egnha

Implement and export repr::repr_html methods for Gestalt's function classes.

egnha avatar Aug 06 '18 13:08 egnha

Initial implementation:

# repr/R/utils.r:
html_escape <- local({
  html_specials <- c(
    `&` = "&amp;",
    `<` = "&lt;",
    `>` = "&gt;"
  )
  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")

egnha avatar Aug 06 '18 13:08 egnha

Enable option to syntax-highlight.

egnha avatar Aug 06 '18 13:08 egnha