---
title: "Instructions for Rmd authors of Guide Documents"
subtitle: "Using HTML Output for Guides"
author:
 - name: Paul Johnson
   affiliation: CRMDA
   email: pauljohn@ku.edu
advertise: >
   Please  visit [http://crmda.ku.edu/guides](http://crmda.ku.edu/guides) 
keywords: guide, Rmarkdown
abstract: >
    This document is just a little reminder of some key things.  
    The vignettes have all of the details.
checked_by: "First Last"
Note to Authors: please_dont_change_the_next 4 lines!
date: "`r format(Sys.time(), '%b. %e %Y')`"
output:
  stationery::crmda_html_document:
     toc: true
     toc_depth: 2
     highlight: haddock
     theme: default
     css: theme/kutils.css
     template: theme/guide-template.html
     number_sections: true
logoleft: theme/logoleft.png
logoright: theme/logo-vert.png
guide_number: 00
bibliography: R.bib
header-includes: 
  \usepackage[utf8]{inputenc}
---

```{r ignoremeRsetup, include=FALSE, results='hide'}
##This Invisible Chunk is required in all CRMDA documents
outdir <- paste0("tmpout")
if (!file.exists(outdir)) dir.create(outdir, recursive = TRUE)
knitr::opts_chunk$set(echo=TRUE, comment=NA, fig.path=paste0(outdir, "/p-"))
options(width = 70)
```



```{r ignoremeTexcopy, echo=F, results='hide'}
library(stationery)
## If theme directory does not have required images or TeX files
## we need to retrieve them and put them in "theme" directory. 
logos <- c("logoleft.png", "logo-vert.png")
try(getFiles(logos, pkg = "stationery", overwrite = FALSE))
## These theme files should be available already, but if not
themefiles <- c("kutils.css", "guide-template.html")
try(getFiles(themefiles, pkg = "stationery", overwrite = FALSE))
## If you do not have a file after that, 
## the following will manufacture a blank image for a placeholder
if(!file.exists("theme/logoleft.png")){
  blankPNG(file = "theme/logoleft.png", height=1, width=3.5, messg = "")
}
if(!file.exists("theme/logo-vert.pdf")){
  blankPNG(file = "theme/logo-vert.png", height=1, width=3.5, messg = "")
}
```


# Introduction

Create a template (skeleton) document by opening R and running

```
library(stationery)
initWriteup("rmd2html-guide")
```

That will create a folder `rmd2html-guide`. If you do not want a
directory to be created, then instead run


```
library(stationery)
initWriteup("rmd2html-guide", dir = ".")
```

This is not meaningfully different from the function in `rmarkdown`
called `draft`. 

# Proceed as follows

If you allowed initWriteup to create a directory, rename that
directory in a way that will be helpful to your project. For example,
“homework-1-2019” (anything that helps you remember what is in the
write-up).

Work on your own *.Rmd file. 

1. Copy the skeleton file to a new name. Choose a name that helps you,
   possibly “hw-1-2019.Rmd” or such.

2. See the code chunk above named ignoremeTexcopy. That is used to
   retrieve image files for the header. If you don't have image logo
   files that you want to use, the last part of that chunk will
   manufacture empty “blank” pdf logo files. It is safe to delete the
   ignoremeTexcopy chunk after you have the logo files you want in the
   theme folder.

3. Compile the document without making other changes. For instructions
   on compiling, see the Section named Compile the Document.

4. Make revisions incrementally. Start by inserting your own title and
   address information. Re-compile often to make sure no errors have
   been made.

Don't make changes that you don't understand in the ignoremeRoptions
code chunk above. For goodness sake, don't delete that one.


# Check our instructions

With every skeleton, we also provide an instructions file in the
working directory. 

There are also several vignettes distributed with the stationery package. Please review them.

1. “stationery”: the package framework overview
2. “code_chunks”: discusses display of code in LaTeX documents with both Sweave and knitr chunks
3. “Rmarkdown”: about using Markdown with R, an alternative to LaTeX/Noweb.
4. “HTML Special Features”: In Markdown intended for HTML output, authors can exploit some features. 


##  Compile the Document

There are several options. Suppose the document we edit is `skeleton.Rmd`.

1. Within R, run our function `rmd2html`

```
library(stationery)
rmd2html("skeleton.Rmd")
```

2. Use the shell script that is provided with the `skeleton.Rmd` file:

```
$ ./rmd2html.sh skeleton.Rmd
```

Both of these allow additional arguments, of course. The details on
all arguments allowed are offered in the documention within R.

For example, arguments specified here will override the settings in the
yaml header of the document:

```
stationery::rmd2html("skeleton.Rmd", toc = TRUE, toc_depth = 1, keep_md = TRUE)
```

The command line script allows the same arguments, however THERE MUST
NOT BE SPACES betwen the option name, the equal sign, and the value of 
the option:

```
$ ./rmd2html.sh --toc=TRUE --toc_depth=1 --keep_md=TRUE skeleton.Rmd
```

A full list of arguments is provided, in R run `?rmd2html`.

3. Open the Rmd file in RStudio. The "knit" menu should offer the
   correct choice "crmda_html_document". It is **VITAL** to choose the
   correct output format.
   
# Editor Caution: Rstudio Danger


While editing an Rnw file in Rstudio, there will be a button labeled
knit and a small triangle by that item. It is very (VERY!) important
to choose the correct output format. If you choose incorrectly,
Rstudio may damage your document by trying to revise it.

# What to edit

## Leave our template and style files (probably)

For our documents, we use a customized template and style sheet, those
are specified in the document header. 

```
output:
  stationery::crmda_html_document:
    css: theme/kutils.css
    template: theme/guide-template.html
	theme: default
```

Notice that the theme folder is supposed to have the style sheet,
images, etc. If those are not provided, the example documents have a
code chunk like this can be run to get them:

    `r ''````{r ignoreTexcopy, include=FALSE}
    library(stationery)
    ## If theme directory does not have required images or TeX files
    ## we need to retrieve them and put them in "theme" directory. 
    logos <- c("logoleft.png", "logo-vert.png", "R.bib")
    try(getFiles(logos, pkg = "stationery", overwrite = FALSE))
    ## These theme files should be available already, but if not
    themefiles <- c("kutils.css", "guide-template.html")
    try(getFiles(themefiles, pkg = "stationery", overwrite = FALSE))
    ## If you do not have a file after that, 
    ## the following will manufacture a blank image for a placeholder
    if(!file.exists("theme/logoleft.pdf")){
        blankPDF(file = "theme/logoleft.pdf", height=1, width=3.5, messg = "")
    }
    if(!file.exists("theme/logo-vert.pdf")){
        blankPDF(file = "theme/logo-vert.pdf", height=1, width=3.5, messg = "")
    }
     `r ''````
  

`getFiles()` is a simple little function that does almost nothing.  It
just saves one little step required to use `system.file` from R
base. That will not erase files if they exist already. Note you can
change the package where your logo files are stored. That's how we
customize reports in our workflow, the logos with our institutional
identifies are saved in a package called `crmda`.

## About the HTML file size problem.

The vignette "HTML special features" has a complete explanation.

The key advice is this. If you leave "theme: default" (or use any of
the bootstrap themes), then your document will incorporate the
bootstrap libraries and the saved file size will be (unacceptably)
large. If you change to "theme: null" then bootstrap features will be
lost, but some of the handy HTML features can be obtained without
bootstrap.

The HTML special feature that is especially likely to be helpful, and
is not costly, is the color highlighted section. These are callouts,
we have an implementation of them in our cascading style sheet. They
will work even if the bootstrap theming is turned off..

The other HTML special features that depend on the bootstrap library,
are the tabbed subsections and the bootstrap-resizeable sections.  The
resizable sections are especially designed to help readers on cell
phones. Maybe these features are no so important in some HTML
documents.

If you specify `theme: null` the document output HTML file will be
much smaller, but some features will no longer work correctly. The
tabbed subsections will be sacrificed and the proportional spacing
of the header may be somewhat "squished". 

# HTML special features

## Colored callout sections

These should work even if you disable bootstrap. We implemented them
in kutils.css

#### Colored callout is a level 4 heading with markup {.bs-callout .bs-callout-gray}
This is a gray callout. Could be "red", "orange" "blue", "green"
instead of gray. For more on this, there is the vignette "HTML_special_features".

#### Policies about writing in these documents. {.bs-callout .bs-callout-red}
This demonstrates a red callout

## Tabbed sub-sections {.tabset .tabset-fade}

These require bootstrap. If you change to `theme: null` then they will
print as ordinary sub sections.

Declare a level 2 heading with `{.tabset .tabset-fade}` and then the
level 3 headers after that are treated as tabs.

### <span style="color:red">First Tab Here</span>

Info within first tab. You must click "Second Tab Here" to see the
second tab.

### <span style="color:orange">Second Tab Here</span>

Now you see contents of second tab. I could, literally, write a book
in here. Could be code chunks, pictures, my favorite Bible verses.

### Third Tab Here

This is the content inside the third tab 

Note to terminate the tabbed sections we need to declare a new
section of a higher level.

## Math Check

The usage of equations is discussed in the vignette "R markdown". 
In HTML output, the display of equations requires an available MathJax
server.  Our function "stationery::crmda_html_document" should be
used as the output device because it protects the workability of
MathJax. Otherwise, it does nothing (just saying...).

Markdown accepts much LaTeX code. Especially well supported are
equations, either "inline", such as $y_i = \beta_0 + \beta_1 x1_i +
\varepsilon_i$, or "display" mode.

Because HTML output lacks some features we are accustomed to in \LaTeX
documents, the "usual rules" are not entirely correct. Nevertheless,
we ask authors to limit themselves to two styles of display equations.
Either use the demarcators `\[` and `\]` to declare a display equation:

\[
y_i = \beta_0 + \beta_1 x1_i + \varepsilon_i \label{eq:lin10}
\]

Or replace those demarcators with `\begin{equation}` and
`\end{equation}`. Even if the Rmd to HTML translation will tolerate
`$$` and `$$` to frame a displayed equation, don't use them.

Equation numbering does not work as usual in HTML output, that's
a problem discussed in "HTML_special_features". Immediately after
this text, we will write a display equation that would create
a numbered equation in an rmd2pdf document. The output will be an 
equation with no number and the cross reference that follows will
have an empty space in parentheses.

\begin{equation}
\hat{y}_i=\beta_0 + \beta_{1}X_i\label{eq:reg}
\end{equation}

Note a cross reference to that, such as "as we indicate in equation
(\ref{eq:reg})" is a fail.

This is an example of the reason why many of us suggest avoiding use
of HTML output if there is anything important to be presented in a
document. The proof-reading required to figure out which LaTeX
features might work, and which do not, is exhausting.


## Code Chunk Check

R code chunks are demarcated by three back-ticks and appear in-text
with a shaded box (because we are using the listings-style output).

```{r myFirstPlot, dev=c('png'), out.width="500px",out.height="300px", fig.width=4, fig.heigth=2}
x <- rnorm(500)
hist(x)
```

There are many more examples of code chunks in the vignette "code_chunks". 

#### R code inside a colored callout {.bs-callout .bs-callout-red}
```{r xsummary}
mean(x)
```

```{r reg10}
dat <- data.frame(x = rnorm(100), y = rnorm(100))
m1 <- lm(y ~ x, data = dat)
```
```{r reg20, results='asis'}
library(rockchalk)
vl <- c("x" = "Excellent Predictor")
or <- outreg(list("First Model" = m1), varLabels = vl, tight = FALSE,
type = "html", browse = FALSE)
```

In the kutils package, we made a function semTable() that presents
structural equation models. 

```{r sem10}
library(kutils)
require(lavaan)
HS.model <- 'visual  =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed   =~ x7 + x8 + x9'
output1 <- cfa(HS.model, data = HolzingerSwineford1939, std.lv = TRUE)
```

```{r sem20, results='asis'}
cfa1 <- semTable(output1, fits = "rmsea", paramSets = c("loadings", "latentvariances"), type = "html")
```

# Citations

The YAML header specifies the name of the bibliography file.  The
HTML backend wants the full name of the bib file, "theme/R.bib" 
whereas the documents that use PDF backend want simply "theme/R".
We'll figure that out someday.

The markdown citation method would use brackets, as in [@RCore] and
[-@RCore]. 

Please remember that LaTeX natbib notation is not supported in
the `rmd2html` transition, as you should see here: \citep[RCore]. 
LaTeX style cites will work in rmd2pdf type documents. 


[//]: (All guides must have this as the final stanza)

## Replication Information
```{r sessionInfo, echo = FALSE}
sessionInfo()
```

```{r warnings, echo = FALSE}
if(!is.null(warnings())){
    print("Warnings:")
    warnings()
}
```

Available under
[Created Commons license 3.0 <img src="http://crmda.dept.ku.edu/images/cc-3.0.png" alt="CC BY"
style="width: 75px;height: 20px;"/>](http://creativecommons.org/licenses/by/3.0/)

