4.4 Print Verbatim R code chunks
4.4.1 Verbatim inline code
- use
knitr::inline_expr.
---
title: "Test inline expr"
output: html_document
---
To use `chunk_reveal("walrus", title = "## Walrus operator")` inline, you can wrap it in R inline chunk like this
`` `r knitr::inline_expr('chunk_reveal('walrus', title='## Walrus operator')')` ``will be rendered as:
To use
chunk_reveal("walrus", title = "## Walrus operator")inline, you can wrap it in R inline chunk like this
`r chunk_reveal('walrus', title = '## Walrus operator')`
❗️ Need to be careful with nested quotes, single vs. double quotes. They need to be matched properly.
4.4.2 Verbatim R code chunks
Code chunks are executable blocks of code. But somtimes, you may want to display R code chunks verbatim in your output document, without executing them.
One solution for including verbatim R code chunks (see below for more) is to insert hidden inline R code (`r ''`) immediately before or after your R code chunk.
- The hidden inline R code will be evaluated as an inline expression to an empty string by knitr.
Then wrap the whole block within a markdown code block. The rendered output will display the verbatim R code chunk — including backticks.
R code generating the four backticks block:
Write this code in your R Markdown document:
````markdown
`r ''````{r}
plot(cars)
```
````
or
````markdown
```{r}`r ''`
plot(cars)
```
````
Knit the document and the code will render like this in your output:
This method makes use of Markdown Syntax for code.
Q: What is the Markdown Syntax for code?
A:
Inline code use a pair of backticks, e.g.,
`code`. To use \(n\) literal backticks, use at least \(n+1\) backticks outside.Note that use a space (
␣) to separate your outside backticks from your literal backtick(s).For example, to generate
`code`, you use``␣`code`␣``(i.e., two backticks + space + one backtick +code+ one backtick + space + two backticks). Note that you need to write sequentially.
Plain code blocks can be written either
After three or more backticks (fenced code blocks), or
Can also use tildes (
~)Indent the blocks by four spaces (indented code blocks)
Special characters do not trigger special formatting, and all spaces and line breaks are preserved. Blank lines in the verbatim text need not begin with four spaces.
Note that code blocks must be separated from surrounding text by blank lines.
If the code itself contains a row of tildes or backticks, just use a longer row of tildes or backticks at the start and end:
These begin with a row of three or more tildes (~) and end with a row of tildes that must be at least as long as the starting row.
A trick if you don’t want to type more than three tildes or backticks is that you just use different inner and outer symbols.
Will be rendered as:
4.4.3 Add attributes to text output blocks
A shortcut form (without braces) can also be used for specifying the language of the code block:
```haskell
qsort [] = []
```
This is equivalent to:
``` {.haskell}
qsort [] = []
```
haskell is the language class.
- If your class is inside braces, you need to add a dot before the language name, e.g.,
{.haskell}. - If add the language name without the braces, you don’t need the dot, e.g.,
haskell.
You can add more classes, including custom classes for styling. .className will be rendered as class="className" in the output HTML. Multiple classes can be added by separating them with spaces, e.g., {.haskell .numberLines}.
For example, you want to add a class numberLines for adding line numbers:
```haskell {.numberLines}
qsort [] = []
```
Which is equivalent to:
``` {.haskell .numberLines}
qsort [] = []
```
and
<pre id="mycode" class="haskell numberLines" startFrom="100">
<code>
primes = filterPrime [2..] where
filterPrime (p:xs) =
p : filterPrime [x | x <- xs, x `mod` p /= 0]
</code>
</pre>If highlighting is supported for your output format and language, then the code block above will appear highlighted, with numbered lines starting with 100, 101, and go on.
primes = filterPrime [2..] where
filterPrime (p:xs) =
p : filterPrime [x | x <- xs, x `mod` p /= 0]
Add styles directly to code blocks
You can add any HTML attributes to the code block, such as width, height, style, etc.
For example, you want to change the background color of a code block to pink.
The HTML output will be:
will look like
plot(cars)
Impose no wrap for certain code blocks
- Define a CSS class
no-wrapin your CSS file:
- Add this class to the code block:
```{.stata .nowrap}
. sysuse auto, clear
. regress price mpg
Long regression output that you don't want to wrap in the output document.
...
```By adding the nowrap class, the long regression output will not be wrapped in the output document; syntax highlighting will still work.
This prevents autowrap but will lose syntax highlighting.
<pre class="nowrap"><code>
</code></pre>
ref: R Markdown Cookbook: Add attributes to text output blocks
Code chunks within enumerate
Mind the indentation. Rstudio does not automatically adjust indentation for codes.
specify
results="asis"if encounterYou can’t use `macro parameter character #’ in horizontal mode.
cross references using bookdown (
\@ref{fig:scatter-plot}) might not work.Use latex references
\ref{fig:scatter-plot}(base latex) or\autoref{fig:scatter-plot}(fromhyperrefpackage)markdown language does not work well inside latex environments. A possible workaround is use
1and indent four spaces for contents that follow.
If it is still a pain in the ass, use this solution.
Basically, just copy the output from R condole and paste in Rmd.
References:
https://yihui.org/en/2017/11/knitr-verbatim-code-chunk/
https://themockup.blog/posts/2021-08-27-displaying-verbatim-code-chunks-in-xaringan-presentations/
Pandoc’s Markdown: https://pandoc.org/MANUAL.html#fenced-code-blocks