Search code examples
rr-markdownpandocbookdown

Remove colon in figure caption using pandoc and bookdown in R Markdown


I am changing the font of a figure caption in my R Markdown and am using bookdown and pandoc to do so. My question is closely related to: How to change the figure caption format in bookdown?. I was able to get correct figure numbering and was able to alter the format of the "Figure 1" portion of the caption. However, I cannot figure out how to remove the colon in the output (i.e., "Figure 1:. ").

Minimal Example

Pandoc Function (taken from here)

function Image (img)
  img.caption[1] = pandoc.Strong(img.caption[1])
  img.caption[3] = pandoc.Strong(img.caption[3])
  img.caption[4] = pandoc.Strong(".  ")
  return img
end

To use function Image in the R Markdown, save the file as "figure_caption_patch.lua", which will be called in pandoc_args in the YAML metadata.

R Markdown

---
title: Hello World
author: "Somebody"
output:
  bookdown::word_document2:
    fig_caption: yes
    number_sections: FALSE
    pandoc_args: ["--lua-filter", "figure_caption_patch.lua"]

---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```    

# Test
Some text (Figure \@ref(fig:Xray)). Some text followed by a figure:

```{r Xray, fig.cap="Single-crystal X-ray structure of some text", echo=FALSE}
plot(cars)
```

Output

Figure 1:. This is a caption.

Desired Output

Figure 1. This is a caption.

In the pandoc function, I tried to subset the string of img.caption[3], but it did not work. I tried the following:

img.caption[3] = pandoc.Strong(string.sub(img.caption[3], 1, 1))

I know that if I was using R, then I could do something like:

a = c("words", "again")
substring(a, 1, 1)[1]

#output
[1] "w"

But unsure, how to do this with pandoc.


Solution

  • Looks like there was a change in rmarkdown which adds a colon by default. Also the reason why the answer in the linked post does not work anymore. For more on this and a solution see https://community.rstudio.com/t/how-to-change-the-figure-table-caption-style-in-bookdown/110397.

    Besides the solution offered there you could achieve your desired result by replacing the colon by a dot. Adapting the lua filter provided by https://stackoverflow.com/a/59301855/12993861 this could done like so:

    function Image (img)
      img.caption[1] = pandoc.Strong(img.caption[1])
      img.caption[3] = pandoc.Strong(pandoc.Str(string.gsub(img.caption[3].text, ":", ".")))
      return img
    end
    

    enter image description here