RMarkdown 内联代码格式

RMarkdown Inline Code Format

我正在阅读 ISL 与 R 中的机器学习相关的内容

我真的很喜欢这本书的布局方式,特别是在作者引用内联代码或库的地方 library(MASS)

有谁知道使用 R Markdown 是否可以达到相同的效果,即当我在论文中引用它时,将 MASS 关键字设为棕色?当我在 R Markdown 文档中谈论它们时,我想对数据框中的列进行颜色编码。当你把它编成 HTML 文档时,它提供了很好的格式,但是当我把它编成 MS Word 时,它似乎只是改变了字体类型

谢谢

我想出了一个解决方案,我认为它可以解决您的问题。本质上,因为内联源代码获得与代码块相同的样式标签,所以您对 SourceCode 所做的任何更改都将应用于两个块,我认为这不是您想要的。相反,需要有一种方法来仅针对内联代码,这在 rmarkdown 中似乎是不可能的。相反,我选择做的是获取生成的 .docx 文件,将其转换为 .zip 文件,然后修改包含所有数据的 .xml 文件。它将新样式应用于内联源代码文本,然后可以在您的 MS Word 模板中对其进行修改。这是代码:

format_inline_code = function(fpath) {
  if (!tools::file_ext(fpath) == "docx") stop("File must be a .docx file...")
  cur_dir = getwd()
  .dir = dirname(fpath)
  setwd(.dir)
  out = gsub("docx$", "zip", fpath)

  # Convert to zip file
  file.rename(fpath, out)

  # Extract files
  unzip(out, exdir=".")

  # Read in document.xml
  xml = readr::read_lines("word/document.xml")

  # Replace styling
  # VerbatimChar didn't appear to the style that was applied in Word, nor was
  # it present to be styled. VerbatimStringTok was though.
  xml = sapply(xml, function(line) gsub("VerbatimChar", "VerbatimStringTok", line))

  # Save document.xml
  readr::write_lines(xml, "word/document.xml")

  # Zip files
  .files = c("_rels", "docProps", "word", "[Content_Types].xml")
  zip(zipfile=out, files=.files)

  # Convert to docx
  file.rename(out, fpath)

  # Remove the folders extracted from zip
  sapply(.files, unlink, recursive=TRUE)

  setwd(cur_dir)
}

您要在 MS Word 模板中修改的样式是 VerbatimStringTok。希望对您有所帮助!