Search code examples
ryamlr-markdownknitrvignette

Replace file header containing escape characters


I created a vignette for a package with following header:

---
title: "My package vignette"
output: rmarkdown::html_document
vignette: >
  %\VignetteIndexEntry{MyPackage}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

However, vignette format doesn't allow full functionalities allowed by html_document.

I would like to automatically change the YAML header in order to have the ability to knit the vignette in full html_document format (with options like toc_float: true)

I'm trying to read the .Rmd file with ReadLines and replace the header using gsub, but I'm struggling with escape characters / regex:

content <- readLines('vignettes/MyPackage.Rmd',encoding = 'UTF-8')

vignette_header <- "output: rmarkdown::html_document
vignette: >
  %\\VignetteIndexEntry{MyPackage}
  %\\VignetteEngine{knitr::rmarkdown}
  %\\VignetteEncoding{UTF-8}"

normal_header <- 
'output:
  html_document:
    toc_float: true'  

gsub(vignette_header,normal_header,content )
Error in gsub(vignette_header, normal_header, content) : 
  regular expression 'output: rmarkdown::html_document
vignette: >
  %\VignetteIndexEntry{ALPSYSparams}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}' incorrect, because of 'Invalid contents of {}'

Thanks for your suggestions, alternative methods to modify a file header with escape characters welcome.


Solution

  • Instead of modifying header, as a workaround I made two Rmarkdown files with different headers, and used child chunck option to insert the same Markdown body:

    1. Vignette :
    ---
    title: "My package vignette"
    output: rmarkdown::html_document
    vignette: >
      %\VignetteIndexEntry{MyPackage}
      %\VignetteEngine{knitr::rmarkdown}
      %\VignetteEncoding{UTF-8}
    ---
    
    ```{r child=here::here('data/MyPackageVignetteBody.Rmd')}
    
    ```
    
    1. Fully featured Markdown :
    ---
    title: "My package fully featured Markdown"
    output: 
      html_document:
        toc: true
        toc_float: true
    ---
    
    ```{r child=here::here('data/MyPackageVignetteBody.Rmd')}
    
    ```