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

LaTeX代码块行号置于灰色框内及代码字号调整问题

解决方案

1. 让行号纳入灰色背景框内

问题根源在于默认背景框的左边界没有覆盖行号区域,调整以下两个参数即可解决:

  • 新增xleftmargin参数,设置合适的值(比如2em)让背景框向左延伸,覆盖行号位置
  • 调整numbersep参数(比如改为1em),缩小行号与代码的间距,避免背景框内出现过多空白

2. 调大代码块内的字号

修改basicstyle中的字号命令,把原配置里的\footnotesize换成更大的字号(比如\small、\normalsize,按需选择)即可。

修改后的完整配置代码

\usepackage{listings}
\usepackage{xcolor}  % 补全你原代码中遗漏的反斜杠

\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}

\lstdefinestyle{mystyle}{
    backgroundcolor=\color{backcolour},   
    commentstyle=\color{codegreen},
    keywordstyle=\color{magenta},
    numberstyle=\small\color{codegray},
    stringstyle=\color{codepurple},
    basicstyle=\ttfamily\small,  % 将字号从footnotesize改为small,按需可换成normalsize
    breakatwhitespace=false,         
    breaklines=true,                 
    captionpos=b,                    
    keepspaces=true,                 
    numbers=left,                    
    numbersep=1em,  % 缩小行号与代码的间距
    xleftmargin=2em,  % 扩展背景框左边界,覆盖行号区域
    frame=lines,
    showspaces=false,                
    showstringspaces=false,
    showtabs=false,                   
    tabsize=2
}

\lstset{style=mystyle}

关键参数说明

  • xleftmargin=2em:强制背景框向左扩展,确保行号处于灰色背景内部
  • numbersep=1em:优化行号与代码的间距,让整体排版更紧凑协调
  • basicstyle=\ttfamily\small:直接提升代码字号,若需要更大字体可替换为\normalsize或\large

内容的提问来源于stack exchange,提问作者Jennifer M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:01:02