Rmarkdown:markdown语法附带的交叉引用图像

问题描述

我想交叉引用我使用markdown ![caption with spaces](path/to/image.png)语法包含的图像。

我希望能够将此图片作为\@ref(fig:caption-with-spaces)进行交叉引用。

我正在使用bookdown::pdf_document2

这可能吗?

解决方法

据我所知,标签不能粘贴到markdown ![caption](path/to/image)语法附带的图像上。

这给您两个选择:

  1. 使用LaTeX的\includegraphics命令。
  2. 使用编织器的include_graphics函数。

LaTeX解决方案如下所示:

\begin{figure}
   \includegraphics{path/to/picture.png}
   \caption{Caption with spaces}
   \label{fig:example}
\end{figure}

编织器解决方案看起来像

```{r,fig.cap = "Caption with spaces",label="example"}
knitr::include_graphics("path/to/picture.png")
```

使用这两种解决方案,您都可以使用\ref{fig:example}交叉引用生成的图像。

,

R Markdown通过R生成图形时会添加图形ID,但不能用于纯Markdown图像。在这种情况下,您可以自己添加一个ID:

![Caption with spaces](path/to/pictures.png){#fig:caption-with-spaces}

该ID可以自由选择,但应以fig:开头。


如果您希望将所有内容保存在纯Markdown中,但又不想手动添加标识符,则可以使用pandoc Lua filter

local stringify = (require 'pandoc.utils').stringify
function Image (img)
  if img.identifier == '' then
    img.identifier = 'fig:' .. stringify(img.caption):gsub('%s','-'):lower()
    return img
  end
end

通过在输出设置中添加一个pandoc_args参数来使用:

output:
  bookdown::pdf_document2:
    pandoc_args: ['--lua-filter','auto-image-ids.lua']