Hmm, I found some examples of the undocumented knit: hook, which could be used for this,
---
knit: (function(inputFile, encoding) {source('_pre_knit.R'); render(inputFile, output_format = custom_format, run_pandoc = FALSE); original = paste0(inputFile,"_tmp.Rmd"); rmarkdown::render(inputFile, encoding = encoding); file.copy(original, inputFile); unlink(original)})
output:
pdf_document
---
```{r preformat, echo=FALSE}
cap = function(x){if(knitr::is_latex_output())
sprintf("\\textsc{%s}",x) else x}
```
This is an R Markdown ~cap(document with formatting)~.
```{r reformat, echo=FALSE}
cap = function(x){if(knitr::is_latex_output())
sprintf("\\textbf{%s}",x) else x}
```
## Section 2
This is new section with ~cap(bizarre formatting)~.
with _pre_knitr.R containing the custom render functions (would eventually move to a package)
library(rmarkdown)
pre_knit <- function(input, ...){
rd <- readLines(input)
id <- grep('~', rd)
rd[id] <- stringr::str_replace_all(rd[id],
"~([:alnum:]+)\\((.*?)\\)~",
replacement = '`r \\1("\\2")`')
file.copy(input, paste0(input, 'original.Rmd'))
writeLines(text = rd, con = input)
}
custom_format <- rmarkdown::output_format(knitr = rmarkdown::knitr_options(opts_chunk = list(dev = 'png')),
pandoc = rmarkdown::pandoc_options(to = "markdown"),
pre_knit = pre_knit)
pdf_format <- rmarkdown::output_format(knitr = rmarkdown::knitr_options(opts_chunk = list(dev = 'png')),
pandoc = rmarkdown::pandoc_options(to = "latex"))
It kind of works, as a workaround; it might be tidier to modify the metadata between the two runs rather than create a temporary file. I'm still curious if there's a way to directly call pre_knit somewhere in the YAML.