jebyrnes
jebyrnes

Reputation: 9332

Height of RMarkdown code chunk in reveal.js slides

I keep running into the problem of my code chunks overflowing in my slides, and so having to scroll around them. Not optimal for teaching.

  1. How can one make a code chunk taller (or wider) on a chunk by chunk basis?

  2. How can one in reveal.js or other html formats change code text size, again, on a chunk by chunk basis. I know globally I can change things in the CSS, but want to be more dynamic than that.

p.s. If anyone wants to know how to change the center-text behavior while not affecting other slide elements, troubleshot that one recently, and it's nontrivial, but doable.

Upvotes: 1

Views: 909

Answers (1)

Martin Schmelzer
Martin Schmelzer

Reputation: 23909

Customize Code Chunks using CSS

You could use fenced_code_attributes to add a CSS class (or several different classes) to certain code chunks. For this to work, you add this option to your YAML header and define a new hook using knit_hoooks$set() (for details see Hooks). After that, we can use the chunk option class = 'myCssClass'.

In the following example we define a class .smallCode, which sets a certain width for the chunk and a smaller font size. In the final document, the result looks like this:

<pre class="sourceCode r smallCode">
  <code class="sourceCode r">
  THE CODE WE PRODUCED
  </code>
</pre>

As you can see, we just added the class smallCode to the <pre> element! Yay!

You can modify anything, the font styles, the background and much more. For an overview of possibilities check out this CSS Tutorial

Wrapping Source Code

If you want the source code to be wrapped, you can use the chunk option tidy=T with its option width.cutoff (also implemented in the example below).

Reproducible Example:

---
title: "Customized Code Chunks"
author: Martin Schmelzer
date: March 22, 2005
output: 
  revealjs::revealjs_presentation:
    md_extensions: +fenced_code_attributes
---
<style>
pre.smallCode {
  width:  360px;               /* Change the width of the chunk */
  height: 360px;               /* Change the height of the chunk */
  font-size: 0.4em;            /* Change the font-size */
  background-color: lightgrey; /* Change background color */
} 
</style>

```{r, include=FALSE}
knitr::knit_hooks$set(source = function(x, options) {
  return(paste0(
    "```{.r",
    ifelse(is.null(options$class),
      "", 
      paste0(" .", gsub(" ", " .", options$class))
    ),
    "}\n",
    x,
    "\n```"
  ))
})
```

# Customized Code Chunks

## Example

<!-- Here we use the option tidy=TRUE with a cutoff after 40 characters -->
```{r, class = 'smallCode', tidy=T, tidy.opts=list(width.cutoff=40)}
df <- data.frame(A = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20))
```

And here is a screenshot of the code chunk we just have customized:

enter image description here

Upvotes: 4

Related Questions