egnha / gestalt

Tidy Tools for Making and Combining Functions
Other
38 stars 3 forks source link

Printing in Jupyter notebook #8

Open egnha opened 6 years ago

egnha commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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

egnha commented 6 years ago

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 commented 6 years ago

Enable option to syntax-highlight.