21 Translating R code

21.1 HTML

  1. Q: TODO: Adapt to the new exercise formulation:

    The escaping rules for <script> tags are different because they contain JavaScript, not HTML. Instead of escaping angle brackets or ampersands, you need to escape </script> so that the tag isn’t closed too early. For example, script("'</script>'"), shouldn’t generate this:


    Adapt the escape() to follow these rules when a new argument script is set to TRUE.

    Old exercise text: The escaping rules for <script> and <style> tags are different: you don’t want to escape angle brackets or ampersands, but you do want to escape </script> or </style>. Adapt the code above to follow these rules.

    TODO: Check why escaping of script/style tags would be necessary and change answer accordingly: https://github.com/hadley/adv-r/issues/1190

    Required Code from Advanced R:

    A: Sourcecode wrapped in <script> or <style> tags is different from the other HTML-tags: the <script> tag inserts (mainly) JavaScript into the HTML document. Here the angle brackets and ampersands should not be escaped so the code remains intact. Because JavaScript may contain multiple nested <script> tags, we need to escape the inner tags as <\/script>.

    check, what is meant with “want to escape </script> or </style>

    style tags encapsulate css-styling guidelines and the escaping follows the same rules as for the JavaScript above.

    Our tag function factory needs two serve two competing requirements for escaping: For most of the tag functions the content (brackets and ampersands) needs to be escaped. In script and style tags the content should NOT be escaped, but closing script- and style-tags need to be escaped.

To distinguish between these options, we extend escape.character() to include an argument (escape_choice) to choose the escape-style, that we want.

# add argument `escape_choice` to escape-function
escape.character <- function(x,
                             escape_choice = c("content", "script_or_style")
                             ) {
  escape_choice <- match.arg(escape_choice)
  if (escape_choice == "content") {
    x <- gsub("&", "&amp;", x)
    x <- gsub("<", "&lt;", x)
    x <- gsub(">", "&gt;", x)
  if (escape_choice == "script_or_style") {
    x <- gsub("</script>", "<\\/script>", x, fixed = TRUE)
    x <- gsub("</style>",  "<\\/style>",  x, fixed = TRUE)

escape.advr_html <- function(x, ...) x

escape <- function(x, ...) UseMethod("escape")

When we create the tag functions we can then specify the escape style we want:

# create tag with specified escape-style
tag <- function(tag,
                escape_choice = c("content", "script_or_style")) {
  escape_choice <- match.arg(escape_choice)
    exprs(... = ),
      dots <- dots_partition(...)
      attribs <- html_attributes(dots$named)
      children <- map_chr(dots$unnamed,
                          # choose the escaping
                          ~ escape(., escape_choice = !!escape_choice))
      !!paste0("<", tag), attribs, ">",
      paste(children, collapse = ""),
      !!paste0("</", tag, ">")

Let’s test our new tag() function:

p <- tag("p")
b <- tag("b")

identical(p("This &","this <content>",
            b("& this will be escaped")) %>%
          "<p>This &amp;this &lt;content&gt;<b>&amp; this will be escaped</b></p>")
#> [1] TRUE

script <- tag("script", escape_choice = "script_or_style")

script("These signs will not be escaped: &, <, >, ", "but these ones will: </script> or </style>")
#> <HTML> <script>These signs will not be escaped: &, <, >, but these
#> ones will: <\/script> or <\/style></script>
  1. Q: The use of ... for all functions has some big downsides. There’s no input validation and there will be little information in the documentation or autocomplete about how they are used in the function. Create a new function that, when given a named list of tags and their attribute names (like below), creates tag functions with named arguments.

    All tags should get class and id attributes.

    A: The use of ... for all functions seems too general. It is known which attributes each tag function may have, so we can organize them in a named list of tags and attribute names.

    We now need to create tag functions where these attributes are prespecified as arguments. This will enable autocompletion and input validation. (Documentation would require the functions to be bundeled as a package which we won’t do here.)

    Let’s start by programmatically creating one tag function now and worry about the iteration problem later.

    The function factory needs to be changed: We need to parse the information provided by the list (tag name and arguments) and unquote-splice the provided arguments into the args part of rlang::new_function(). This will provide the autocompletion. In this step we also add the global attributes class and id.

    The values of the provided named attributes need to be collected, when the function is called. We use a little “environment-hack” to accomplish this.

We also rewrite validate_dots. We check for any unexpected named arguments, which will serve as input validation. The list of unnamed arguments will be escaped as before.

validate_dots <- function(...) {
  dots <- dots_list(...)
  # Input validation
  if (any(have_name(dots))) { # names(dots) != ""
    stop("Unexpected named argument found.")
  list(unnamed = dots)

A few comments regarding the implementation details: The ... had to be placed in front of the other arguments - otherwise positional matching would assign unnamed values to prespecified values and and unnamed content wouldn’t be recognized properly. It was also a challenges to properly collect the prespecified arguments. These are prespecified but setting them at runtime is optional, so they had to be collected in a lazy fashion. Our hack via caller_env() isn’t pretty and could certainly be improved upon - but it works, as we can see here:

# create a single tag function
a <- tag(list(a = "href"))
#> Error in tag(list(a = "href")): could not find function "tag"

# all the general and specific arguments exist, so autocompletion will work
#> Error in formals(a): object 'a' not found

# named arguments are attributes, content is escaped properly
a(class = "anchor", id = "a-1", 
  href = "http://somelink.com", "take a look at this & this")
#> Error in a(class = "anchor", id = "a-1", href = "http://somelink.com", :
#> could not find function "a"

# not all named arguments need to be used
a(href = "http://somelink.com", "take a look at this")
#> Error in a(href = "http://somelink.com", "take a look at this"): could not
#> find function "a"

# unspecified named arguments will throw an error
a(href = "http://somelink.com", "take a look at this", width = "200")
#> Error in a(href = "http://somelink.com", "take a look at this", width =
#> "200"): could not find function "a"

To create many tag functions we can iterate over a list with inputs.

tag_inputs <- list(
  a = c("href"),
  img = c("src", "width", "height"),
  body = NULL,
  h1 = NULL,
  b = NULL,
  p = NULL
# FIX required

# TODO: created functions not fully correct, somehow attribs is written into the tag function instead of the tag-name

# structure of the map/list structure not correct yet
html_tags <- tag_inputs %>% 
  map(~ tag)  # potentially use imap to operate on index as well
  1. Q: Reason about the following code that calls with_html() referening objects from the environment. Will it work or fail? Why? Run the code to verify your predictions.

    A: (TODO: In the exercise the definition of p changed into p <- function() "p". This needs to be added and the exercise/answer might need to get updated. Further with_html is defined in the next exercise. Therefore, a change to introduce it already here has to be made…and the chunks then need to be changed to eval = TRUE) When we created the various HTML tag functions, address() was one of them. This HTML tag may be used to provide contact information on an HTML page. All our tag functions are not present in the global environment, but rather elements of the list html_tags.

    The DSL code wrapped in with_html() is evaluated in its own environment and in the “context” of html_tags. The tag functions are available, because we provided a list of them as a data mask. As /home/travis/R/Library/rlang/help/as_data_mask indicates: “Objects in the mask have precedence over objects in the environment.”

    The error message then tells us, what the problem is: p(address) operates on address(), the function not the character, and we haven’t implemented an escape.function() method.

  2. Q: Currently the HTML doesn’t look terribly pretty, and it’s hard to see the structure. How could you adapt tag() to do indenting and formatting? (You may need to do some research into block and inline tags.)

    A: First let us define all needed functions from the textbook:

    Now, let’s look at the example from above:

    The formatting comes down to just one long line of code. This output will be more difficult to work with, to inspect what the code does and if it’s correct. What kind of formatting would we prefer instead? The Google HTML Styleguide suggests indentation by 2 spaces and new lines for every block, list, or table element. There are other recommendations, but we will keep things simple and will be satisfied with the following output.

    First we adjust the print.advr_html method. We replace the strwrap function, because this will wrap HTML-code into one long line regardless of its input. We use cat instead, because it prints linebreaks ("\n") nicely.

    In our desired output we can see, that the content of the body-function requires another formatting than the other tag-functions. We will therefore create a new format_code-function, that allows for optional indentation and linbreaks. For this strwarp provides two helpful arguments: each element will start with a linebreak (prefix = "\n") and will be indentend propely (indent = 2).

    We adjust the body function to include the format_code()-helper. (This could also be approached programatically in the tag function factory.)

    The resulting output is much more satisfying.

21.2 LaTeX

  1. Q: Add escaping. The special symbols that should be escaped by adding a backslash in front of them are \, $, and %. Just as with HTML, you’ll need to make sure you don’t end up double-escaping. So you’ll need to create a small S3 class and then use that in function operators. That will also allow you to embed arbitrary LaTeX if needed.


  2. Q: Complete the DSL to support all the functions that plotmath supports.