Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indent R Markdown code block in PDF/LaTeX output

I am currently writing a document in RMarkdown and knitting the output to pdf. It would be desirable for me to indent the code blocks to be consistent with the rest of my formatting.

Here is the document as written:

example document

I would like the gray portion of the block to be in line with "This is a sentence."

Is there a way to do this in R markdown, perhaps by dropping down into LaTeX?

like image 981
Bryce Frank Avatar asked Nov 24 '25 06:11

Bryce Frank


1 Answers

If you want to change the formatting of the box, the key line in the LaTeX template is:

\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}

The snugshade command is defined within the framed LaTeX package, which is useful for creating shaded boxes as included within RMarkdown. However, it lacks many controls to simply edit the styling.

Based off this answer, you could consider using the mdframed package which offers more advanced controls than the framed package. As explained here The margins can be tweaked using the renewenvironment command, which we will use to redefine the Shaded function with our custom style:

enter image description here

To get this working in RMarkdown, we need to replace the Shaded environment with our new definition. This can be achieved as follows:

---
output: 
  pdf_document:
    keep_tex: TRUE
header-includes:
  - \usepackage{mdframed}
  - \definecolor{shadecolor}{gray}{.95}
  - \renewenvironment{Shaded}{\begin{mdframed}[
      backgroundcolor=shadecolor,
      linecolor = shadecolor,
      leftmargin=\dimexpr\leftmargin-2pt\relax,
      innerleftmargin=1.6pt,
      innertopmargin=5pt,
      skipabove=10pt,skipbelow=3pt
    ]}{\end{mdframed}}
---

Some Text

```{r cars}
summary(cars)
```

enter image description here

Note: as you haven't provided a reproducible example, you will have to fine tune the settings to get this working with your configuration.

If you start getting more LaTeX commands, you can considering saving this as a separate .tex file as explained here

like image 125
Michael Harper Avatar answered Nov 26 '25 19:11

Michael Harper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!