You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RMD代码块添加行号失败求助:attr.source='.numberLines'无效

解决R Markdown代码块行号不显示的问题

方案一:使用bookdown扩展输出格式

attr.source='.numberLines'是bookdown对knitr的扩展功能,普通html_document等输出格式不支持该参数。只需将输出格式替换为bookdown对应的版本即可:

  1. 修改YAML头部的输出配置:
---
title: "example"
author: "plover"
date:  '2022-12-29. Version: `r Sys.Date()`'
output:
  bookdown::html_document2:
    code_folding: show
    highlight: tango
    number_sections: false
    df_print: kable
    theme: flatly
    toc: yes
    toc_float: yes
    toc_depth: '3'
  bookdown::word_document2:
    toc: no
  bookdown::pdf_document2:
    toc: yes
---
  1. 单代码块启用行号:保留原代码块的attr.source = '.numberLines'参数即可,例如:
d <-3+1
e <-4+2
f = d + e
  1. 全局启用行号:在setup代码块中添加全局设置,所有代码块自动显示行号:
knitr::opts_chunk$set(echo = TRUE, attr.source = '.numberLines')

方案二:普通HTML输出自定义实现行号(无需bookdown)

若不想依赖bookdown,可通过自定义CSS和JavaScript实现行号:

  1. 在YAML头部添加自定义CSS引用:
output:
  html_document:
    # 原有的其他配置保留
    css: code-line-numbers.css
  1. 创建code-line-numbers.css文件,写入以下样式:
pre.numbered-code code > span.line {
  display: inline-block;
}
pre.numbered-code code > span.line:before {
  content: attr(data-line);
  display: inline-block;
  width: 2em;
  margin-right: 1em;
  text-align: right;
  color: #999;
  user-select: none;
}
  1. 在文档末尾添加脚本代码块,自动给R代码块添加行号:
htmltools::tags$script(HTML("
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('pre.r').forEach(function(preBlock) {
    preBlock.classList.add('numbered-code');
    const code = preBlock.querySelector('code');
    const lines = code.innerHTML.split('\\n');
    code.innerHTML = lines.map((line, idx) => 
      `<span class=\"line\" data-line=\"${idx + 1}\">${line}</span>`
    ).join('\\n');
  });
});
"))

方案三:PDF输出的行号设置

对于PDF输出,除了使用bookdown::pdf_document2外,还可以直接在代码块中使用class.source = 'numberLines'(效果等同于attr.source='.numberLines'):

g <-3+1
h <-4+2
i = g + h

内容的提问来源于stack exchange,提问作者plover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 21:25:33