R/utils.R

Defines functions cat_trace print.latexexpression print.latextoken2 str_replace_fixed `%??%`

Documented in print.latexexpression print.latextoken2

`%??%` <- function(x, y) {
  return(if (is.null(x) || is.na(x) || (is.logical(x) && !x))  y else x)
}

str_replace_fixed <- function(string, pattern, replacement) {
  str_replace_all(string, fixed(pattern), replacement)
}

#' Prints out a parsed LaTeX object, as returned by TeX(..., output='ast').
#' This is primarily used for debugging.
#' 
#' @param x The object
#' @param depth Increases padding when recursing down the parsed structure
#' @param ... (Ignored)
#' @export
print.latextoken2 <- function(x, depth=0, ...) {
  token <- x
  pad <- strrep(" ", depth)
  cat(pad,
      if (depth > 0) str_c("| :", token$command, ":"), 
      if (!is.null(token$rendered)) str_c(" -> ", token$rendered),
      "\n",
      sep="")
  
  for (children_type in c("children", "args", "optional_arg", "sup_arg", "sub_arg")) {
    if (length(token[[children_type]]) > 0) {
      if (children_type != "children") {
        cat(pad, "* <", children_type, ">", "\n", sep="")
      }
      for (tok_idx in seq_along(token[[children_type]])) {
        c <- token[[children_type]][[tok_idx]]
        if (is.list(c)) {
          cat(pad, " | [argument ", tok_idx, "]\n", sep="")
          for (cc in c) {
            print(cc, depth+1)
          }
        } else {
          print(c, depth+1)
        }
      }
    }
  }
}

#' Print an expression returned by TeX()
#' 
#' Prints out the plotmath expression generated by \code{\link{TeX}}
#' and the original TeX string.
#' 
#' @param x Object to print
#' @param ... Ignored
#' @export
print.latexexpression <- function(x, ...) {
  cat("   LaTeX:", attr(x, "latex"), "\n")
  cat("plotmath:", attr(x, "plotmath"), "\n")
}

cat_trace <- function(...) {
  trace <- getOption("latex2exp.debug.trace", FALSE)
  if (trace) {
    cat("Trace:", ..., "\n")
  }
}
stefano-meschiari/latex2exp documentation built on Jan. 27, 2023, 3:43 a.m.