如何避免RMarkdown html_fragment输出自动换行问题
问题现象
2022年1月使用RMarkdown生成html_fragment时,输出的HTML中每个<p>标签内容都是单行长文本;现在运行完全相同的代码,<p>标签内的文本会在70-100字符处自动插入换行符,导致内容跨行,示例如下:
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
这种换行导致后续依赖单行<p>内容的流程出错,尝试设置opt_chunks$set(width)无效,因为该参数仅影响代码块输出,不作用于纯文本段落。
根因分析
问题源于pandoc版本更新:RMarkdown依赖pandoc处理文档转换,早期pandoc默认不对文本进行自动换行(wrap=none),但后续版本(大致从2.14.x开始)将默认换行策略改为auto,会自动将长文本按约80字符宽度换行。
解决方法
通过指定pandoc参数强制关闭自动换行,即可恢复单行输出,有两种实现方式:
方式1:修改RMarkdown的YAML配置
直接在temp.Rmd的输出配置中添加pandoc参数:
--- title: Demo output: html_fragment: self_contained: false pandoc_args: ["--wrap=none"] --- Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
方式2:在render函数中传递参数
如果不想修改Rmd文件,可直接在渲染函数中指定参数:
rmarkdown::render(input = 'code/temp.Rmd', output_file = 'linereturnproblem.html', output_dir = 'results/messages', encoding="UTF-8", quiet = TRUE, pandoc_args = "--wrap=none")
两种方式都会强制pandoc不自动换行,确保<p>标签内的内容保持为单行。
内容的提问来源于stack exchange,提问作者Simon Gillings

