Using a custom template for Rmd pdf without changing current setup - r

I have recently learned that modifying the default (Pandoc?) template for a Rmd pdf report gives access to some neat customisation.
So in order to modify the default template I first move it to my working directory using:
file.copy(system.file("rmd/latex/default-1.17.0.2.tex", package ="rmarkdown"), "template.tex")
Next I type up my Rmd file:
---
output:
pdf_document:
template: template.tex
keep_tex: true
latex_engine: xelatex
includes:
in_header: in_header.tex
number_sections: true
---
This is a rmd kind of document.
Where in_header.tex includes only one line
\geometry{a4paper, top=38mm, left=45mm, right=45mm}
I first just want to run the Rmd file with the template as is (expecting no change) but the report fails to compile if and only if I include the template - otherwise it runs without an issue.
The error is
! Undefined control sequence.
l.58 \geometry
[...]
Question
How can I use the template argument to build on an editable template in my working folder without causing any other change to my current setup.
Info
> R.Version()[["version.string"]]
[1] "R version 3.5.1 (2018-07-02)"
> packageVersion("rmarkdown")
[1] ‘1.10’
> packageVersion("knitr")
[1] ‘1.20’

As you are already driving this from R, you may as well use the (excellent) example set up by the rticles package which provides a larged number of LaTeX customizations for (academic) papers.
And you can then run with that them. For example, over the last two years I added these packages:
tint for a modern 'Tufte-alike' writeup
pinp for very nice two-column pdf vignettes
link for LaTeX letters and some extra
binb for variants of beaner packages
This allows you to
set a custom template.tex
include whichever LaTeX class files / style files you need
programmatically set options
I find this preferable to copying stanzas around which I did previously (eg for slides).

The rmarkdown::pdf_output function seems to do a few things differently when the default template is used. For example, it sets the variable graphics=yes. I suspect that it also sets geometry, but I have not seen where it does that. Anyway, if you want to use a custom template based on the default template you are "fighting" with this block from the template:
$if(geometry)$
\usepackage[$for(geometry)$$geometry$$sep$,$endfor$]{geometry}
$endif$
The geometry package is only loaded, when the geometry header is defined. One simple solution to your problem is to move the geometry definition from the header include to the YAML header:
---
geometry:
- a4paper
- top=38mm
- left=45mm
- right=45mm
output:
pdf_document:
template: template.tex
keep_tex: true
latex_engine: xelatex
includes:
in_header: in_header.tex
number_sections: true
---
This is a rmd kind of document.
With this you can remove \geometry{...} from in_header.tex.

Related

Change default YAML of Rmarkdown file

I want to change the default template of the Rmarkdown document. I edited the file named document.Rmd in the templates in the RStudio application folder so that the YAML is:
---
title: 'document'
output:
html_document:
self_contained: true
toc: true
toc_float: true
bookdown::pdf_document2:
extra_dependencies: ["float"]
toc: true
---
However, when I open a new Rmarkdown document from RStudio, I get a prompt that asks what type of Rmarkdown document I want. I choose HTML, click OK, and then I get the file opened with these two YAMLs!
---
title: "Untitled"
output: html_document
---
---
title: 'document'
output:
html_document:
self_contained: true
toc: true
toc_float: true
bookdown::pdf_document2:
extra_dependencies: ["float"]
toc: true
---
I do not want to go through the hustle of creating a package or a template. This simple solution should work, I think.
My question: Does anybody know how to work around this? Thank you in advance!
After reading your question, I found this source, which indicated that you could add a template. I also read that document.RMD does not include the YAML. That's why you are getting a double-YAML.
Since I had never added a template for R Markdown, I went through the steps to see how it all came together. That led me to create a repository on Github, and well, here we are. Essentially, I made a Github repository that you can install with the exact template you wanted.
You can also look at the code, as well. Since it was created just to answer this question, if you wanted it to be different, you can change it, as well.
You'll find the repository here: fraupflaume/customYAML
If you want to install it:
devtools::install_github("fraupflaume/customYAML")
To use it, you don't have to call the library (there's no R code). Start an R Markdown script, select "From Template," then choose "Custom YAML."

Purposes of theme, template and includes in beamer presentation generated with R markdown

R markdown presentations with output format beamer can make use of
Classical LaTex beamer themes such as Copenhagen or Madrid or employ custom beamer themes.
Templates , i.e. a template.tex
Includes, e.g. in_header: preamble.tex, before_body: before_body.texand after_body: after_body.tex
which can be implemented in the rmarkdown::beamer_presentation through the YAML-header as follows:
theme: "THEMENAME"
template: template.tex
includes:
- in_header: preamble.tex
- before_body: before_body.tex
- after_body: after_body.tex
What are the specific purposes of these files? That is, what contents should go in each of these files, how do they add or modify the final presentation, and which of the files are equivalent and possibly redundant?
If I understand the rmarkdown lingo correctly, they use the term template for the instructions how the markdown document will be translated into tex, e.g. the default beamer_presentation template for example defines how information from your yaml-header is used in the tex document, e.g. that whatever you put down for title will be translated into \title{...}. It also contains a hole kitchen sink of packages rmarkdown loads by default, many of which make no sense with beamer.
the include hooks offer possibilities to smuggle additional latex code into your document. The difference between the different options is where they will be executed in the intermediate tex document. For example in_header will be included at the end of the preamble. Which of them to use will depend on what you want to add. For most things in_header will be fine.

Bookdown: Exporting to a word document (Error in files2[[format]] : attempt to select less than one element in get1index)

I am writing my thesis using the bookdown package and the memoir latex class. Everything works relatively fine when I am exporting to pdf or to html but I am unable to export the thesis to a word document...
I get the following mysterious error:
Error in files2[[format]] :
attempt to select less than one element in get1index
It is difficult to provide a reproducible example though, as I am working from my messy dissertation repository.
But here is (a part of) my _output.yml file:
bookdown::pdf_book:
includes:
in_header: latex/preamble.tex # defines style and latex options
before_body: latex/before_body.tex # defines cover page
latex_engine: xelatex # lualatex or xelatex
citation_package: none # needs to be "none" in order to use the csl file
keep_tex: true # keeps the .tex file
dev: "cairo_pdf"
toc: false # deactivates default table of contents
highlight: pygments # code highlighting
pandoc_args: [ "--csl", "./csl/apa6.csl" ] # specifies the csl file to be used
bookdown::word_document2:
pandoc_args: [
"--csl", "./csl/apa6.csl",
"--bibliography", "./bib/packages.bib",
"--bibliography", "./bib/thesis.bib",
#"--reference-doc", "./assets/2018-05-17-aim1-draft.docx",
"--filter", "pandoc-citeproc"
#"--filter", "./assets/fix-apa-ampersands.py"
]
Any idea ?
This is a bug of the bookdown package, which I just fixed on Github. Please try the development version there:
remotes::install_github('rstudio/bookdown')

knitr/pandoc: article template supporting keywords: and linespacing:

I'm using the latest R Studio, R 3.2.5, rmarkdown 0.9.6, which comes with pandoc 1.15.2 to write a journal article. Submission requires: linespacing: 1.43 and a keywords: line just below the abstract.
When I click Knit PDF I get the default template "C:\R\R-3.2.5\library\rmarkdown\rmd\latex\default-1.15.2.tex" which does not support these fields in the YAML header. I see that default-1.17.02.tex supports linespacing:, but not keywords:.
I tried to modify the latter template to add keywords handling, which seemed pretty straight-forward. The relevant portion of the template, that I called modified-template-1.17.0.2.tex is
$if(title)$
\maketitle
$endif$
$if(abstract)$
\begin{abstract}
$abstract$
\end{abstract}
$endif$
\providecommand{\keywords}[1]{\textbf{\textit{Keywords---}} #1}
$if(keywords)$
\keywords{$keywords$}
$endif$
I used the YAML header below, and pandoc found it; however, it generated .tex syntax errors, unrelated to the keywords: field. I'm thinking that the rmarkdown templates are specific to the version of pandoc, but I have no way to tell.
can anyone help with this?
---
title: "My title"
author: ME
date: '`r format(Sys.time(), "%B %d, %Y")`'
output:
pdf_document:
fig_caption: yes
keep_tex: yes
number_sections: yes
template: "modified-template-1.17.0.2.tex"
keywords: Box M test, HE plots, MANOVA, graphics, ...
abstract: "This paper explores a variety of fascinating topics ... "
---
Note added: I tried this modifying the default-1.15.2.tex template as described above. My result is the same, and the error I get is:
! Undefined control sequence.
l.527 {\centering \includegraphics
pandoc.exe: Error producing PDF from TeX source
Error: pandoc document conversion failed with error 43
One more test: I simply used a copy of the standard default-1.15.2.tex template in my local folder, with the YAML line
template: "default-1.15.2.tex"
This also gives the same error, so I am mystified as to the cause.
This is an answer to the keywords: problem. It is admittedly a kludge, but doesn't require changing the template: Simply include the keywords as an additional paragraph in the abstract in the YAML header.
abstract: "This paper explores a variety of topics ...
**Keywords**: Box's M test; HE plots; MANOVA; graphics
"
To format as a separate paragraph required two blank lines
For posterity, one solution that seems to work is to copy default-1.17.02.tex to the working directory and modify it to include the keywords argument. In the renamed modified-1.17.02.tex, add this after the if block for the author name:
$if(keywords)$
pdfkeywords={$for(keywords)$$keywords$$sep$; $endfor$},
$endif$
And then later in the document, after the if block for placing the abstract:
\providecommand{\keywords}[1]{\textbf{\textit{Keywords---}} #1}
$if(keywords)$
\keywords{$keywords$}
$endif$
In the project Rmd file, we just need to specify that we are using our custom template, specify that graphics = true (to circumnavigate the \includegraphics error) and the keywords themselves:
---
title: "My title"
author: ME
date: '`r format(Sys.time(), "%B %d, %Y")`'
output:
pdf_document:
template: modified-template-1.17.0.2.tex
graphics: yes
keywords: keyword 1; keyword 2; et cetera
abstract: "Abstract here."
---
Body of article here.
Compiling yields a title page with the keywords field present:
EDIT: The OP also mentioned line spacing. When using the 1.17.02.tex style (used automatically if the most recent version of Pandoc is available, either through manual install or by using the latest RStudio preview build), the ability to adjust the line spacing is done by setting linestretch: 1 for single space, and linestretch: 2 for double anywhere in the YAML header.

References Truncated in Beamer Presentation prepared in Knitr/RMarkdown

I'm currently preparing a presentation in RStudio (using RMarkdown and Knitr, outputting to a Beamer presentation) that has quite a few references.
I'm using a pretty typical YAML header:
---
title: "Title"
author: "Me"
date: "February 27th, 2016"
output:
beamer_presentation
csl: ../../apa.csl
bibliography: ../../RefenceDesk.bib
---
This presentation compiles and the references appear as they should, but unfortunately they all appear on one slide (and actually run off the page). Is there any way to have the references appear on multiple slides?
{.allowframebreaks} is the solution for multislides bibliographies in beamer. It works out of the box with regular pandoc templates (see my previous answer). However, knitr has a setting that prevents it, by redefining \widowpenalties in its beamer template. You can verify that if you examine the .tex file with keep_tex: true.
In my opinion, this is a bug. A quick fix would be to reset \widowpenalties to its default value. It can be done in your yaml front matter:
---
title: Title
header-includes:
- \widowpenalties 1 150
output:
beamer_presentation
---
Then, you can indicate the reference section as such:
## References {.allowframebreaks}
As #David above said in the comments:
For me it didnt work with ## References {.allowframebreaks} but it worked out with # References {.allowframebreaks}.
I would like to point out that, apparently for the reference slide to work you have to create a last slide with the same heading level es set by slide_level: __ at the YAML section.
So, the user should set one of the following:
# References {.allowframebreaks}. for those using slide_level: 1, OR
## References {.allowframebreaks}. for those using slide_level: 2, OR
### References {.allowframebreaks}. for those using slide_level: 3 and so on...
While this goes outside of using the regular pandoc citation template, I have found another approach that can be used to put the references across slides but it relies on the natbib citation package.
In the YAML front matter, I added:
---
title: "Title"
output:
beamer_presentation:
citation_package: natbib
bibliography: ../../RefenceDesk.bib
biblio-style: "apalike"
---
The reference slide does not get a title and I cannot seem to adjust the font size (by using a \scriptsize at the end of the .Rmd file), but at least they appear coherently.
EDIT: For parsimony, I removed the csl: ../../apa.csl line, since natbib does not require it.

Resources