yihui / bookdown-crc

A minimal example of using bookdown to write a book for Chapman & Hall/CRC
https://yihui.name/en/2018/08/bookdown-crc/
MIT License
72 stars 66 forks source link

fig.cap markdown isn't parsed when out.width is specified. #3

Closed cpsievert closed 4 years ago

cpsievert commented 5 years ago

To replicate, put some markdown in this fig.cap.

https://github.com/yihui/bookdown-crc/blob/f91226b1df87164c5030c9f51197df0ce920596a/01-introduction.Rmd#L9-L12

For example, "**Hello** world!" outputs "**Hello** world!"

Interestingly, if you remove the out.width chunk option, it works as expected.

cpsievert commented 5 years ago

Oh, another thing, the markdown is always parsed for HTML output, but this problem happens when you do:

bookdown::render_book("index.Rmd", "bookdown::pdf_book")
yihui commented 5 years ago

You have to use text references: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html#text-references

cpsievert commented 5 years ago

Great, this seems to fix a lot of the issues I was seeing, thanks!

Could you provide some intuition as why this is necessary? Even if it's just a useful workaround? Having a comment about this somewhere (either in the publishing section of the bookdown book or in this repo) would have saved me lots of time.

yihui commented 5 years ago

From the book:

[...] It is also useful when these captions contain special HTML or LaTeX characters, e.g., if the figure caption contains an underscore, it works in the HTML output but may not work in LaTeX output because the underscore must be escaped in LaTeX.

The text can contain anything that Markdown supports [...]

It is necessary to use a text reference in your case because your caption is not "plain-text": it contains formatting (with Markdown syntax). When out.width is used, knitr switches to hook_plot_tex to generate LaTeX code for graphics (i.e. the \begin{figure} \includegraphics{} \caption{} stuff), and Pandoc doesn't recognize Markdown in \caption{}. Without out.width, it generates Markdown ![](), and Pandoc can recognize Markdown in the caption [].

In short, you can only put the caption in fig.cap if the caption is not plain plain-text without any special characters in any languages. In other cases, it is only safe to use text references.